Undo – remove a commit and retain the changes in the staging area

Of course, it is also possible to undo the commit, but keep the changes to the files in the index or the staging area so that you are ready to recreate the commit with, for example, some minor modifications.

Getting ready

We'll still use the example of the hello world repository. Make a fresh clone of the repository, or reset the master branch if you have already cloned one.

Create a fresh clone as follows:

$ git clone https://github.com/dvaske/hello_world_cookbook.git
$ cd hello_world_cookbook

We can reset the existing clone as follows:

$ cd hello_world_cookbook
$ git checkout master
$ git reset --hard origin master
HEAD is now at 3061dc6 Adds Java version of 'hello world'

How to do it...

  1. Check whether we have no files in the modified state and check the log:
    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    
    nothing to commit, working directory clean
    
    $ git log --oneline
    3061dc6 Adds Java version of 'hello world'
    9c7532f Fixes compiler warnings
    5b5d692 Initial commit, K&R hello world
    
  2. Now, we can undo the commit, while retaining the changes in the index:
    $ git reset --soft HEAD^
    
    $ git log --oneline
    9c7532f Fixes compiler warnings
    5b5d692 Initial commit, K&R hello world
    
    $ git status
    On branch master
    Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
      (use "git pull" to update your local branch)
    
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
        new file:   HelloWorld.java
        new file:   Makefile
    

You can now do minor (or major) changes to the files you need, add them to the staging area, and create a new commit.

How it works…

Again, Git will reset the branch pointer and HEAD to point to the previous commit. However, with the --soft option, the index and working directories are not reset, that is, they have the same state just as they had before we created the now undone commit.

The following figure shows the Git state before and after the undo:

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset