Write Git Objects by Hand: A Mini-git in C++
Git stores everything as objects, and the object format is small enough to write by hand. This guide builds a C++ program that writes a blob, a tree, and a commit into a fresh repository, then checks every hash against real git. The blob hash matches git hash-object exactly, the tree hash matches git mktree exactly, and git cat-file, git log, and git fsck all read the result. A one-byte tamper test shows what happens when the bytes stop agreeing.
Written November 7, 2026 · 14 min read
- One format, four types
- Build it
- Three hashes git agrees with
- Real git reads our objects
One format, four types
Git keeps four kinds of objects: blob, tree, commit, and tag. A blob holds the bytes of one file. A tree holds a directory listing. A commit holds a tree plus the author, the committer, and a message. A tag points at another object with a name. This guide writes the first three. Tags are left out, and the reason is given at the end.
Every loose object shares one on-disk shape. The loose object format page states the shape plainly: each loose object holds a prefix followed by the data, and the whole thing is compressed with zlib and stored in a file. The prefix is the type, a space, the size of the data in decimal, and a NUL byte. The object id is the SHA-1 hash of the uncompressed prefix plus data. The file lives under the objects directory, in a subdirectory named by the first two hex characters of the id, with the remaining 38 characters as the file name. The Pro Git chapter on git objects works the same recipe by hand in Ruby: build the header, hash header plus content, compress with zlib, write the file at the path the hash names.
That recipe has three consequences worth holding onto before any code. First, the id is a hash of content, so the same content always produces the same id, and different content produces a different id. Second, a blob stores bytes only. It has no file name, no mode, and no timestamp. The name and mode live in the tree entry that points at the blob. Third, the tree entry is binary, not text. Each entry is a mode in octal, a space, a file name, a NUL byte, and then the 20 raw bytes of the child id. Writing the hex string there instead of the raw bytes is the most likely mistake in the whole program, and it produces a tree hash that git will not reproduce.
The program
The program below is the whole implementation. It writes one blob, one tree with one entry, and one commit with no parent, then points the main branch at the commit. It takes the git directory as its argument. The fixed timestamp keeps the commit hash reproducible: the same input always yields the same three hashes, which is why the re-run below reproduces the first run exactly.
// minigit.cpp — minimal git object writer in C++: blob/tree/commit,
// verified byte-for-byte against real git (hash-object / mktree / cat-file / fsck).
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <filesystem>
#include <openssl/sha.h>
#include <zlib.h>
namespace fs = std::filesystem;
static std::string sha1_hex(const std::string& data) {
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char*>(data.data()), data.size(), digest);
char out[41];
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) std::sprintf(out + 2 * i, "%02x", digest[i]);
return std::string(out, 40);
}
static std::string sha1_raw(const std::string& data) {
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char*>(data.data()), data.size(), digest);
return std::string(reinterpret_cast<char*>(digest), SHA_DIGEST_LENGTH);
}
// Write one loose object; returns its hex id. Idempotent: existing objects untouched.
static std::string write_object(const fs::path& gitdir, const std::string& type,
const std::string& payload) {
std::string store = type + " " + std::to_string(payload.size()) + '\0' + payload;
std::string hex = sha1_hex(store);
fs::path dir = gitdir / "objects" / hex.substr(0, 2);
fs::create_directories(dir);
fs::path file = dir / hex.substr(2);
if (!fs::exists(file)) {
uLongf bound = compressBound(static_cast<uLong>(store.size()));
std::vector<unsigned char> comp(bound);
if (compress(comp.data(), &bound,
reinterpret_cast<const Bytef*>(store.data()),
static_cast<uLong>(store.size())) != Z_OK) {
std::fprintf(stderr, "compress failed\n");
std::exit(1);
}
FILE* f = std::fopen(file.c_str(), "wb");
std::fwrite(comp.data(), 1, bound, f);
std::fclose(f);
}
return hex;
}
int main(int argc, char** argv) {
fs::path gitdir = argc > 1 ? argv[1] : ".git";
fs::create_directories(gitdir / "objects");
fs::create_directories(gitdir / "refs" / "heads");
std::string blob = "hello minigit\n";
std::string blob_hex = write_object(gitdir, "blob", blob);
std::printf("blob %s\n", blob_hex.c_str());
// Tree entry: "100644 hello.txt\0" + 20 raw bytes of the blob id.
std::string tree_payload = std::string("100644 hello.txt") + '\0' +
sha1_raw("blob " + std::to_string(blob.size()) + '\0' + blob);
std::string tree_hex = write_object(gitdir, "tree", tree_payload);
std::printf("tree %s\n", tree_hex.c_str());
std::string commit_payload =
"tree " + tree_hex +
"\nauthor Minigit <mini@example.com> 1790000000 +0000"
"\ncommitter Minigit <mini@example.com> 1790000000 +0000"
"\n\ninitial commit\n";
std::string commit_hex = write_object(gitdir, "commit", commit_payload);
std::printf("commit %s\n", commit_hex.c_str());
FILE* f = std::fopen((gitdir / "HEAD").c_str(), "w");
std::fputs("ref: refs/heads/main\n", f);
std::fclose(f);
f = std::fopen((gitdir / "refs" / "heads" / "main").c_str(), "w");
std::fprintf(f, "%s\n", commit_hex.c_str());
std::fclose(f);
std::printf("minigit-ok\n");
return 0;
}
Three details in this code decide whether git accepts the output. The header is built from the payload size, not the file size: the blob content is 14 bytes, so the hashed string starts with the 8 bytes of the header plus those 14 bytes. The tree entry carries the blob id as 20 raw bytes from the SHA-1 digest, never as 40 hex characters. The commit payload carries a fixed timestamp, 1790000000, which is 2026-09-21 14:13 UTC. A real program would use the current time. The fixed value is what makes the hashes below reproducible, and the guide says so rather than pretending the timestamp is current.
Two library choices are worth naming. The hash comes from OpenSSL, and the compression comes from zlib, so the build links both. The program uses C++17 only, for the filesystem library. Nothing in it needs a newer standard.
Build it
The build command:
$ g++ -std=c++17 -O2 -Wall -Wextra -o minigit minigit.cpp -lz -lcrypto
$ echo "build rc=$?"
build rc=0
Return code 0, zero warnings. The -Wall -Wextra flags are load-bearing here: a build that passes without them proves less, because a sign or size warning in the compression call would be exactly the kind of defect that writes a corrupt object. Running the program against a fresh directory writes the three objects and the two ref files:
$ ./minigit repo/.git
blob aafd11ee7c1bd00d6a4e757a23e44e5258b05321
tree 37617524013aeed75fd0429d497f239c5454fc01
commit c8cd1de1e07b89514e132d8606b24b0aa91d0e80
minigit-ok
Those three lines are the claim. The rest of the guide checks them against git itself.
Three hashes git agrees with
The blob holds 14 bytes, the string hello minigit plus a newline. Piping the same bytes through git hash-object must print the same id, because the id is a hash of the same header plus content:
$ printf 'hello minigit\n' | git hash-object --stdin
aafd11ee7c1bd00d6a4e757a23e44e5258b05321
It matches. The tree holds one entry, mode 100644, name hello.txt, pointing at that blob. Feeding the same entry to git mktree must print the same tree id:
$ printf '100644 blob aafd11ee7c1bd00d6a4e757a23e44e5258b05321\thello.txt\n' | git --git-dir=repo/.git mktree
37617524013aeed75fd0429d497f239c5454fc01
It matches too. The two checks together prove the byte layout, not just the hash function. If the tree entry had carried the blob id as hex text, the hash would differ and the check would fail at this line. The commit has no independent command to compare against in the same way, because its hash depends on the author timestamp, so the next section checks it by reading instead of by recomputing.
The sizes confirm the payloads are what the program claims. git cat-file -s reports 14 for the blob, 37 for the tree, and 167 for the commit. The tree number is worth checking by hand: 6 bytes for the mode, 1 for the space, 9 for the file name, 1 for the NUL byte, and 20 for the raw id, which adds to 37. The commit number is the tree line, the author line, the committer line, a blank line, and the message, which adds to 167.
Real git reads our objects
With the hashes confirmed, the question becomes whether git can use the repository. git cat-file -p on the commit prints the stored object back:
$ git --git-dir=repo/.git cat-file -p c8cd1de1e07b89514e132d8606b24b0aa91d0e80
tree 37617524013aeed75fd0429d497f239c5454fc01
author Minigit <mini@example.com> 1790000000 +0000
committer Minigit <mini@example.com> 1790000000 +0000
initial commit
Reading the tree prints the single entry, and the log walks the one-commit history:
$ git --git-dir=repo/.git cat-file -p 37617524013aeed75fd0429d497f239c5454fc01
100644 blob aafd11ee7c1bd00d6a4e757a23e44e5258b05321 hello.txt
$ git --git-dir=repo/.git log --oneline
c8cd1de initial commit
The log works because the program wrote the two ref files git needs: HEAD pointing at the main branch, and the main branch file holding the commit id. Without those files there would be objects but no history to walk.
The integrity check is git fsck, which the fsck manual page describes as verifying the connectivity and validity of the objects in the database, including hash checks and full reachability tracking:
$ git --git-dir=repo/.git fsck --strict
$ echo "fsck rc=$?"
fsck rc=0
No output, return code 0. The strict flag adds checks for legacy file modes, which do not apply to a fresh repository, but it costs nothing and is the flag the manual recommends for new projects.
One corrupted byte
A format that cannot detect damage is not a storage format. The test corrupts one byte of the compressed blob file, at offset 10, then asks git to read the blob back:
$ printf 'X' | dd of=repo/.git/objects/aa/fd11ee7c1bd00d6a4e757a23e44e5258b05321 bs=1 seek=10 conv=notrunc 2>/dev/null
$ git --git-dir=repo/.git cat-file -p aafd11ee7c1bd00d6a4e757a23e44e5258b05321
error: inflate: data stream error (invalid distance too far back)
error: unable to unpack aafd11ee7c1bd00d6a4e757a23e44e5258b05321 header
fatal: Not a valid object name aafd11ee7c1bd00d6a4e757a23e44e5258b05321
$ echo "tampered cat-file rc=$?"
tampered cat-file rc=128
The zlib stream fails to inflate, so git reports the object as invalid and exits 128. Restoring the saved byte brings the blob back:
$ git --git-dir=repo/.git cat-file -p aafd11ee7c1bd00d6a4e757a23e44e5258b05321
hello minigit
$ echo "restored cat-file rc=$?"
restored cat-file rc=0
This is the cheapest integrity fixture a format like this offers. One corrupted byte, one failed read, one restored byte, one passing read. It works because the id is a hash of the content: git recomputes the hash on read, and a single changed byte changes the hash, so the stored name no longer matches the stored bytes.
From loose objects to a pack
Loose objects are one file per object, which is fine for three objects and slow for thirty thousand. Real repositories pack objects into a single file. The pack format document describes that file: a header with the four bytes PACK, a version number, and an object count, then one entry per object, each with a compact type and length header and compressed data, and a checksum trailer. Packed objects drop the type and size prefix that loose objects carry, and may store an object as a delta against another object. That is a second format, and this program does not write it.
What this guide does prove is the reading side. The three loose objects were packed with git's own pack command, the loose files were deleted, and the index was rebuilt from the bare pack file:
$ printf 'c8cd1de1e07b89514e132d8606b24b0aa91d0e80\n37617524013aeed75fd0429d497f239c5454fc01\naafd11ee7c1bd00d6a4e757a23e44e5258b05321\n' | git --git-dir=repo/.git pack-objects repo/.git/objects/pack/pack
8b72326efa8a92285aa9a42e88c520461f94077f
$ git --git-dir=repo/.git index-pack repo/.git/objects/pack/pack-8b72326efa8a92285aa9a42e88c520461f94077f.pack
8b72326efa8a92285aa9a42e88c520461f94077f
The pack holds 3 objects in 1 pack file of 221 bytes, with an index of 1156 bytes. After the loose files were removed, git count-objects -v reported 0 loose objects and 3 in-pack objects. Reading all three objects back from the pack returns the same content, the log still walks the history, and the strict integrity check still passes with return code 0:
$ git --git-dir=repo/.git cat-file -p aafd11ee7c1bd00d6a4e757a23e44e5258b05321
hello minigit
$ git --git-dir=repo/.git log --oneline
c8cd1de initial commit
$ git --git-dir=repo/.git fsck --strict
$ echo "pack fsck rc=$?"
pack fsck rc=0
The boundary is explicit: writing loose objects in C++ is verified here, and reading a pack git wrote is verified here. Writing a pack in C++ is not verified here. It needs the PACK header, the compact type and length encoding, and delta compression, none of which this program implements. Do not present this guide as covering pack writing.
What this does not cover
Tag objects are the fourth type, and this program does not write one. A tag payload names an object, a type, a tag name, and a tagger line, and follows the same header and hash rule as the other three types, so adding one is a small extension of the same code. It is left out because the three types above already prove the format, and an untested tag would be the one object in this tutorial that git never checked.
SHA-256 repositories are also out of scope. Git supports them, and the loose object format page states the id is the SHA-1 or SHA-256 hash as appropriate. This program hashes with SHA-1 only, and every hash in this tutorial is a 40-character SHA-1 id. A SHA-256 version would need a different digest call and 64-character ids, and it was not built or run here.
Recovery is out of scope too. Finding a lost commit through the reflog or dangling objects is a real skill, and the Pro Git chapter covers it. This guide teaches the write path and proves it against git. It does not teach the recovery path.
Frequently asked questions
Why does the blob hash match git exactly?
Because both sides hash the same bytes. The hashed string is the header plus the content, and the header is the type, a space, the size, and a NUL byte. The file name, the file mode, and the time of writing play no part. Change any byte of the content and the hash changes. That is what content-addressed means.
Why raw bytes in the tree entry, not hex?
Because the tree format stores the child id as 20 binary bytes. The hex form is 40 characters and is only a display spelling. Writing the hex text into the entry produces a valid-looking tree with a different hash, and git will not reproduce it. The program hashes the blob id from its raw digest for exactly this reason.
Why a fixed timestamp in the commit?
So the commit hash is reproducible. With a fixed author time, the same program run twice writes the same three objects with the same three hashes. A real tool would stamp the current time, and the hash would change on every run. The fixed value is a property of this demonstration, not of the format.
Does git accept the repository as a real one?
For reading, yes. The log walks the history, the integrity check passes, and the pack round-trip works. The repository has no working tree and no index file, so it is not a repository you would check files out of. It is a repository you can read objects from, which is the claim this guide makes.
What breaks first if I extend this?
The tree writer. One file in one directory is the easy case. A real tree builder must sort entries by name with directories sorting as if they had a trailing slash, must recurse into subtrees, and must handle the executable and symlink modes. The blob and commit writers scale as written. The tree writer is the part to test against git at every step, the same way this guide tests it.
Related guides on this site
- Build Your Own Mini-Git: Objects, Trees, Commits, Packfiles
- Fix 'Passing const as this Argument Discards Qualifiers' in C++ — Const Objects, Const References, and Const Methods
- Fix C++ shared_ptr Cycle Leak — Two Objects Keep Each Other Alive, weak_ptr Breaks the Cycle
- C++ Classes and Objects: Your First Class, Constructor, and Methods
Source
- Pro Git: Git Internals — Git Objects: Git is a content-addressable filesystem; hash-object stores content and returns its key; the object id is the SHA-1 hash of the content plus a header; blobs hold content only, trees hold mode, type, hash, and name per entry, commits hold a tree plus author, committer, and message; the object storage section builds the header, hashes it, compresses with zlib, and writes the file at the path the hash names.
- gitformat-loose: Git Loose Object Format: each loose object holds a prefix of type, size, and NUL byte followed by the data, compressed with zlib; the object id is the SHA-1 or SHA-256 hash of the uncompressed data; the file lives under the objects directory with the first two hex characters as the directory and the rest as the file name.
- git-fsck: Git Manual: fsck verifies the connectivity and validity of the objects in the database; the strict flag enables stricter checking and is recommended for new projects; fsck tests SHA-1 and general object sanity with full reachability tracking.
- pack-format: Git Documentation: a pack file starts with the PACK signature, a version number, and an object count; entries carry a compact type and length header with compressed data, and may be stored as deltas; the version 2 index holds a fan-out table, sorted object names, CRC32 values, and offsets.
blob aafd11ee7c1bd00d6a4e757a23e44e5258b05321
tree 37617524013aeed75fd0429d497f239c5454fc01
commit c8cd1de1e07b89514e132d8606b24b0aa91d0e80
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.