This past week I did the Git challenge on CodeCrafters.
A quick word of explanation: CodeCrafters gives you an environment where you can implement well-known, sometimes fairly complex, pieces of software step by step. Your programming gets stronger and you get more fluent, and you also pick up new concepts that are specific to the design of that particular piece of software.
I did this challenge in Rust, and the code is here. But I know it supports a lot of languages, and for each one it has a ready-made testing platform, so you don’t get bogged down in the details and can just write code.
New challenges they release go into a beta phase, where they’re free (so that any bugs can surface), but once a challenge goes GA it becomes paid, and you no longer have access to it unless you have a referral.
If anyone wants to do the older, GA challenges, this referral link gets you free access to all of them for a week. (It gives me a free week too, so if you sign up through it, I’d love to know, so I can figure out when to use mine.)
Overall it was a pretty cool site, and I really enjoyed the Git challenge. I generally get a real kick out of implementing a protocol and seeing the outside world agree with my code, and this Git challenge was exactly that. Once you get past the first two or three stages, you suddenly realize you can use your own code in place of Git commands, which is just awesome!
The Git challenge itself also had a few interesting points that I want to talk about below.
1. Git intro#
Git’s storage system architecture is really interesting overall. It has three main concepts that we deal with most in this challenge: objects, packfiles, and hashes.
When we run git init, Git creates the .git directory and populates it. A few of the important things inside that directory:
- The
objectsdirectory, which is sort of like a database. All the objects and packfiles live in here. - The
refsdirectory, which holds what are essentially pointers. These pointers can be branches, tags, or anything else that points to a commit. - The
HEADfile, which holds the address of the ref we’re currently on (usuallyrefs/heads/master, but when we’re on a detached HEAD, for example, it’s directly the hash of the commit we’re on).
By default, everything in Git is uniquely identified by a SHA-1 hash, which is 20 bytes, or 40 characters hex encoded.
The smallest unit of data in Git is called an object. Every object consists of a header and a body, separated by a 0 byte. To save on precious gigabytes, Git usually runs objects through zlib so they take up less space. Finally, it takes a hash of the whole header and body and stores the result at .git/objects/hash[..2]/hash[2..].
Here’s a glimpse of Git’s object storage:
/usr/bin/ls .git/objects
00 07 0e 17 1f 28 2e 37 3e 45 4e 57 60 69
71 78 84 8b 95 9d a6 ae b4 ba c2 c9 d3 dd
e4 eb f1 f8 02 09 0f 19 20 29 2f 38 3f 46
50 59 61 6a 73 7a 85 8c 96 9f a7 af b5 bb
c3 cc d5 de e5 ec f2 fa 03 0a 10 1b 23 2a
...
Objects in Git come in three types: blob, tree, and commit. A blob is just raw data. A commit is, well, a commit! And a tree more or less represents a directory.
The thing is, one of Git’s big goals is speed. For example, it wants git checkout to be O(1), and that’s why it dumps files into objects in full instead of just computing their diffs. That way, on every checkout it just reads the commit and drops all the objects it needs into the staging area wholesale. In practice, the diff that you and I see is computed on the fly and is purely for show!
Another interesting detail is the subfoldering on the first two characters of the hash inside the objects directory. If you’ve noticed, an object with hash 123456… isn’t stored at
.git/objects/123456...
but at
.git/objects/12/3456...
which is a bit odd! At first I thought it was for better indexing and faster file lookups, but apparently it has nothing to do with that. They just wanted to avoid hitting Linux’s hard limit on the number of files in a single directory. It seems Linux just isn’t a fan of having lots of files in one directory.
2. Git plumbing!#
Git has a set of commands known as git plumbing commands that aren’t part of Git’s main UI. They let you poke around in Git’s internals, and in fact Git’s main commands are built by chaining these plumbing commands together.
For example, git commit is a combination of git write-tree and git commit-tree.
Below I’ll introduce a few handy ones that also come in useful for this challenge:
git cat-file
This command lets you see an object’s type, size, and contents. You run it with one of three flags: -s, -t, or -p.
$> git rev-parse HEAD
d49ff6514c7bf1f6f558608b6637c8ac8df27d73
$> git cat-file -t d49ff6514c7bf1f6f558608b6637c8ac8df27d73
commit
$> git cat-file -s d49ff6514c7bf1f6f558608b6637c8ac8df27d73
248
$> git cat-file -p d49ff6514c7bf1f6f558608b6637c8ac8df27d73
tree d722c49a854b58495c43ec375f3b99a17164b996
parent 0c1cb03453557a2d74a2e2e0efe7aa36ef3a1e8c
author ArshiAAkhavan <letmemakenewone@gmail.com> 1736913010 -0500
committer ArshiAAkhavan <letmemakenewone@gmail.com> 1736913010 -0500
add some comments
If you already know the object’s type, you can also give it directly:
$> git cat-file blob de1e40e421ff241facff84419f903bc09c89aaaf
[package]
name = "codecrafters-git"
version = "0.1.0"
authors = ["Codecrafters <hello@codecrafters.io>"]
edition = "2021"
rust-version = "1.80"
[dependencies]
anyhow = "1.0.68" # error handling
bytes = "1.3.0" # helps manage buffers
clap = { version = "4.5.23", features = ["derive", "cargo"] } # command line
flate2 = "1.0.34" # compression
hex = "0.4.3"
reqwest = { version = "0.12.12", features = ["blocking"] }
sha1 = "0.10.6"
thiserror = "1.0.38"
This command shows trees too, but for nicer output you should use ls-tree:
git ls-tree d722c49a854b58495c43ec375f3b99a17164b996
100644 blob 73fab072c5adfcb0a8712064618e210ca7c5d540 .gitignore
100644 blob 9df45bf151498450284b22f89b87f698b8433330 Cargo.lock
100644 blob de1e40e421ff241facff84419f903bc09c89aaaf Cargo.toml
100644 blob e27ea4a0d7abaf94c14450e1b18699c314bd4cc8 README.md
040000 tree b3721d28ee9828552c44c7178ac39b18e49c97a9 src
There are three more commands as well: hash-object builds a blob from a file, write-tree recursively stores the whole staging area in the object storage, and commit-tree takes a tree hash and builds a commit from it.
3. Git packfiles#
In the last stage of the challenge, you have to implement git clone. Git has two protocols for talking between client and server: one is the dumb server and the other is the smart server. The dumb server is much simpler, and therefore slower, and it’s great for implementing a PoC. The general process goes like this:
- First you send a request to
/info/refs, and it returns all the refs along with their hashes. - Then, for the ref you want (which for
git cloneismaster, or its edition for sensitive kids,main), you can fetch its object from/objects/hash[..2]/hash[2..], which gives you the HEAD commit object. From there on you just keep shoveling: decode the object you fetched, then fetch the objects referenced inside it the same way, until you’ve shoveled the whole repo down onto your machine!
This protocol is apparently very old, and GitHub, for example, no longer supports it, but some Git repositories (like CodeCrafters’ own) still keep its API open, so you can test against it.
And then there’s the smart protocol, whose goal is to speed things along. It basically says: instead of you fetching the objects one by one, tell me which ref you want and I’ll send you everything you need in one go. For this exchange they use their own homegrown protocol called packet-line (pkt-line). The way it works is that in your request you say “I have these, I want those,” and the server gives you whatever you’re missing to build them.
Here’s a sample pkt-line message:
0000
0032want 7b8eb72b9dfa14a28ed22d7618b3cdecaa5d5be0
0000
0009done
Each line starts with a 32-bit number that specifies the length of the whole message, followed by the message itself, up to the first 0 byte. 0000 itself is a magic value that means flush, i.e. that part of the message is over and we’re moving on to the next one.
In the example above, we’ve asked the server for everything needed to build the object we gave it, and told it we don’t have anything yet (there’s no have anywhere in the message!). So if that hash up there were the master ref, you’d effectively be saying “I want to clone,” and Git would respond with all the required objects.
If you want to play around with it some more, you can use these two curl commands:
# fetch refs
curl 'https://github.com/codecrafters-io/git-sample-2/info/refs?service=git-upload-pack' -o -
# fetch master
curl -X POST \
-H "Content-Type: application/x-git-upload-pack-request" \
-H "Accept: application/x-git-upload-pack-result" \
--data-binary $'0032want 7b8eb72b9dfa14a28ed22d7618b3cdecaa5d5be0\n00000009done\n' \
https://github.com/codecrafters-io/git-sample-2.git/git-upload-pack \
-o - | xxd
But sending back all of these objects is really bulky in itself, and the network might not be too happy about it. Remember, every object is the actual file itself, not its diff, so cloning is like downloading the entire repo.
To solve this, Git defined another data type called the packfile (along with its little sister, the packet-index), whose goal is to compress a large number of objects as tightly as possible.
The design and implementation of packfiles use some neat serialization and compression ideas that bring file sizes way down. For example, here some objects can be stored as diffs of other objects, and every last bit of the data’s capacity gets put to use!
This guy does a great job of going through the details of the packfile structure, but he slips up in one or two places, which this guy corrected. And our friend here implemented git clone in Haskell and explains step by step what you need to do. The efforts of these three men make any further attempt on my part to explain packfiles pointless, but I strongly recommend reading at least the first guy’s post and its corrections, just to see how much energy went into compressing these packfiles.