Exploring History
Overview
Teaching: 25 min
Exercises: 0 minQuestions
How can I identify old versions of files?
How do I review my changes?
How can I recover old versions of files?
Objectives
Explain what the HEAD of a repository is and how to use it.
Identify and use Git commit numbers.
Compare various versions of tracked files.
Restore old versions of files.
As we saw in the previous episode, we can refer to commits by their
identifiers. You can refer to the most recent commit of the working
directory by using the identifier HEAD
.
We can track our progress by looking, so let’s do that using our HEAD
s. Before we start,
let’s make a change to for-loop.sh
, adding commentary using the #.
$ nano for-loop.sh
$ cat for-loop.sh
# for-loop example
# we will be creating a program that "deals" values at random
#!/bin/bash
cards=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10)
echo "how many cards would you like?"
read value
for i in $(seq 1 $value);
do echo ${cards[RANDOM%${#cards[@]}]};
done
# `${cards[RANDOM%${#cards[@]}]}` command randomly selects values from `cards`
Now, let’s see what we get.
$ git diff HEAD for-loop.sh
diff --git a/loops/for-loop.sh b/loops/for-loop.sh
index 9dd28bc..8975db5 100644
--- a/loops/for-loop.sh
+++ b/loops/for-loop.sh
@@ -10,3 +10,4 @@ for i in $(seq 1 $value);
do echo ${cards[RANDOM%${#cards[@]}]};
done
+# `${cards[RANDOM%${#cards[@]}]}` command randomly selects values from `cards`
which is the same as what you would get if you leave out HEAD
(try it). The
real goodness in all this is when you can refer to previous commits. We do
that by adding ~1
(where “~” is “tilde”, pronounced [til-duh])
to refer to the commit one before HEAD
.
$ git diff HEAD~1 for-loop.sh
If we want to see the differences between older commits we can use git diff
again, but with the notation HEAD~1
, HEAD~2
, and so on, to refer to them:
$ git diff HEAD~2 for-loop.sh
diff --git a/for-loop.sh b/for-loop.sh
index de9b2a4..8006c63 100644
--- a/for-loop.sh
+++ b/for-loop.sh
@@ -1,2 +1,13 @@
# for-loop example
# we will be creating a program that "deals" values at random
+#!/bin/bash
+cards=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10)
+
+echo "how many cards would you like?"
+read value
+
+for i in $(seq 1 $value);
+do echo ${cards[RANDOM%${#cards[@]}]};
+
+done
+#`${cards[RANDOM%${#cards[@]}]}` command randomly selects values from `cards`
We could also use git show
which shows us what changes we made at an older commit as
well as the commit message, rather than the differences between a commit and our
working directory that we see by using git diff
.
$ git show HEAD~2 for-loop.sh
commit 94456da74c0fd245cadf7b5e35eef29580f53ee5
Author: User <user@ucsb.edu>
Date: Tue Dec 7 15:18:58 2021 -0800
Add in subdir for loops
diff --git a/loops/for-loops.sh b/loops/for-loops.sh
new file mode 100644
index 0000000..e69de29
In this way,
we can build up a chain of commits.
The most recent end of the chain is referred to as HEAD
;
we can refer to previous commits using the ~
notation,
so HEAD~1
means “the previous commit”,
while HEAD~123
goes back 123 commits from where we are now.
We can also refer to commits using
those long strings of digits and letters
that git log
displays.
These are unique IDs for the changes,
and “unique” really does mean unique:
every change to any set of files on any computer
has a unique 40-character identifier.
Our HEAD~2
comment addition was given the ID
7f9e4987af8d390eac5205e9a760e3f72204041c
,
so let’s try this:
$ git diff 94456da74c0fd245cadf7b5e35eef29580f53ee5 for-loop.sh
diff --git a/for-loop.sh b/for-loop.sh
index de9b2a4..8006c63 100644
--- a/for-loop.sh
+++ b/for-loop.sh
@@ -1,2 +1,13 @@
# for-loop example
# we will be creating a program that "deals" values at random
+#!/bin/bash
+cards=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10)
+
+echo "how many cards would you like?"
+read value
+
+for i in $(seq 1 $value);
+do echo ${cards[RANDOM%${#cards[@]}]};
+
+done
+#`${cards[RANDOM%${#cards[@]}]}` command randomly selects values from `cards`
That’s the right answer, but typing out random 40-character strings is annoying, so Git lets us use just the first few characters (typically seven for normal size projects):
$ git diff 94456da for-loop.sh
diff --git a/for-loop.sh b/for-loop.sh
index de9b2a4..8006c63 100644
--- a/for-loop.sh
+++ b/for-loop.sh
@@ -1,2 +1,13 @@
# for-loop example
# we will be creating a program that "deals" values at random
+#!/bin/bash
+cards=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10)
+
+echo "how many cards would you like?"
+read value
+
+for i in $(seq 1 $value);
+do echo ${cards[RANDOM%${#cards[@]}]};
+
+done
+#`${cards[RANDOM%${#cards[@]}]}` command randomly selects values from `cards`
All right! So
we can save changes to files and see what we’ve changed. Now, how
can we restore older versions of things?
Let’s suppose we change our mind about the last update to
for-loop.sh
(the “ill-considered change”).
git status
now tells us that the file has been changed,
but those changes haven’t been staged:
$ git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: for-loop.sh
no changes added to commit (use "git add" and/or "git commit -a")
We can put things back the way they were
by using git checkout
:
$ git checkout HEAD for-loop.sh
$ cat for-loop.sh
# for-loop example
# we will be creating a program that "deals" values at random
#!/bin/bash
cards=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10)
echo "how many cards would you like?"
read value
for i in $(seq 1 $value);
do echo ${cards[RANDOM%${#cards[@]}]};
done
As you might guess from its name,
git checkout
checks out (i.e., restores) an old version of a file.
In this case,
we’re telling Git that we want to recover the version of the file recorded in HEAD
,
which is the last saved commit.
If we want to go back even further,
we can use a commit identifier instead:
$ git checkout 94456da for-loops.sh
$ cat for-loop.sh
$ git status
On branch main
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: for-loop.sh
Notice that the changes are currently in the staging area.
Again, we can put things back the way they were
by using git checkout
:
$ git checkout HEAD for-loop.sh
Don’t Lose Your HEAD
Above we used
$ git checkout 94456da for-loops.sh
to revert
for-loop.sh
to its state after the commit94456da
. But be careful! The commandcheckout
has other important functionalities and Git will misunderstand your intentions if you are not accurate with the typing. For example, if you forgetfor-loop.sh
in the previous command.$ git checkout 94456da
Note: checking out '94456da'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at 94456da
The “detached HEAD” is like “look, but don’t touch” here, so you shouldn’t make any changes in this state. After investigating your repo’s past state, reattach your
HEAD
withgit checkout main
.
It’s important to remember that
we must use the commit number that identifies the state of the repository
before the change we’re trying to undo.
A common mistake is to use the number of
the commit in which we made the change we’re trying to discard.
In the example below, we want to retrieve the state from before the most
recent commit (HEAD~1
), which is commit 94456da
:
So, to put it all together, here’s how Git works in cartoon form:
Simplifying the Common Case
If you read the output of
git status
carefully, you’ll see that it includes this hint:(use "git checkout -- <file>..." to discard changes in working directory)
As it says,
git checkout
without a version identifier restores files to the state saved inHEAD
. The double dash--
is needed to separate the names of the files being recovered from the command itself: without it, Git would try to use the name of the file as the commit identifier.
The fact that files can be reverted one by one tends to change the way people organize their work. If everything is in one large document, it’s hard (but not impossible) to undo changes to the introduction without also undoing changes made later to the conclusion. If the introduction and conclusion are stored in separate files, on the other hand, moving backward and forward in time becomes much easier.
Recovering Older Versions of a File
Jennifer has made changes to the Python script that she has been working on for weeks, and the modifications she made this morning “broke” the script and it no longer runs. She has spent ~ 1hr trying to fix it, with no luck…
Luckily, she has been keeping track of her project’s versions using Git! Which commands below will let her recover the last committed version of her Python script called
data_cruncher.py
?
$ git checkout HEAD
$ git checkout HEAD data_cruncher.py
$ git checkout HEAD~1 data_cruncher.py
$ git checkout <unique ID of last commit> data_cruncher.py
Both 2 and 4
Solution
The answer is (5)-Both 2 and 4.
The
checkout
command restores files from the repository, overwriting the files in your working directory. Answers 2 and 4 both restore the latest version in the repository of the filedata_cruncher.py
. Answer 2 usesHEAD
to indicate the latest, whereas answer 4 uses the unique ID of the last commit, which is whatHEAD
means.Answer 3 gets the version of
data_cruncher.py
from the commit beforeHEAD
, which is NOT what we wanted.Answer 1 can be dangerous! Without a filename,
git checkout
will restore all files in the current directory (and all directories below it) to their state at the commit specified. This command will restoredata_cruncher.py
to the latest commit version, but it will also restore any other files that are changed to that version, erasing any changes you may have made to those files! As discussed above, you are left in a detachedHEAD
state, and you don’t want to be there.
Reverting a Commit
Jennifer is collaborating with colleagues on her Python script. She realizes her last commit to the project’s repository contained an error, and wants to undo it. Jennifer wants to undo correctly so everyone in the project’s repository gets the correct change. The command
git revert [erroneous commit ID]
will create a new commit that reverses the erroneous commit.The command
git revert
is different fromgit checkout [commit ID]
becausegit checkout
returns the files not yet committed within the local repository to a previous state, whereasgit revert
reverses changes committed to the local and project repositories.Below are the right steps and explanations for Jennifer to use
git revert
, what is the missing command?
________ # Look at the git history of the project to find the commit ID
Copy the ID (the first few characters of the ID, e.g. 0b1d055).
git revert [commit ID]
Type in the new commit message.
Save and close
Solution
The command
git log
lists project history with commit IDs.The command
git show HEAD
shows changes made at the latest commit, and lists the commit ID; however, Jennifer should double-check it is the correct commit, and no one else has committed changes to the repository.
Understanding Workflow and History
What is the output of the last command in
$ cd loops $ echo "you can loop through lists and sequences" > notes-for-loop.txt $ git add notes-for-loop.txt $ echo "You can also nest loops inside another." >> notes-for-loop.txt $ git commit -m "More notes on loops" $ git checkout HEAD notes-for-loop.txt $ cat notes-for-loop.txt #this will print the contents
For loops start with `for` and ends with `done`.
you can loop through lists and sequences
For loops start with `for` and ends with `done`. You can loop through lists and sequences.
Error because you have changed notes-for-loop.txt without committing the changes
Solution
The answer is 2.
The command
git add notes-for-loop.txt
places the current version ofnotes-for-loop.txt
into the staging area. The changes to the file from the secondecho
command are only applied to the working copy, not the version in the staging area.So, when
git commit -m "More notes on loops"
is executed, the version ofnotes-for-loop.txt
committed to the repository is the one from the staging area and has only one line.At this time, the working copy still has the second line (and
git status
will show that the file is modified). However,git checkout HEAD notes-for-loop.txt
replaces the working copy with the most recently committed version ofnotes-for-loop.txt
.So,
notes-for-loop.txt
will outputFor loops start with `for` and ends with `done`.
Checking Understanding of
git diff
Consider this command:
git diff HEAD~9 for-loop.sh
. What do you predict this command will do if you execute it? What happens when you do execute it? Why?Try another command,
git diff [ID] for-loop.sh
, where [ID] is replaced with the unique identifier for your most recent commit. What do you think will happen, and what does happen?
Getting Rid of Staged Changes
git checkout
can be used to restore a previous commit when unstaged changes have been made, but will it also work for changes that have been staged but not committed? Make a change tofor-loop.sh
, add that change, and usegit checkout
to see if you can remove your change.
Explore and Summarize Histories
Exploring history is an important part of Git, and often it is a challenge to find the right commit ID, especially if the commit is from several months ago.
Imagine the
shell-scripts
project has more than 50 files. You would like to find a commit that modifies some specific text infor-loop.sh
. When you typegit log
, a very long list appeared. How can you narrow down the search?Recall that the
git diff
command allows us to explore one specific file, e.g.,git diff for-loop.sh
. We can apply a similar idea here.$ git log for-loop.sh
Unfortunately some of these commit messages are very ambiguous, e.g.,
update files
. How can you search through these files?Both
git diff
andgit log
are very useful and they summarize a different part of the history for you. Is it possible to combine both? Let’s try the following:$ git log --patch for-loop.sh
You should get a long list of output, and you should be able to see both commit messages and the difference between each commit.
Question: What does the following command do?
$ git log --patch HEAD~9 *.txt
Key Points
git diff
displays differences between commits.
git checkout
recovers old versions of files.