Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Git Tips: Revert with a new commit

DZone's Guide to

Git Tips: Revert with a new commit

· DevOps Zone ·
Free Resource

Monitor your CI/CD pipelines end-to-end with Hygieia, an open source dashboard from Capital One.

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.

Track and monitor your entire CI/CD pipeline on a single pane of glass. Hygieia is an open source, visual dashboard for keeping CI/CD pipelines green.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}