Building Git in Java

Git is something most developers use every day without thinking much about what happens on disk. Concepts like commit graphs, staging areas, and tree hashes seem complex until you implement them yourself. To see how these pieces fit together, I built a version control system from scratch in Java.
I picked Java because static typing and clear class structures make it straightforward to model content-addressable storage, binary object serialization, and recursive directory trees.
Here is a breakdown of how the storage layer, index file, and diff algorithm work.
1. Content-Addressable Storage: Blobs, Trees, and Commits
Like Git, this VCS is built on a content-addressable storage design. This means files and directory structures are identified solely by their content hashes:
-
Blobs (Binary Large Objects): When a file is staged, the system reads its contents, computes its SHA-1 hash, and stores the compressed file inside
.vcs/objects/under a folder named after the first two hash characters:Javapublic class Blob { private final String hash; private final byte[] content; } -
Trees: To preserve directory structures, the VCS maps folders to
treefiles. A tree file is simply a list of pointers to other blobs (files) and trees (subfolders) along with their corresponding names:blob 4a123bc... index.css tree e89a2bc... components/ -
Commits: A commit object points to a root tree (representing the project state at that instant), the author details, and parent commit hashes (to build the commit history graph).
2. Staging Area and Index File
How does the system know what files are ready to be committed? It maintains an index file. The index acts as a staging state:
- It tracks file paths, modification times, and SHA-1 hashes of staged files.
- When a file changes, the VCS computes its hash and compares it to the index entry. If the hashes mismatch, the file is marked as modified.
- On commit, the system parses the staging index to construct the hierarchical tree objects.
3. The Tree-Walking Diff Algorithm
To generate clean commit histories and summaries of modifications, the VCS implements a custom recursive tree-walking algorithm:
- Input: The algorithm receives the root tree hashes of two different revisions (e.g., Commit A and Commit B).
- Comparison: It walks the tree structures simultaneously.
-
- If a path exists in A but not in B, it is marked as
DELETED. - If a path exists in B but not in A, it is marked as
ADDED. - If a path exists in both but the SHA-1 hash is different, the system steps inside:
- If it's a tree, it recurses.
- If it's a blob, it triggers a unified line-by-line diff comparing the file contents.
- If a path exists in A but not in B, it is marked as
Building a version control tool from scratch demystifies how Git works under the hood. Once you realize that commits are just text files pointing to tree hashes and blobs stored in a content-addressable folder, the entire mental model becomes clear and intuitive.