Git can add a new commit to reverse the changes done in a specific past commit, called reverting a commit.
When a past commit introduced a bug or an unwanted change, but you do not want to modify that commit — because rewriting history can cause problems if others have already based work on it — you can instead revert that commit.
Reverting creates a new commit that cancels out the changes of the earlier one i.e., Git computes the opposite of the changes introduced by that commit — essentially a reverse diff — and applies it as a new commit on top of the current branch. This way, the problematic changes are reversed while preserving the full history, including the "bad" commit and the "fix".
→
[revert C2]
C2) Scenario You are working with a repo named pioneers, which contains information about computer science pioneers. You discovered that one of the earlier commits mistakenly added information about a fictional character instead of a real CS pioneer.
Target Correct the mistake without rewriting past commits. That is, add a new commit that reverts the offending comment.
Preparation
1 Revert the commit Add Neo.
You can use the git revert <commit> command to revert a commit. In this case, we want to revert the commit that is two commits behind the HEAD.
git revert HEAD~2
What happens next:
- Git prepares a new commit which reverses the target commit
- Git opens your default text editor containing a proposed commit message. You can edit it, or accept the proposed text.
- Once you close the editor, Git will create the new commit.
In the revision graph, right-click on the commit you want to revert, and choose Reverse commit...
2 Verify the revert commit has been added e.g.,
git log --oneline --decorate
604b770 (HEAD -> main) Revert "Add Neo"
682fc8d Add Hopper
268ceb1 Add Turing
6fb6bd8 Add Neo
done!
A revert can result in a conflict, if the new changes done to reverse the previous commit conflict with the changes done in other more recent commits. Then, you need to resolve the conflict before the revert operation can proceed. Conflict resolution is covered in a later topic.