Skip to content

lab 25 Git Internals:
Working directly with Git Objects

Goals

Now let’s use some tools to probe git objects directly.

Finding the Latest Commit

Execute:

git hist --max-count=1

This should show the latest commit made in the repository. The SHA1 hash on your system is probably different from what is on mine, but you should see something like this.

Output:

$ git hist --max-count=1
* 0022837 2022-10-24 | Added a Rakefile. (HEAD -> main) [Jim Weirich]

Dumping the Latest Commit

Using the SHA1 hash from the commit listed above …

Execute:

git cat-file -t <hash>
git cat-file -p <hash>

Here’s my output …

Output:

$ git cat-file -t 0022837
commit
$ git cat-file -p 0022837
tree 411af6240f8f5ada935b2116bb8c138b85bd6481
parent 3172288d9193164b244204af3021f0ee417f75f7
author Jim Weirich <jim (at) edgecase.com> 1666638121 +0000
committer Jim Weirich <jim (at) edgecase.com> 1666638121 +0000

Added a Rakefile.

NOTE: If you defined the ‘type’ and ‘dump’ aliases from the aliases lab, then you can type git type and git dump rather than the longer cat-file commands (which I never remember).

This is the dump of the commit object that is at the head of the main branch. It looks a lot like the commit object from the presentation earlier.

Finding the Tree

We can dump the directory tree referenced in the commit. This should be a description of the (top level) files in our project (for that commit). Use the SHA1 hash from the “tree” line listed above.

Execute:

git cat-file -p <treehash>

Here’s what my tree looks like…

Output:

$ git cat-file -p 411af62
100644 blob 28e0e9d6ea7e25f35ec64a43f569b550e8386f90	Rakefile
040000 tree 35847f779c876b264c14646918c15b0d70e0fc3f	lib

Yep, I see the Rakefile and the lib directory.

Dumping the lib directory

Execute:

git cat-file -p <libhash>

Output:

$ git cat-file -p 35847f7
100644 blob 3a2a15c835fe07fdadc263380748ea53e2818b4e	hello.rb

There’s the hello.rb file.

Dumping the hello.rb file

Execute:

git cat-file -p <rbhash>

Output:

$ git cat-file -p 3a2a15c
# Default is World
# Author: Jim Weirich (jim@somewhere.com)
names = ARGV || ["World"]

puts "Hello, #{names.join(" ")}!"
puts "You have #{names.length} names!"

There you have it. We’ve dumped commit objects, tree objects and blob objects directly from the git repository. That’s all there is to it, blobs, trees and commits.

Explore On You Own

Explore the git repo manually on your own. See if you can find the original hello.rb file from the very first commit by manually following the SHA1 hash references starting in the latest commit.