How Git stores your commits
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.
Step by step
- 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.
- 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. - A tree object lists names, modes and hashes of the blobs and subtrees in a folder.
- 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.
- 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
- Git Internals - Git Objects — Pro Git book — content-addressable filesystem, blob, tree and commit objects, parent commits, object path from the SHA-1, header, hash and zlib steps
- gitglossary — Git documentation — definitions of object (named by the SHA-1 of its contents, cannot be changed), blob, tree and commit