Git for non-programmers 3

Last time we finished with a change only in the working tree, one which I don’t want to keep. It is possible to just manually revert your changes but it is much quicker to use git.

Reverting changes in the working tree

In this instance we will use git checkout to ‘checkout’ the version of universe.py in the index like so:

git checkout -- universe.py

This can also be done with git restore:

git restore universe.py

We can also refer to a directory to checkout everything below that directory, for example, to checkout the whole tree from the root of your project:

git checkout -- .

Reverting changes in the index

$ git status
HEAD detached at 73ae532
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	new file:   pi.py

The above example shows that I have added a new file pi.py so that it is ready to be committed, as you can see we can ‘unstage’ the file with git restore:

git restore --staged pi.py

Reverting commits

Generally commits should not be reverted if they have been shared as everyone else that has a copy of the commit would have to revert it as well but if a commit is just in your local copy it is possible to undo with git reset.

$ git log
commit 3f723bf9e59b589d0d462ca6d3d94616b80ff641 (HEAD)
Author: Adam Bark
Date:   Fri Jul 31 13:52:59 2020 -0500

    Add a module to print pi

commit 73ae5322e3073a20758f7d7c98b8b3955ec3a4ea
Author: Adam Bark
Date:   Sun Jul 14 17:07:47 2019 -0500

    Initial commit
git reset HEAD^
$ git log
commit 73ae5322e3073a20758f7d7c98b8b3955ec3a4ea (HEAD)
Author: Adam Bark
Date:   Sun Jul 14 17:07:47 2019 -0500

    Initial commit

Here I use the alias HEAD^ to denote the commit prior to HEAD (for more on HEAD see the previous post) but any commit can be referenced as the new HEAD. This form of the command leaves the working tree in place but resets the index to the state of the selected commit. If you also want the working tree to be reset use

git reset --hard HEAD^

Conclusion

Now you know a few ways to get rid of changes that you don’t want any more. There’s a bit more scope, this time around, to get in to a state that you’re not sure how to get out of (that’s not to say it’s impossible but git is a complex tool and this post could get very long) so feel free to experiment in a new clone like so:

git clone . ../my-test-universe

Here the first argument is the repository you want to clone so this is how you would clone from the root of your code base. The second argument is the directory you want to clone into. Now you can pick one and run any commands you like safe in the knowledge that you have a backup.

git 

See also