How Git stores your commits

· 3 min read

#how-it-works#git

Git is a content-addressable filesystem: it stores everything as objects named after their contents. The idea to keep: a commit does not copy your project, it points at a snapshot by hash.

The short version

Git uses three kinds of object. A blob holds the contents of a file. A tree holds a list of file names and modes, each with a reference to a blob or to another tree. A commit points at the top-level tree of the project at that moment, plus its parent commit, the author and the message. Every object is named by the SHA-1 of its contents, so it cannot be changed: a changed file becomes a new object.

How a Git commit points at a tree, a blob and its parent Commit C2 points at a tree, and the tree points at a blob that holds file contents. A dashed arrow from commit C2 points at commit C1, its parent. commit C2 tree, parent, message tree names and hashes blob file contents commit C1 the parent 1 2 3 parent Each box is named by the SHA-1 of its own contents.
Arrows 1 and 2 follow the snapshot down to the file contents; the dashed arrow 3 links the commit to the one before it.

Step by step

  1. Git adds a short header (type and size) to the file contents and computes the SHA-1 of the whole. That hash is the object's name.
  2. It compresses the object with zlib and writes it under .git/objects: the first two characters of the hash are the folder, the other 38 are the file name.
  3. A tree object lists names, modes and hashes of the blobs and subtrees in a folder.
  4. A commit stores the hash of the top-level tree, the hash of its parent commit, the author and the message. The first commit has no parent.
  5. Change one line and the blob gets a new hash, so the tree that lists it does too, and so does the next commit. Old objects stay.

Why it matters

Identical content gets an identical name, so Git has no reason to keep a second copy of a file you did not touch. That is my inference from the definition, not a sentence in the docs. It also explains why history is stable: older commits are never edited, only followed by new ones.

Sources