Reading and writing Git internals in an afternoon

Plenty of good programmers run git commit and git merge all day while treating .git/ like a black box they are afraid to touch. If a rebase goes sideways, they copy changed files to /tmp, clone a fresh folder, and hope nobody notices.

I wrote Tiny Git (tiny-git in the shell1) in pure Python without calling git underneath. My goal was to keep the whole codebase small and clear enough that you can read it from top to bottom in one afternoon and see how Git actually stores history.

pip install tiny-git
tiny-git init
tiny-git add src/
tiny-git commit -m "Initial snapshot"
tiny-git fsck

Four pieces that do the real work

  1. SHA-1 objects on disk. Every blob, tree, and commit is named after the SHA-1 hash of its header plus byte content. If ten commits contain the exact same file, all ten trees point to the same compressed object file.
  2. Atomic writes and fsck. Objects write to a temporary file first and rename into place atomically so a killed process never leaves a corrupted half-file in .tinygit/objects. Running tiny-git fsck re-hashes objects and checks every tree and parent pointer, while a HEAD reflog records branch moves.
  3. A plain staging index. The index is just a sorted list of tracked paths and blob hashes sitting between your working directory and the next commit. Once you write that file yourself, status, diff, and safe checkout checks (refusing to overwrite uncommitted edits, similar to Smart File Organizer) stop feeling complicated.
  4. Three-way merges. Merging two branches walks the commit graph back to their lowest common ancestor, compares base, ours, and theirs trees file by file, and writes standard conflict markers when both sides edited the same lines.

Footnotes

  1. Python package names allow hyphens while import statements do not, so you run tiny-git on the command line and from tinygit.repository import Repository in Python. ↩


Linked mentions

You might also enjoy