Video in progress

Strong Middle 🌿 Git

How does Git store a commit internally? How are blob, tree and commit objects linked together?

Git is a content-addressable store: each object is stored under the hash of its contents. A blob is file contents, a tree is a directory (names and references to blobs/trees), and a commit is the root tree, parent commits, the author and a message. The chain of hashes makes history immutable.

📖 Answer

You can look at it yourself:

git cat-file -p HEAD
# tree 8f2c...
# parent 41ab...
# author Aziz <aziz@example.uz> 1730620000 +0500
#
# Hisobot eksporti

git cat-file -p 8f2c      # a tree: each line is mode, type, hash, name
# 100644 blob 9e1d...    pom.xml
# 040000 tree 77aa...    src

Important consequences:

  • A snapshot, not a diff. Each commit shows the state of the whole project. For unchanged files the old blob is reused, so no space is wasted. Git computes the diff at display time.
  • The same content is one blob. If you move a file (rename), no new blob is created; Git also detects a rename afterwards, by similarity.
  • Immutability. If you change a single byte in an old commit, its hash changes, and then the hashes of all commits on top of it. That is why rebase and amend create "new commits".

Objects start out as separate compressed files in .git/objects/, and then git gc packs them into packfiles with delta compression. The hash has historically been SHA-1. Newer Git versions also support SHA-256 repositories, but they are not yet widespread among hosting services.