Inspect a Previous Commit
In this section, we will inspect a previous commit, performing the "time machine" function of Git.
The files reflect where HEAD points toYour location on the commit history is indicated by a reference called the HEAD pointer. The HEAD always points to a commit. Your working directory reflects the status of that commit.
The commit history is like an audio tape. The HEAD pointer is similar to the playhead of the tape machine, indicating the current position. Normally, the HEAD is point to the tip (last commit) of a branch, because that's where the next commit will follow right after. When we inspect a previous commit, Git moves the HEAD to somewhere in the middle of the tape. This is called an detached HEAD.
We will inspect a previous commit by detaching the HEAD. When the HEAD points to a different commit, the files in the working directory will change accordingly. This is automatically coordinated by Git, like magic.
Steps
Look at the commit history. Each commit has a corresponding HASH value.
Get the HASH for the commit you want to inspect
Go to a previous commit:
git checkout
that HASHGet back to the latest commit:
git checkout
the branch name
In action
Out current myfile.py
looks like this
The commit history:
Say we want to jump to the second commit of "Print out the mean". Grab the HASH (actually the first 6 digits will be distinctive enough), and git checkout
that commit.
Notice it's now in a detached HEAD state. This means the HEAD moved away from the last commit. If we look at myfile.py
now, it will reflect the content at that snapshot.
Note that the last line print(arr.std())
is not there.
Finally, we get back to the latest commit. If you check out the branch name, Git will move to the latest commit.
The last line is back in myfile.py
.
Discussion
Can you make new commits with a detached HEAD?
You can make new commits. It's best to create a new branch for it. Otherwise once you move back to the original branch, these commits will be orphaned.
How do I find out the branch name?
When you do git log
, it shows which branch the HEAD is pointing to.
Here it's called master
, which is the default branch name in Git.
Alternatively, use git branch
. More on that in the branch section.
Last updated