Amending and Undoing Commits

When commits aren't right, what do we do?

Scenario

Let's assume you're a developer trying to correct a typo or adding missed changes to an ongoing solution. Here's how you can do it:

Step 1 - Make the necessary changes to your files

  • Update the files with the required modifications.

  • Use any text editor or IDE of your choice to make the changes.

Step 2 - Stage the changes

Use the following command to stage the modified files:

git add <file1> <file2> ...

Step 3: Amend the commit

  • To incorporate the changes into the most recent commit, use the following command:

git commit --amend
  • This will open a text editor where you can modify the commit message.

  • Save and close the editor to finalize the amended commit.

Amending a commit creates a new commit with a new commit ID. Therefore, it is recommended to only amend commits that have not been pushed to a remote repository.

Reverting to a Previous Commit

Reverting a commit is useful when you want to undo the changes introduced by a specific commit without removing it from the commit history. There are two primary methods to achieve this: using git revert and using git reset. Let's explore both approaches:

Using git revert

The git revert command creates a new commit that undoes the changes made in a previous commit while keeping the commit history intact.

Step 1: Identify the commit to revert.

  • Use git log to view the commit history and identify the commit hash of the commit you want to revert.

Step 2: Revert the commit.

  • Execute the following command to revert the identified commit:

git revert <commit-hash>
  • Git will create a new commit that undoes the changes introduced by the specified commit.

Using git reset

The git reset command allows you to reset the branch pointer to a previous commit, effectively removing commits from the commit history. This method should be used with caution, as it modifies the commit history.

Step 1: Identify the commit to reset to.

  • Use git log to find the commit hash of the commit you want to reset to.

Step 2: Reset the branch.

  • Execute the following command to reset the branch to the specified commit:

git reset --hard <commit-hash>

This will remove the commits after the specified commit and reset the branch pointer.

Note: When using git reset, be cautious as it discards commits permanently.

It is not recommended to use git reset on commits that have been pushed to a remote repository.

Last updated