“undo”, “reset”, “revert” – ah English! Perhaps the author of The Giver used Git in the past, since one of their rules was “use precision of language.”
What do we mean by “undo a previous commit?” Let’s say we had 3 commits A, B, and C. And we realize ‘B’ was a mistake. Perhaps we changed a color to red, and it should go back to white. But we don’t want to pretend that ‘B’ never happened. That would mean modifying Git history, and Git really hates changing history if you have the repo shared with others.
So yeah, you could rewrite the code to manually undo the changes introduced in ‘B’, or you could let Git do that for you by running `git revert <commitID>`
As you see in the above graph, using this git visualization tool, a new commit is made with the changes introduced from ‘A’ removed. The take home message is that a new commit is made, instead of “commit A” vanishing.
I like this Stack Overflow answer:
If I found B I committed before is wrong, and I want to “undo” its change,
git-revert-ing B will cause:
A <- B <- C <- B' ^ HEAD
B'is reversing the change done in B
Now to the command line to see this in action!
Say you’ve added three files: A.txt, B.txt, and C.txt for commits A, B, and C, respectively. (One day, I’m going to blog about a list of files being out of order, “dis-respectively “)
We want to “undo” the changes introduced in B.
If you are following along at home, let’s pause for a second and make sure your core.editor is configured to use your preferred text editor.
The read between the lines: you’ll want to know how to exit whatever editor comes up.
Right now I’m using notepad to give me a fighting chance instead of the vi editor, aka the destoryer of CS careers. YMMV, so check out this GitHub help article on setting up an preferred text editor. Hint: it’s `git config –global core.editor notepad` if you want to use notepad across all your repos.
Okay with that taken care of, let’s do the revert. We want to “undo” the B.txt commit, so let’s party w `git revert <commit id for B>` and suddenly a wild notepad appears!
Since I’m cool with the default commit message “Revert ‘B’ for this demo (remember, git revert creates a new commit so it has to get a commit message from you), simply close notepad (File – Exit or ‘x’).
Now if you do your git log –oneline, you’ll notice the new commit. If you do a `ls` or `dir` and the git-equivalent to see what files git is tracking `git ls-files`, you’ll see that B.txt is no where to be found.
Once again to recap what we did. We could have simply deleted the file B.txt and committed those changes. But for a more complex scenario where you need to remove a feature that consists of more than a single file or line change, you should consider using `git revert`.