In Part I, I tried to introduce Git to non-believers who have their brains formatted by CVS. We learned to create a repository and commit files to it. Part II will be very short. We will learn to look at the history of changes made to a file and learn to revive an old version of the file.
Let’s say, that you have a file called test.c. This file has been committed several times in the past. You can look at the history of changes by running this command.
git log test.c
This will display something like this.
commit 9faa6e6d4df82766de1ecc63ff5e79463e21c7cb Author: Bibhas Bhattacharya <firstname.lastname@example.org> Date: Wed Aug 15 10:03:29 2012 -0400 Comments2 commit f8648963ac296d974dedd5530a56a024c495219c Author: Bibhas Bhattacharya <email@example.com> Date: Wed Aug 15 10:01:43 2012 -0400 Comments1
The date and author of every commit made for the file is displayed. In CVS, each commit creates a new version number. In Git, you get a unique key for the commit. This is shown in bold face above. Git generates the key by using SHA-1 hash of the Git tree (something that closely resembles the files and directories as they existed at the time of the commit).
So, anyway, the important thing is that there is no CVS like version number. Every version has a unique key.
Now, let’s say that you made a terrible mistake to the file. Perhaps your cat went in the middle of the night and typed in gibberish to it and saved it. Now what? Well, first we need to find out what has changed since a specific commit. For that, run this command:
git diff 9faa6e6d4df82766de1ecc63ff5e79463e21c7cb test.c
The hash value of the commit you are trying to compare with goes into the command.
This will print out a terrible output that only Martians can understand.
index a4b000a..01dfe10 100644 --- a/src/test.c +++ b/src/test.c @@ -1,2 +1,2 @@ -New line -Line 2 +New line was here +Only a memory 3
Fortunately, git works with many excellent visual diff programs. Most installations probably have vimdiff configured by default. To view the difference in a graphical tool, run this command:
git difftool 9faa6e6d4df82766de1ecc63ff5e79463e21c7cb test.c
To configure a different diff tool, read this article. Right about now, I am starting to miss my Eclipse diff view. Oh, how many times has it come to my aid in times of major distress!
Anyway, getting back to the mischief caused by your cat. We now have to fix the problem. The diff may show the source of the error and you may be able to manually fix the problem. If you must start from scratch, just checkout the older version.
git checkout 9faa6e6d4df82766de1ecc63ff5e79463e21c7cb test.c
This will completely replace the file with the older version.