TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท git ยท version control ยท devops

How Git works inside

Git is a content-addressed store of immutable objects (blobs, trees, commits and tags) named by their hash, plus small movable refs such as branches and HEAD that point into the commit graph.

15 min6 animations

๐Ÿ–จ๏ธ Cheat sheet

A box of fingerprinted photos

Imagine a photo album for your project. Every time you want to remember how things look, you take photos and stick them on a new page.

Each photo gets a label with its fingerprint: a long code worked out from exactly what is in the picture. Change one dot and the fingerprint is completely different. Take the same picture twice and you get the same fingerprint, so the box only keeps it once.

Everything is filed in one box, sorted by fingerprint. There are four kinds of things in the box:

  • a photo of one thing, just the picture, with no name on it;
  • a contents card that lists which photos belong on a page and what each one is called;
  • an album page: one contents card, who made the page and when, a caption, and the fingerprint of the page before;
  • a gold label: a signed note that points at one special page, like "the version we handed in".

Git calls an album page a commit.

Nothing in the box is ever changed. If you want something different, you make a new photo with a new fingerprint.

A content-addressed object store

At its core Git is a key-value store. The key is the object id: the hash of a short header (type size and a null byte) followed by the content. By default the hash is SHA-1, written as 40 hex digits. git init --object-format=sha256 creates a repository with SHA-256 ids (64 hex digits) instead; Git's plan is to make SHA-256 the default for new repositories in Git 3.0. Same content, same id, so identical content is stored once. The hash names content rather than hiding it (see hashing vs encryption).

ObjectHolds
blobthe bytes of one file, with no name or permissions
treea directory listing: mode, type, name and id of each blob or subtree
commitone root tree, zero or more parent commits, author, committer, message
tag (annotated)the id and type of an object, a tag name, the tagger and a message (optionally signed)

git cat-file -p prints any object:

1$ echo hello | git hash-object --stdin2ce013625030ba8dba906f756967f9e9ca394464a3 4$ git cat-file -p HEAD5tree a753c71170689c96966a87263a94c848ea429d0c6author Ana <ana@example.com> 1792904560 +00007committer Ana <ana@example.com> 1792904560 +00008 9First page10 11$ git cat-file -p HEAD^{tree}12100644 blob ce013625030ba8dba906f756967f9e9ca394464a    README.md13040000 tree e32ef1ac1fbf2245cc15228ee619e4ea946d9380    src

Objects are immutable. Because a commit's id covers its tree id and its parents' ids, one commit id pins the whole snapshot and all of its history: change any byte anywhere and every id above it changes. The repository lives in .git/:

1.git/2  HEAD                      ref: refs/heads/main3  config4  index                     the staging area5  objects/ce/0136...        a loose object, zlib-compressed6  objects/pack/             packfiles (.pack and .idx)7  refs/heads/main           a branch: one commit id8  refs/tags/v19  refs/remotes/origin/main  a remote-tracking branch10  logs/                     reflogs11  packed-refs

A lightweight tag is just a ref under refs/tags/; only an annotated tag (git tag -a) creates a tag object.

Everything gets a fingerprint5 steps
The box012345๐Ÿง‘โ€๐ŸŽจYou๐Ÿ”Fingerprint reader
Press play and watch it happen!

Every page shows the whole room

An album page doesn't say "the lamp moved a bit". It shows the whole project as it looked that day, through its contents card. That sounds wasteful, but it isn't: if a photo didn't change, the new card just lists the same fingerprint again, so the box still holds only one copy.

To see what changed between two pages, you lay them side by side and compare. Each page is a complete snapshot.

When the box gets crowded, someone packs it neatly. Photos that look nearly alike are packed as one full photo plus a small note saying "same as that one, but with a hat". That saves space in the box, but every page still shows the whole room.

Snapshots, not diffs

Each commit points to a complete tree. Files and directories that didn't change keep the same blob and tree ids, so a new commit only adds objects for what changed (the changed blobs and the trees on the path to them). git diff and git log -p compute differences on the fly by comparing trees.

Storage is a separate concern. New objects are written loose, one zlib-compressed file each. git gc moves them into packfiles; it also runs automatically as git gc --auto once there are too many loose objects (gc.auto, 6700 by default). Fetches and pushes arrive as a pack too, which Git keeps as a packfile unless it holds fewer than transfer.unpackLimit objects (100 by default). Inside a pack, an object may be stored as a delta against a similar object, chosen by similarity rather than by history order, and a .idx file maps ids to offsets. Deltas are a compression detail: the model you program against is always whole snapshots.

Snapshots that share photos4 steps
Album pages01234Photos in the box01234๐Ÿง‘โ€๐ŸŽจYou
Press play and watch it happen!

Bookmarks, the ribbon and the tray

Fingerprints are long, so you stick bookmarks on pages instead. A bookmark is a sticky tab with a name, like "main", and the page's fingerprint written on it. Making a new bookmark costs almost nothing. Git calls a bookmark a branch.

A ribbon shows where you are reading right now, and it's usually tied to a bookmark. Git calls this ribbon HEAD. When you add a page, the bookmark the ribbon is tied to moves onto the new page, and the ribbon goes with it.

Before you add a page, you lay the photos for it on a tray, so you choose exactly what goes on the next page.

You can also lay the ribbon straight on an old page to look around. Then it isn't tied to any bookmark. New pages you add there have no bookmark of their own, so stick one on before you leave, or they are hard to find again.

Refs, HEAD and the index

A branch is a ref: a file such as .git/refs/heads/main holding one commit id (or a line in packed-refs; the newer reftable backend stores refs differently). Creating one writes about 41 bytes, which is why branches are cheap.

HEAD is usually a symbolic ref: .git/HEAD contains ref: refs/heads/main. git commit builds a tree from the index, writes a commit whose parent is the current HEAD commit, and moves the branch HEAD points to. HEAD follows because it names the branch, not the commit.

The index (.git/index, the staging area) lists every tracked path with its mode and blob id. git add hashes the file into a blob and updates its entry; git ls-files -s shows it. Git compares three trees: HEAD, the index and the working tree. git switch main (or git checkout main) points HEAD at main and rewrites the index and working tree to match its commit.

Detached HEAD: git switch --detach <commit> (or checking out a tag or a commit id) writes the commit id itself into .git/HEAD. Commits made there are reachable only from HEAD; switch away and only the reflog remembers them. Run git switch -c <name> first to keep them on a branch.

Bookmarks, the ribbon and the tray4 steps
Album pages01234๐Ÿง‘โ€๐ŸŽจYou๐Ÿงบ The tray
Press play and watch it happen!

Joining two lines of pages

Ana's bookmark, main, is on page b7c. Ben and Cleo both started from that page, and each added pages on their own line under their own bookmark.

Ben's turn first. Main hasn't moved since he started, so joining is easy: Ana slides her bookmark forward onto Ben's newest page. No new page is made. Git calls that a fast-forward.

Then Cleo's turn. Now main has moved on, and so has Cleo, so there's nothing to slide along. Git compares both lines with the page they share and makes a new joining page that points back to two pages before it, one from each line.

Merge: fast-forward or merge commit

git merge other checks how the two commits relate:

  • If the current branch's commit is an ancestor of other, it's a fast-forward: Git just moves the branch ref to other's commit and updates the working tree. No commit is created.
  • Otherwise the histories have diverged. Git finds the merge base (the best common ancestor, git merge-base), does a three-way merge of base, ours and theirs, and writes a merge commit with two parents. The default strategy is ort (since Git 2.34).

--no-ff forces a merge commit even when a fast-forward is possible, to keep a visible join; --ff-only refuses anything else. On a conflict Git stops, writes conflict markers into the files and keeps the base, ours and theirs versions in the index until you git add the resolution and commit.

Fast-forward or a joining page4 steps
Shared pages01234Ben's line, then main01234Cleo's pages01234๐Ÿ‘ฉAna
Press play and watch it happen!

Copying pages and the ribbon's diary

Instead of a joining page, Ben can redo his pages on top of Ana's newest one. Because each new page points back to a different page before it, it gets a new fingerprint: they are copies, not the same pages moved. His bookmark jumps to the copies, and the old pages are left with no bookmark at all.

They aren't lost yet. The ribbon keeps a diary, written down every time it or a bookmark moves: "was on page d4e, now on d8b". If you made a mistake, you look up the old fingerprint in the diary and put a bookmark back on it. Git calls this diary the reflog.

Diary entries don't last for ever: an entry for a page no bookmark is on any more gets crossed out after about a month.

Now and then Git tidies the box. Pages that no bookmark, ribbon or diary entry can reach any more, and that are old enough, are thrown out for good.

Rebase, the reflog and garbage collection

git rebase main (run on feature) replays each commit that is on feature but not on main onto main's tip, as new commits with the same changes. New parents mean new ids. Then it moves feature to the last copy. The originals are now unreachable from any branch. Never rebase commits that others have already fetched; if you must rewrite a pushed branch, push with --force-with-lease.

The reflog records every move of HEAD and of each branch, in .git/logs/. It is local only and never pushed. For example (ids are illustrative):

1$ git reflog feature2d8b4f21 feature@{0}: rebase (finish): refs/heads/feature onto e5f3c09b2d17a4e8f6c1b0a9d3e2f5c47a8b6d103d4e9a7b feature@{1}: commit: add search4$ git reset --hard feature@{1}     # undo the rebase

ORIG_HEAD also holds the previous tip after a rebase, merge or reset.

Garbage collection. git gc packs objects and deletes unreachable ones: objects that no ref, reflog entry or index entry leads to. It only prunes unreachable objects older than gc.pruneExpire (two weeks by default; until then recent Git keeps them in a "cruft pack" rather than as loose files), and it expires reflog entries after gc.reflogExpire (90 days) or, for entries no longer reachable from the branch tip, gc.reflogExpireUnreachable (30 days). So a "lost" commit is usually recoverable for weeks, and gone after that.

Copied pages and the diary5 steps
Ana's pages012345Ben's old pages0123๐Ÿ‘ฆBen๐Ÿ““ Ribbon's diary
Press play and watch it happen!

A friend's copy of the album

Your team keeps one copy of the album at a friend's house. Git calls that copy origin. You also keep pencil bookmarks in your own album, like "origin/main", that say where the friend's bookmarks were the last time you visited.

When a teammate adds a page at the friend's house, your pencil bookmark doesn't know yet. Fetching means visiting, copying the new pages into your box and moving your pencil bookmarks. It never moves your own bookmarks.

Pulling is fetching and then joining the new pages into yours, in one go.

Remotes: fetch versus pull

git clone records the source as the remote origin and creates remote-tracking branches such as refs/remotes/origin/main: your local record of where the remote's branches were at your last fetch. You don't commit to them; git fetch and git push update them.

  • git fetch asks the remote for its refs, downloads the objects you're missing (usually as one packfile) and moves origin/*. Your own branches, index and working tree stay as they were, so it's always safe.
  • git pull is git fetch followed by integrating the upstream branch into the current one. If your branch hasn't moved, that is a fast-forward. If both sides have new commits, it merges (--no-rebase, pull.rebase=false) or rebases (--rebase, pull.rebase=true); with neither configured, Git stops and asks you to choose.
  • git push sends the objects the remote lacks and asks it to move its branch. The remote rejects a push that isn't a fast-forward of its branch unless you force it.

"Ahead 1, behind 2" in git status compares your branch with origin/main as of the last fetch, not with the live server.

Fetch, then pull4 steps
Your album01234The friend's copy01234๐Ÿ‘งTeammate
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about How Git works inside, told the same way as the story.
  1. You change one drawing in a big project and add a new page. What new things go into the box?
  2. Ben redid his pages on top of Ana's and now wishes he hadn't. His bookmark only shows the copies. Can he get the old pages back?
  3. You visit the friend's house and copy the new pages, but you don't join them in. What moved in your album?
  4. You lay the ribbon straight on an old page, add two new pages there, then tie the ribbon back to main. What happens to the two new pages?
Answer every question to check.Passing marks How Git works inside as done.
Got the hang of How Git works inside? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿš€ Shipping to productionStep 1 of 10

Next on the path โ†’๐Ÿญ CI/CD