Our Story

Ceremony

Just Married

Git Tips: Revert with a new commit

by - March 03, 2014

Sometimes you want to set the state of your project back to a previous commit, but keep the history of all the preceding changes. You want to make a commit that reverses all the changes between your previous commit and the current HEAD.

First let’s create a new branch, ‘revert-branch’, from the commit we want to revert to. In this example we’re just reverting to the previous commit (I’m assuming that we’re currently in branch ‘master’), but this can be any commit:

git branch revert-branch HEAD^







Next checkout your new branch:




git checkout revert-branch







Now the neat trick: soft reset the HEAD of the new branch to master. A soft reset changes the state of HEAD, but doesn’t affect the working tree or index:




git reset --soft master





Now if we do a git status, we’ll see that the index reports the reverse of the commit(s) that we want to revert. In this case I want to back out of the addition of ‘second.txt’, but this could be a far more complex set of changes:




$ git status
# On branch revert-branch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: second.txt
#







Now I can commit this ‘reversal’:




git commit -m "reverted to initial state."



Test and merge revert-branch into master. Nice.

You May Also Like

0 comments