Undo – remove a commit and retain the changes to files

Instead of performing the hard reset and thereby losing all the changes the commit introduced, the reset can be performed so that the changes are retained in the working directory.

Getting ready

We'll again 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.

You can make a fresh clone as follows:

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

You 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. First, we'll check whether we have made no changes to files in the working tree (just for the clarity of the example) and the history of the repository:
    $ 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'll undo the commit and retain the changes introduced in the working tree:
    $ git reset --mixed 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)
    
    Untracked files:
      (use "git add <file>..." to include in what will be committed)
    
        HelloWorld.java
        Makefile
    
    nothing added to commit but untracked files present (use "git add" to track)
    

We can see that our commit is undone, but the changes to the file are preserved in the working tree, so more work can be done in order to create a proper commit.

How it works…

From the parent commit pointed to by the commit at HEAD, Git resets the branch pointer and HEAD to point to the parent commit. The staging area is reset, but the working tree is kept as it was before the reset, so the files affected by the undone commit will be in the modified state. The following figure depicts this:

How it works…

Tip

The --mixed option is the default behavior of git reset, so it can be omitted:

git reset HEAD^
..................Content has been hidden....................

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