I used to think revert would get you back to the state when a given commit was submitted. It does not. Instead it simply undo’s the given commit. To do the former, you have to use reset instead.
git reset --hard HEAD~5
Will take you back to the state of the repo 5 commits ago. If you have uncommited work you want left alone then use
--soft instead of
git revert undo’s the commit who’s hash was given, and makes new commit with the changes that undo that given commit.
If it’s a merged commit then you have to use the
-m option (for merge) along with either a 1 or a 2. 1, meaning you want to take it back to the state of the remote parent. 2 meaning you want to take it back to the state of your local parent. (I usually use 1. I trust remote more than myself)
If anything goes wrong when you try to revert use
git cherry-pick --abort and try again.
Sometimes you may have to merge. If anything goes wrong with the merge you can use
git merge --abort and start over.
So let’s go through this with a realistic (but hopefully not common) scenario. Let’s say some bad code went live. You’re on your site and notice something terribly wrong. Don’t fret! Let’s say you did a recent push and you think you know which commit has the problem, but don’t want to take the time to debug it while your live app is in a bad state. Here’s what you do (assuming you are up-to-date on your master branch).
$ get checkout -b revert-branch
$ get revert
$ git push origin revert-branch
Above we are checking out a new branch, undoing the bad commit, and pushing the branch up. You can find the hash of the bad commit on Github or with
git revert will put you in your default text editor with the commit message “revert “, so all you have to do is save and quit (:wq if the editor is vi or vim) and you’re ready to push up. Then pull the pr in and update the site and you’re in the clear!
That’s what you do if you’ve royally screwed up live, but sometimes you mess up your local branch beyond repair and you just want to start over with whatever is in the remote master branch. If that’s the case run the below command.
git reset --hard origin/master
that will simply replace your current branch with the origin/master branch. If your remote is named something else besides origin, such as upstream then instead of origin/master, you’d use upstream/master. You can check double check what your remote is named with
git remote -v.