Sub topic 3
Git as a content-addressable object store
This chapter assumes you can use init, add, commit, log and branch, and that you are comfortable in a Unix-style shell. It also assumes you know that a hash function turns any input into a short, fixed-size fingerprint. The chapter explains the idea that underlies everything else in this tutorial: Git stores your history as a database of objects, and each object is named by a hash of its own content.
What "content-addressable" means
Most storage systems are location-addressable. You pick a name or a path, such as notes/todo.txt, and the system returns whatever is stored there. You can overwrite the contents without changing the name.
A content-addressable store reverses this. The address is computed from the data. You give the store some content, and it returns a key derived from that content. To read the data back, you present the key.
Git's object database, under .git/objects, works this way. It behaves like a key-value store with these properties:
- The key is derived from the value. Nobody chooses an object's name. Git computes it.
- Identical content gets one key. Storing the same bytes twice produces one object. Git deduplicates automatically.
- Objects are immutable. If you change one byte, the content hashes to a different key, so you have created a new object. The old one is unchanged.
- The key verifies the data. Hashing an object's content again and comparing the result to its name detects corruption.
git fsckrelies on this.
How an object ID is computed
An object ID is not the hash of the raw content alone. Git builds a byte string made of three parts, in this order:
- The object type:
blob,tree,commitortag. - A space, then the content length in bytes written as decimal text, then a NUL byte (
\0). - The content itself.
Git hashes that whole string. For a file containing the six bytes hello\n, the string is blob 6\0hello\n. You can reproduce Git's answer without Git:
printf 'blob 6\0hello\n' | sha1sum
echo 'hello' | git hash-object --stdinBoth commands print ce013625030ba8dba906f756967f9e9ca394464a. The git hash-object command is covered in its own chapter. Here it only confirms the formula. The same calculation in Python looks like this:
import hashlib
def object_id(kind: bytes, content: bytes) -> str:
header = b"%s %d\0" % (kind, len(content))
return hashlib.sha1(header + content).hexdigest()
print(object_id(b"blob", b"hello\n"))The header serves two purposes. It binds the type into the ID, so a blob and a commit with identical content bytes still get different IDs. It also binds the length, which guards against some malformed or truncated inputs.
From ID to file on disk
When Git stores an object loosely, it compresses the header and content together with zlib. It writes the result to a file whose path comes from the ID. The first two hex digits become a directory name, and the remaining digits become the file name:
.git/objects/ce/013625030ba8dba906f756967f9e9ca394464aSplitting off two digits spreads objects across at most 256 subdirectories. This keeps any single directory from growing huge on filesystems that handle large directories poorly.
Compression happens after hashing. The ID depends only on the uncompressed header and content. The same object therefore has the same ID whether it is stored loose, inside a packfile, or on another machine.
The four object types
The store holds exactly four kinds of object. Later chapters take each in detail, so this is only the map:
| Type | Holds | Refers to |
|---|---|---|
| blob | The bytes of one file, with no name | Nothing |
| tree | A directory listing of names, modes and IDs | Blobs and other trees |
| commit | A tree ID, parent commit IDs, author, committer and message | One tree and zero or more commits |
| tag | An annotated tag: a target ID, a type, a tagger and a message | Usually a commit |
Objects refer to each other by ID. A commit stores its tree's ID, and a tree stores the IDs of its blobs and subtrees. The result is a directed graph with no cycles. A cycle would require an object to contain its own hash, which is impossible to construct.
Consequences of this design
Changes propagate upward
An object's ID covers its content, and a tree's content includes its children's IDs. If you edit one file deep in the project, that blob gets a new ID. Each tree on the path to the root then gets a new ID too, and so does the commit. This structure is called a Merkle tree. Two commits with the same top-level tree ID are guaranteed to have identical content in every file and directory below it. Git can compare large trees quickly because equal IDs mean equal subtrees, and it skips them without looking inside.
Unchanged files cost nothing
A new commit that touches one file reuses the existing blobs and subtrees for everything else, because their IDs are unchanged. Git snapshots are therefore cheap, even though each commit conceptually describes the whole project.
Names live in trees, not blobs
A blob has no file name, path or permissions. Two files with different names but the same content share one blob. Renaming a file creates a new tree entry that points at the same blob, and no new content is written.
The store only grows by default
Writing an object never alters existing ones. Objects you stop referencing remain on disk until a later cleanup removes them. The final chapters cover how that cleanup works.
Collisions and the hash function
Git has historically used SHA-1, which produces 160 bits, displayed as 40 hex digits. If two different inputs produced the same ID, one object could silently stand in for the other. For random data, that is astronomically unlikely.
SHA-1 is no longer considered collision-resistant against a deliberate attacker. Researchers have produced two different PDF files with the same SHA-1 digest. Git responds in two ways:
- Current Git builds use a SHA-1 implementation that detects the input patterns of known collision attacks and refuses to produce a hash for them.
- Git supports SHA-256 repositories, created with
git init --object-format=sha256. IDs are then 64 hex digits long. Support is still limited in hosting services and tools, and SHA-1 and SHA-256 repositories do not interoperate directly.
Seeing it in a fresh repository
You can confirm that nothing is stored until you write something. A new repository's object directory holds no object files, only the empty info and pack directories:
git init store-demo
cd store-demo
find .git/objectsOnce an object is written, a two-character directory appears under .git/objects and a file is created inside it. The next chapters use this to build up from single blobs to complete commits.
Common mistakes
- Expecting two identical files to produce two objects. Identical content means one blob, whatever the file names.
- Hashing only the content and expecting a match. The ID covers the header too, so
sha1sum filedoes not equalgit hash-object file. - Reading object files directly with
cat. They are zlib-compressed, so the output looks like binary noise. Usegit cat-file. - Thinking an edit modifies an object. An edit creates a new object, and the old one stays until it is cleaned up.
- Expecting line-ending conversion to be invisible. If Git converts line endings when you add a file, the stored content differs from the file on disk, so the ID differs from what
sha1sumshows for the working file.
Exercise
A file contains the 4 bytes abc followed by a newline, so 4 bytes in total. Write the exact byte string Git hashes to produce its blob ID, and explain why copying the file to a new name does not create a second object.
Show answer
The byte string is blob 4, then a NUL byte, then abc and a newline, written blob 4\0abc\n. Git hashes this with SHA-1 and uses the result as the ID. A copy under a new name has identical content, so it produces the same string and the same hash. The object already exists, so Git stores nothing new. The file name is recorded only in a tree entry, not in the blob.
Exercise
You change one line in src/util/helpers.txt and commit. Which kinds of objects get new IDs, and which stay the same?
Show answer
The blob for helpers.txt gets a new ID because its content changed. The trees for src/util, src and the repository root each get new IDs, because each contains the ID of a changed child. The commit is a new object with a new ID. All other blobs and unchanged subtrees keep their IDs and are reused by the new commit.