Git Internals: a Quick Intro
Tested 2026-11-26 on macOS 14.1, Apple M3 Pro; no containers or VMs · with git 2.39.3 (Apple Git-146), Python 3.12.9 · by Vivek Sahu (@viv1) · CC BY 4.0
You’ve just spent an afternoon on three commits.
Then a git reset --hard HEAD~2 on the wrong branch, and git log shows one commit.
The work isn’t gone. Both commits are still in .git; the only thing in your history that changed is a 41-byte file, the branch.
Git also kept a log of where that branch has been, and one command puts it back.
This course is for people who use git every day and want to know what’s underneath. You’ll open .git, build
commits by hand with git’s low-level commands, then lose work in the ways it really gets lost and get it back.
By the end you’ll be able to:
- say what a commit, a tree and a blob are on disk, and predict an object’s id before git prints it;
- explain what a branch, HEAD and the reflog are, and what
reset,switchandbranch -Dchange; - find and recover commits after a bad reset, a deleted branch or a dropped stash, and work you only
git added; - tell when lost work really is gone, and what removes it.
How it works
Each lesson starts with an animated, step-by-step picture (press Play, or step with the arrow keys), then
explains with real output, with optional Go deeper sections. Each practical has you type the commands
yourself in ~/git-internals-intro/: requirements, a hint, a hidden solution, a “predict first” question and a part
where you break it on purpose. One script, ./lab, does the rest:
./lab setup pNchecks what a practical needs (git 2.28 or newer). It creates nothing for you: every repository in this course you make yourself../lab check pNtells you whether your repository is right. It only runs read-only git commands, each one written tolab.log../lab reset pNstarts you at a practical with the earlier ones’ solutions replayed. It asks first, and moves your repositories into a new folder rather than deleting them.
All you need is git and python3 (for ./lab) on your own computer (macOS or Linux). No containers.
Path
| Lesson | Practical | You’ll be able to |
|---|---|---|
| 1 · Where a commit actually lives | read any object with cat-file; say why the same content always has the same id | |
| 2 · Branches are just files | 0 · A commit with no git commit | build commits from blobs and trees by hand; write a branch with update-ref and read its reflog; find a corrupted object |
| 3 · Getting lost work back, and when it really is gone | 1 · Capstone: the rescue | recover work lost four ways, and know when gc makes it unrecoverable |
What your folder will look like
~/git-internals-intro/
├── lab the lab script: setup, check, reset (from Practical 0)
├── lab.log every command ./lab ran, with its output
├── byhand/ Practical 0: a repository whose commits you built with plumbing commands
├── blob-backup Practical 0: your copy of the blob you corrupt
├── rescue/ Practical 1: a repository you lose work in, four ways, and recover
└── doomed-id Practical 1: the id of the commit gc destroys
1 · Where a commit actually lives
In one sentence:
.git/objectsis a folder of compressed files, each named by the hash of its own content, and every commit is three kinds of them, blobs, trees and commits, pointing at each other.
The problem it solves
You run git reset --hard on the wrong branch, and an afternoon of commits disappears from git log. Are they
gone? To answer that you need to know what a commit is on disk, and what git log was showing you. People who
use git every day often can’t say. This lesson answers the first half: what a commit is made of and where it
lives. Lesson 2 answers the second.
The idea: name every piece by its content
Git keeps your project’s history in one folder, .git/objects. Everything in it follows one rule:
An object’s name is the hash of its content. Git takes the bytes, puts a short header in front, runs SHA-1 (a function that turns any bytes into a fixed-size fingerprint) and uses the 40 hex characters it returns as the file name. Think of a library where every book’s shelf number is computed from its text: two identical books get the same number, and a book can’t be changed without moving to a new shelf.
Three kinds of object are enough for a whole history:
| Kind | Holds | Example from this lesson’s repo |
|---|---|---|
| blob | one file’s bytes. No name, no permissions | ce01362: hello |
| tree | one folder’s listing: mode, id and name of each entry (cat-file -p also prints the kind) | 57e9529: greeting.txt is blob ce01362 |
| commit | one root tree, its parent commits, author, time, message | c96d6e7: tree 57e9529, “First commit” |
What it looks like
In a new repository, .git/objects holds no files. Hash a file without storing it:
echo 'hello' > greeting.txt
git hash-object greeting.txt
ce013625030ba8dba906f756967f9e9ca394464a
That’s SHA-1 of the header blob 6, a zero byte, then the 6 bytes of content. Your shell gets the same answer without git:
printf 'blob 6\0hello\n' | shasum
ce013625030ba8dba906f756967f9e9ca394464a -
git add stores the blob. The first two hex characters become a directory, the other 38 the file name:
.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
git commit adds two more objects, the tree and the commit, making 3. git cat-file -p prints any object:
git cat-file -p HEAD
tree 57e9529754dc514a3ec10db2ff882018fbe1fcbf
author Ada <ada@example.com> 1767261600 +0000
committer Ada <ada@example.com> 1767261600 +0000
First commit
git cat-file -p 57e9529754dc514a3ec10db2ff882018fbe1fcbf
100644 blob ce013625030ba8dba906f756967f9e9ca394464a greeting.txt
100644 is the mode of an ordinary file. 1767261600 is the time in seconds since 1970 (here, 1 January 2026,
10:00 UTC).
Same content, same id. Copy greeting.txt to copy.txt and commit: the store grows from 3 objects to 5, not
6. The new tree lists both names against the one blob:
100644 blob ce013625030ba8dba906f756967f9e9ca394464a copy.txt
100644 blob ce013625030ba8dba906f756967f9e9ca394464a greeting.txt
Change one file, and the change climbs to the top. Write hello world into greeting.txt and commit. It gets
a new blob, so its tree gets a new id, so the commit does. copy.txt keeps pointing at the old blob:
100644 blob ce013625030ba8dba906f756967f9e9ca394464a copy.txt
100644 blob 3b18e512dba79e4c8300dd08aeb37f8e728b8dad greeting.txt
Each commit’s parent line holds the previous commit’s id, and that id covers its tree and its own parent. So
one commit id pins the whole snapshot and every commit before it. Nothing in the store is ever edited; a
change is always a new object.
Try it on your computer
Practical 0, after lesson 2, has you build these three kinds of
object yourself without git add or git commit, and predict their ids before git prints them.
Go deeper: the bytes in the file
An object file is the header and content compressed with zlib. Python’s standard library can open one:
python3 -c "import zlib,sys; sys.stdout.buffer.write(zlib.decompress(open('.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a','rb').read()))" | od -c
0000000 b l o b 6 \0 h e l l o \n
0000015
13 bytes uncompressed (od counts in octal: 15 is 13), 21 on disk: for tiny files zlib’s own framing costs more
than it saves. A tree’s entries are binary (the 20 raw bytes of each id, not 40 hex characters), which is why you
read trees with git cat-file -p rather than cat.
Loose files like these are how objects start; lesson 3 covers
the packfiles that git gc moves them into. The format is in the
Git Book, Git Objects.
Go deeper: SHA-1 and SHA-256
A SHA-1 id is 160 bits (40 hex characters × 4 bits). SHA-1 is no longer considered safe against a deliberate collision (SHAttered, 2017), and git can already use SHA-256 instead, chosen when the repository is created:
git init -q --object-format=sha256 sha256demo
cd sha256demo
echo 'hello' | git hash-object --stdin
2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4
64 hex characters, 256 bits; blobs, trees and commits work exactly the same. In git 2.39 the option is still marked experimental, and a SHA-256 repository can’t in general share work with a SHA-1 one (git-init). Almost every repository you meet today is SHA-1; the plan for moving between the two is git’s hash-function-transition document.
Common misunderstandings
- “A commit stores the changes (a diff).” It stores a full snapshot: a root tree listing every file. Git computes diffs when you ask for them. Unchanged files cost nothing, because their blob is shared.
- “The blob knows its file name.” Names live only in trees. Two files with the same bytes are one blob.
- “
git addjust marks a file.” It writes the blob into.git/objectsright away. That’s why work yougit added but never committed can still be recovered (lesson 3).
Check yourself
1. You rename a 2 GB video in a repository and commit. Roughly how much does the store grow?
A few small objects: one new tree (the new name pointing at the same blob id) and one commit, plus new trees for any parent folders. The 2 GB blob is unchanged, so it isn't stored again.2. A colleague says they edited an old commit's message "in place". What actually happened to that commit's id?
It changed. The message is part of the commit's content, so a different message is a different object with a different id, and every commit after it gets a new id too (each one's parent line changed). The old objects are still in the store; lesson 2 shows why you no longer see them.3. Two developers on different machines commit the same files with the same message. Do the commits get the same id?
The trees and blobs do. The commits almost certainly don't: author name, email and time are in the commit's content, so any difference there gives a different id.Next: lesson 2 · Branches are just files.
2 · Branches are just files: refs, HEAD and the reflog
In one sentence: a branch is a 41-byte file holding one commit id, HEAD says which of those files you’re on, and every time one of them moves, git writes the old and new id in a log, so moving a branch doesn’t delete a commit.
The problem it solves
Lesson 1 left the store full of commits that are never edited. But you don’t type ids: you type main,
HEAD, HEAD~2. And after a git reset --hard HEAD~2, git log shows one commit where there were three:
8de11ef one
If reset doesn’t remove objects, where did two and three go? Nowhere. What changed is a name.
How it works
A ref is a file holding an id. A branch called main is the file .git/refs/heads/main:
cat .git/refs/heads/main
wc -c < .git/refs/heads/main
785c39812d3433a188dc61c2616b1dd81e00dce3
41
40 hex characters and a newline. That’s the whole branch. A commit made on main writes a new commit object, then
rewrites this file with the new id. git log starts from the id in the file and follows parent lines backwards.
A commit is “on” a branch only if you can reach it that way.
| Ref | File | Moves when |
|---|---|---|
branch main | .git/refs/heads/main | you commit, merge, reset or rebase on it |
tag v1 | .git/refs/tags/v1 | never, unless forced |
remote-tracking origin/main | .git/refs/remotes/origin/main (a clone writes the remote’s branches as lines in packed-refs, below) | you fetch or push |
git branch feature writes one more file with the same id in it. Nothing is copied.
HEAD is a ref to a ref. .git/HEAD normally holds a line naming the current branch, not an id:
ref: refs/heads/main
git switch feature rewrites that line to ref: refs/heads/feature (and updates your working folder). When you
commit, git follows HEAD to the branch file and moves that.
reset --hard rewrites the branch file. That’s all it does to history: after git reset --hard HEAD~2,
8de11ef710973cb3b8a3e5f0e24fb4379ebb64e3
is in .git/refs/heads/main, and the old tip is still in the store:
git cat-file -t 785c39812d3433a188dc61c2616b1dd81e00dce3
commit
(In this repo feature also still points at it, but the commit would be there even without that.)
The reflog: every place a ref has been
Each time a ref moves, git appends one line to its reflog, a plain text file under .git/logs/:
git reflog main
8de11ef main@{0}: reset: moving to HEAD~2
785c398 main@{1}: commit: three
6c13f26 main@{2}: commit: two
8de11ef main@{3}: commit (initial): one
main@{1} means “where main was one move ago”. So undoing the reset is one command:
git reset --hard main@{1}
git log --oneline
785c398 three
6c13f26 two
8de11ef one
HEAD has its own reflog, which also records every switch between branches. It’s the one to read when you don’t remember which branch you were on:
git reflog
785c398 HEAD@{0}: reset: moving to main@{1}
8de11ef HEAD@{1}: reset: moving to HEAD~2
785c398 HEAD@{2}: checkout: moving from feature to main
785c398 HEAD@{3}: checkout: moving from main to feature
785c398 HEAD@{4}: commit: three
6c13f26 HEAD@{5}: commit: two
8de11ef HEAD@{6}: commit (initial): one
Reflogs are local. They live in your .git and are never pushed or fetched. A fresh clone’s reflog has one
line, clone: from ..., and nothing from anyone else’s history. (git-reflog) They also don’t last forever; lesson 3 covers when entries
expire.
Detached HEAD
Check out a commit rather than a branch and .git/HEAD holds the id itself:
git checkout --detach HEAD
cat .git/HEAD
HEAD is now at 785c398 three
785c39812d3433a188dc61c2616b1dd81e00dce3
Commits you make now move HEAD and no branch. When you switch away, the only record of them is HEAD’s reflog: the classic way to “lose” work.
Try it on your computer
Practical 0 · A commit with no git commit: build blobs, trees
and commits by hand, make a branch by writing its ref, then corrupt an object on purpose and read what git fsck
says.
Go deeper: packed-refs
A repository with thousands of tags would mean thousands of tiny files. git pack-refs --all (which git gc runs)
moves refs into one file, .git/packed-refs, and removes the loose files:
# pack-refs with: peeled fully-peeled sorted
785c39812d3433a188dc61c2616b1dd81e00dce3 refs/heads/feature
8de11ef710973cb3b8a3e5f0e24fb4379ebb64e3 refs/heads/main
After that .git/refs/heads is empty, yet git rev-parse main still works. When the branch moves again, git
writes a loose file, and the loose file wins over the stale line in packed-refs:
grep main .git/packed-refs
cat .git/refs/heads/main
git rev-parse main
8de11ef710973cb3b8a3e5f0e24fb4379ebb64e3 refs/heads/main
785c39812d3433a188dc61c2616b1dd81e00dce3
785c39812d3433a188dc61c2616b1dd81e00dce3
So never read a branch with cat: ask git rev-parse. (git-pack-refs)
Go deeper: the reflog file
git reflog formats .git/logs/refs/heads/main, which is one line per move: old id, new id, who, when (seconds
and time zone), a tab, and why:
0000000000000000000000000000000000000000 8de11ef710973cb3b8a3e5f0e24fb4379ebb64e3 Ada <ada@example.com> 1767261600 +0000 commit (initial): one
...
785c39812d3433a188dc61c2616b1dd81e00dce3 8de11ef710973cb3b8a3e5f0e24fb4379ebb64e3 Ada <ada@example.com> 1767261600 +0000 reset: moving to HEAD~2
40 zeros means “the ref didn’t exist yet”. Because each line has a time, you can also ask by date:
main@{yesterday}, main@{2.hours.ago} (gitrevisions). Deleting a branch deletes its reflog file too, which is why HEAD’s
reflog is the one that saves you after git branch -D (lesson 3).
Common misunderstandings
- “
git reset --harddeletes commits.” It moves a branch. The commits stay in the store; only their name goes. It does throw away uncommitted edits in your working folder: edits you never staged were never objects and are gone, but edits yougit added are blobs in the store, and lesson 3 gets them back. - “A branch contains its commits.” It contains one id. “The commits on a branch” is everything reachable from that id through parent lines.
- “Detached HEAD is an error.” It’s a normal state: HEAD holds an id instead of a branch name. The only risk is committing there and switching away without making a branch.
Check yourself
1. You ran git reset --hard HEAD~3 on main and want it undone. What do you type, and why does it work?
git reset --hard main@{1} (or HEAD@{1} if you made no other move since). The reset added a line
to main's reflog whose old id is the tip you had; @{1} names it. The commits were never removed, so
pointing the branch back is enough.
2. A teammate deleted a remote branch and asks you to look in your reflog for it. You cloned this morning and never checked that branch out. Can you help?
Not from your reflog: reflogs are local, and yours records only what your own refs did. But if the branch existed when you cloned, yourorigin/<branch> still points at the commit the branch had when you
cloned (or last fetched), until a git fetch --prune removes it. Every teammate who fetched it has the same origin/<branch>.
3. cat .git/refs/heads/release says "No such file", but git log release works. What's going on?
The ref was packed: it's a line in .git/packed-refs. Git reads the loose file first and falls back to
packed-refs, so the branch exists; there's just no loose file for it.
Next: Practical 0 · A commit with no git commit, then lesson 3 ·
Getting lost work back, and when it really is gone.
3 · Getting lost work back, and when it really is gone
In one sentence: “lost” work stays in the store until a branch, a reflog line and a two-week grace period have all stopped protecting it and
git gcruns; until thengit reflogorgit fsckfinds it.
The problem it solves
Four ordinary mistakes at work:
| You ran | It looks like |
|---|---|
git reset --hard to the wrong commit | two days of commits gone from git log |
git branch -D on a branch that wasn’t merged | the branch and its commits gone |
git stash drop on the wrong stash | the stash gone from git stash list |
git reset --hard after git add, before any commit | the new file gone from your folder |
These commands move or delete names, never objects (lessons 1 and 2). So: what still points at the work?
The idea: what still points at it
An object lasts as long as something protects it. Four levels:
| What still points at it | Example | Find it with | Safe for |
|---|---|---|---|
| a branch or tag | everyday commits | git log | as long as the ref exists |
| only a reflog line | after reset --hard, branch -D | git reflog | 30 days (90 if the ref’s current tip still reaches it; for HEAD’s reflog: any branch or tag) |
| nothing | a dropped stash, a file git added then reset away, an expired reflog line | git fsck | until a git gc finds its file older than 2 weeks |
| it never was an object | edits you never git added | nothing | already gone |
The 90 and 30 days are gc.reflogExpire and gc.reflogExpireUnreachable, the 2 weeks is gc.pruneExpire
(git-gc). Unreachable means no ref and no reflog line leads to the
object, through any chain of parents or trees. Nothing is deleted until git gc runs. The 2 weeks count from
the age of the object’s file or pack (Go deeper), not from the reflog line’s expiry.
Finding each one
1. A reset (or a rebase, or an amend) that went wrong. The commits are held by the reflog, so git reflog
lists them, as lesson 2 showed. Notice what git fsck --unreachable prints here:
git reset --hard HEAD~2
git fsck --unreachable
git fsck --unreachable --no-reflogs
HEAD is now at e7488a1 one
unreachable blob 814f4a422927b82f5f8a43f8fab6d3839e3983f2
unreachable tree 6218aaa5fc1a58f5b32cbee55bc0cb0954022787
unreachable blob 4cb29ea38f70d7c61b2a3a25b02e3bdf44905402
unreachable tree 725322682524f6bb2c5ddf2d4c2bcad4adf95c6b
unreachable commit 3411c6e2fdbea8e3d9ecc07e7e8a0701e9f62a28
unreachable commit 785785b29a5da9a7dc84990308146bd094a6ff73
The first fsck prints nothing: a reflog line counts as pointing at a commit. Only --no-reflogs shows
the 6 objects of three and two (2 commits, 2 trees, 2 blobs). git reset --hard HEAD@{1} brings them
back.
2. A deleted branch. -d refuses an unmerged branch; -D deletes it and prints its id:
error: The branch 'feature' is not fully merged.
If you are sure you want to delete it, run 'git branch -D feature'.
Deleted branch feature (was 24b6130).
The branch’s own reflog file is deleted with it (.git/logs/refs/heads now holds only main). HEAD’s reflog
isn’t, and it recorded every commit you made while on the branch:
e7488a1 HEAD@{0}: checkout: moving from feature to main
24b6130 HEAD@{1}: commit: f2
8583618 HEAD@{2}: commit: f1
HEAD@{1}, the last commit made on the branch, is its tip. Recreate the branch there:
git branch feature HEAD@{1}
git log --oneline feature
24b6130 f2
8583618 f1
e7488a1 one
3. A dropped stash. A stash is a commit, and git stash list is the reflog of one ref, refs/stash. Drop
removes the reflog line, so nothing points at the stash any more. git stash drop prints the id; if it scrolled
away, fsck finds it, this time without --no-reflogs:
git fsck --unreachable | grep commit
unreachable commit 0fd67c504d8ba74680d7e3ac0837790afad2557e
unreachable commit 5622c56b73c6810a8d0e355ebc0a0808e14c15b2
The stash is the one git show --stat calls Merge: with WIP on ... (the other is its staged half). Applying it puts both the edit and the staged new file back (apply also prints a full git status, left out here):
git stash apply 0fd67c5
git status --short
M a.txt
A b.txt
4. A file you git added, then reset away. git add wrote a blob (lesson 1). No commit and no tree points at
it, so it’s dangling: unreachable, and nothing else unreachable points at it either. --lost-found copies
each dangling object into .git/lost-found/:
git fsck --lost-found
cat .git/lost-found/other/1e60a8aaab0441e0d37da0add56720cbf0ef1782
dangling blob 1e60a8aaab0441e0d37da0add56720cbf0ef1782
important notes
You get the contents back, not the file name: names live in trees, and this blob never got one. You also get
only the version you added: a later edit was never an object.
When it really is gone
One commit through every level, in a repo where three was just reset away (made with the real clock, so its
ids differ). git gc packs objects (Go deeper) and deletes what has run out:
git gc
git count-objects -v
count: 0
in-pack: 9
All 9 objects were packed, three included: the reflog still holds it, so gc keeps it. Now expire the
reflog line by hand and run gc again:
git reflog expire --expire-unreachable=now --all
git gc
git cat-file -t 1edeef92f49f59050b67fd8d90086bac47e40501
commit
Still there: gc packed the 3 objects main can reach and left the other 6 loose (git 2.39; newer gits use a cruft pack, see Go deeper), because their files are
minutes old, younger than 2 weeks. In a second repository whose loose object files were dated back to January,
the same expire and a plain gc deleted the commit at once. Here --prune=now does it:
git gc --prune=now
git cat-file -t 1edeef92f49f59050b67fd8d90086bac47e40501
fatal: git cat-file: could not get object info
Now the only copy is in another clone, if one has it. So after losing something, don’t run
git gc --prune=now “to clean up”. (The gc git starts on its own follows the same rules: see Go deeper.)
Try it on your computer
Practical 1 · The rescue (the capstone): from an empty folder, build a small history, lose work in all four ways, recover each one, then make one new commit truly gone with gc while everything you rescued survives.
Go deeper: what a stash is made of
git stash writes commits, not a special file. refs/stash holds the newest one:
tree 92658f61eef96067373c3259d382b95911f8d94a
parent 3411c6e2fdbea8e3d9ecc07e7e8a0701e9f62a28
parent 5622c56b73c6810a8d0e355ebc0a0808e14c15b2
...
WIP on main: 3411c6e three
It has 2 parents: the commit you were on (3411c6e) and a commit of your index (5622c56, “index on main”),
the staged state. Its own tree holds your tracked files as they were in the working folder.
* 0fd67c5 3411c6e 5622c56 WIP on main: 3411c6e three
|\
| * 5622c56 3411c6e index on main: 3411c6e three
|/
* 3411c6e 785785b three
Each git stash moves refs/stash and adds a reflog line, so stash@{1} is “where refs/stash was one move
ago”, exactly like main@{1}. git reflog stash prints the same list as git stash list. (git-stash)
Go deeper: packfiles, automatic gc and cruft packs
You rarely run gc yourself. “Some git commands run git gc --auto after performing operations that could
create many loose objects” (git-gc), which starts a real
gc once there are more than 6700 loose objects or more than 50 packs (gc.auto, gc.autoPackLimit). It obeys
the same expiry rules as a gc you type.
Objects start as loose files, one per object (lesson 1). git gc puts this repo’s 9 into one packfile plus an index:
.git/objects/pack/pack-3169a54a9966e6eb6b2d112d8042bbc55334193c.idx
.git/objects/pack/pack-3169a54a9966e6eb6b2d112d8042bbc55334193c.pack
git verify-pack -v lists what’s inside: here non delta: 9 objects. A pack may also store an object as a
delta, the difference from a similar object (none of these 9 is one). Ids don’t change: git cat-file -p HEAD reads the packed commit as before.
(gitformat-pack)
Packing resets the clock. A packed object’s age is its pack’s. Once the reflog line expires, gc keeps the object dated like its pack, or drops it if the pack is older than 2 weeks (pack-objects.c). Each gc rewrites the pack, so if gc runs often the 2 weeks start near the end of the 30 days and the protections mostly add up; if no gc ran since the object was written, they overlap.
Unreachable objects that are too young to prune need somewhere to live. git 2.39, on which this course was
tested, writes them back out as loose files (gc.cruftPacks defaults to false). From git 2.41, gc puts them in
a cruft pack, one pack that also records each object’s age, so the same two-week rule applies without thousands
of loose files (Highlights from Git 2.41). The
rescue is the same.
Common misunderstandings
- “If
git reflogdoesn’t show it, it’s gone.” Plaingit reflogis HEAD’s only. A stash’s commit never was in it, and a deleted branch’s commits are there only if you committed on it or checked it out;fsckstill finds the rest.
Check yourself
1. A colleague made a branch, committed on it and rebased it badly, all 3 weeks ago, and has made commits since. Can they get the branch as it was before the rebase?
Yes. The old commits are held by the branch's reflog (and HEAD's), and a line naming a commit the branch no longer reaches lasts 30 days.git reflog <branch> shows a rebase (finish) line; the entry
just below it is where the branch was before the rebase. git branch before-rebase <that id>
keeps it for good. (The 30 days count from when each line was written: here, when the commits were made.)
2. After a git stash drop, git fsck --unreachable lists two commits, 0fd67c5 and 5622c56, but git fsck --no-reflogs calls only 0fd67c5 dangling. Why, and which one do you apply?
5622c56 is the stash's index commit, one of 0fd67c5's 2 parents. It's unreachable, but
another unreachable object points at it, so it isn't a tip: not dangling. Apply the tip,
git stash apply 0fd67c5: it brings back the working-folder edits, and new files come back staged; --index restores the rest of
the staged state (git-stash).
3. After a bad reset, a teammate "helps" by running git reflog expire --expire-unreachable=now --all && git gc --prune=now. What can you still recover?
Nothing from your repository: the expire removed the reflog lines and --prune=now skipped the
two-week wait. Only the server (if you pushed) or another clone can help.
Next: Practical 1 · The rescue, the capstone.
Practical 0 · A commit with no git commit
Goal: a repository called
byhandwhose two commits you built yourself, blob by blob, withoutgit addorgit commit, with each id predicted before git printed it; then a corrupted object you find withgit fsckand repair.Time: ~35 minutes. Where: your own computer, in
~/git-internals-intro/, in a terminal. Needs git 2.28 or newer and python3 (for./lab). Read lesson 1 and lesson 2 first.
Task 1 · Get the lab
mkdir -p ~/git-internals-intro
cd ~/git-internals-intro
curl -fo lab http://localhost:8800/git-internals-intro/tools/lab
chmod +x lab
./lab setup p0
What setup did
It checked that git is 2.28 or newer (git init -b needs it) and knows your name and email (every commit needs
them), and nothing else: everything in this practical you type yourself. ./lab check p0 only runs read-only git
commands in your repository; every command it ran is in lab.log.
Task 2 · An empty repository
Make a repository called byhand in ~/git-internals-intro, with main as its first branch, and go into it.
Predict first: how many files are in
.git/objectsright now? Does.git/refs/heads/mainexist?
Solution
git init -b main byhand
cd byhand
find .git/objects -type f
ls .git/refs/heads
None, and no. .git/HEAD already says ref: refs/heads/main, but there’s no main file yet: HEAD names a branch
that doesn’t exist until its first commit.
Task 3 · Blobs, without git add
Store two pieces of content as blobs, with no file in your folder:
hellofollowed by a newline (the filegreeting.txtwill have this content)# notesfollowed by a newline (later,docs/notes.md)
Predict first: the id of the first blob. You’ve seen it.
Hint
git hash-object prints an id; -w also writes the object; --stdin reads the content from a pipe.
Solution
echo 'hello' | git hash-object -w --stdin
printf '# notes\n' | git hash-object -w --stdin
ce013625030ba8dba906f756967f9e9ca394464a
7c88e8a591766f27635a5bdab01832a59b04cf2e
The first is lesson 1’s id exactly: a blob’s id depends only on its bytes, so it’s the same in every repository on
every machine. Check that the two objects exist with find .git/objects -type f.
Task 4 · A tree and a commit
Make a commit whose snapshot is one file, greeting.txt, an ordinary file (mode 100644) holding the first blob.
Message: Built by hand.
| Command | What it does |
|---|---|
git update-index --add --cacheinfo <mode>,<id>,<path> | puts an entry in the index, the list git builds the next tree from (what git add fills) |
git ls-files --stage | prints the index |
git write-tree | writes a tree object from the index, prints its id |
git commit-tree <tree> -m <message> | writes a commit object for that tree, prints its id; moves no branch |
Predict first: the tree’s id. (Lesson 1’s first commit had exactly this snapshot.)
Solution
git update-index --add --cacheinfo 100644,ce013625030ba8dba906f756967f9e9ca394464a,greeting.txt
git ls-files --stage
git write-tree
100644 ce013625030ba8dba906f756967f9e9ca394464a 0 greeting.txt
57e9529754dc514a3ec10db2ff882018fbe1fcbf
git commit-tree 57e9529754dc514a3ec10db2ff882018fbe1fcbf -m 'Built by hand'
The tree is 57e9529, the same as lesson 1’s: a tree’s content is its entries, and the entries are the same. The
0 in ls-files --stage is the stage number, which is only something else during a merge conflict.
The commit’s id is not lesson 1’s, and not your neighbour’s: it contains your name, email and the current time.
Copy it from what you see; it’s <commit> below.
git log --oneline main now fails with unknown revision: the commit exists, but no branch names it.
Task 5 · Make it a branch
Point main at your commit, without git commit, git reset or editing files under .git by hand.
Hint
git update-ref <ref> <id> writes a ref safely: it locks the file and adds a line to the reflog.
Solution
git update-ref refs/heads/main <commit>
git log --oneline
git status --short
git log shows your commit. git status --short says:
D greeting.txt
Predict first: why “deleted”? Which of the three places, the store, the index and your folder, lacks
greeting.txt?
What you see
Your folder. The commit and the index both have greeting.txt, but you never made the file: the blob went straight
into the store. Bring the folder in line with the commit:
git restore greeting.txt
cat greeting.txt
hello
Task 6 · A second commit, with a folder
Make a second commit on main whose snapshot adds docs/notes.md holding the second blob. Message: Add notes.
Its parent is the first commit. Then make your folder match it.
Hint
Add the entry to the index with its full path; write-tree makes the docs tree for you. commit-tree takes the
parent with -p, and -p main works. Then update-ref again.
Solution
git update-index --add --cacheinfo 100644,7c88e8a591766f27635a5bdab01832a59b04cf2e,docs/notes.md
git write-tree
git cat-file -p 618fcd781e1ab99dacdb0cc0cb55df0bcc6a1760
git commit-tree 618fcd781e1ab99dacdb0cc0cb55df0bcc6a1760 -p main -m 'Add notes'
git update-ref refs/heads/main <the id commit-tree printed>
git restore .
git log --oneline
The root tree now has a tree entry for docs:
040000 tree e958723d91d4d067ace5d4b9538d767a2bc25e6a docs
100644 blob ce013625030ba8dba906f756967f9e9ca394464a greeting.txt
040000 is the mode of a directory. Now look at the branch’s reflog:
git reflog main
Two lines, your two commit ids, and nothing after the colon:
22b548d main@{0}:
1d8b58e main@{1}:
update-ref wasn’t given a reason (-m sets one); git commit would have written commit: Add notes. That’s how
the checker knows you didn’t use it.
Task 7 · Break it: a corrupted object
Objects are files; files get damaged (a bad disk, a sync tool, someone “cleaning up” .git). Damage the
greeting.txt blob on purpose, keeping a copy first. Objects are read-only, so chmod first:
cp .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a ../blob-backup
chmod u+w .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
printf 'junk' > .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
git cat-file -p ce01362
error: inflate: data stream error (incorrect header check)
error: unable to unpack ce013625030ba8dba906f756967f9e9ca394464a header
fatal: Not a valid object name ce01362
inflate is zlib’s decompression: the file isn’t zlib data any more. Find everything that’s wrong the way you would
in a real repository:
-
git fsck --fullchecks every object and every link between them. It names the file and what it expected:... error: ce013625030ba8dba906f756967f9e9ca394464a: object corrupt or missing: .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a missing blob ce013625030ba8dba906f756967f9e9ca394464a -
Which files does it break?
git ls-tree -r mainandgit ls-tree -r main~1list every path with its blob id:greeting.txtin both commits is that blob. -
Repair: the right bytes are anywhere with the same id: your backup, a teammate’s clone, the remote. In a clone the object is usually packed, so there’s no file to copy: remove the damaged file first (git won’t overwrite an object file that exists, even a broken one), then
git -C <their repo> cat-file blob ce01362 | git hash-object -w --stdinwrites it back.fsckchecks that the bytes hash to their id. Put your backup back and check again:cp ../blob-backup .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a git fsck --full; echo "exit $?"
Now delete it (rm that file) and run git fsck --full once more: only missing blob ce01362..., exit code 2
instead of 3. Put the backup back again.
Check your work
cd ~/git-internals-intro
./lab check p0
All 11 checks should pass.
Go deeper: what git commit does
What you did in tasks 4 to 6 is most of git commit: write-tree from the index, commit-tree with HEAD’s
commit as parent, then update-ref of the branch HEAD names, with a reflog reason (commit: Add notes). git add
is hash-object -w plus update-index.
The rest of git commit is hooks, the editor for the message, the
summary it prints, and a check that may start git gc on its own when the repository has grown
(git-gc): lesson 3 covers what that removes. The Git Book walks through the same plumbing in
Git Objects.
Next: lesson 3 · Getting lost work back, and when it really is gone.
Practical 1 · The rescue (capstone)
Goal: a repository called
rescuewhere you lose work in the four ways lesson 3 described, and get every piece back without retyping it; then one commit you destroy for good withgit gc, while everything you rescued survives.Time: ~40 minutes. Where: your own computer, in
~/git-internals-intro/, in a terminal. Read lesson 3 first.
cd ~/git-internals-intro
./lab update
./lab setup p1
./lab update gets the copy of the lab script that knows this practical. Skipped Practical 0, or your folder is in a
state you don’t trust? ./lab reset p1 moves your repositories aside and replays Practical 0’s solution.
This time you make commits the ordinary way, with git add and git commit. Your ids will differ from the ones
below (they contain your name and the time); read yours from your own output.
Task 1 · A history to lose
Make a repository rescue in ~/git-internals-intro, first branch main, with three commits:
one: a filea.txtholding the lineonetwo: adds the linetwotoa.txtthree: adds the linethree
Solution
git init -b main rescue
cd rescue
echo one > a.txt; git add a.txt; git commit -m one
echo two >> a.txt; git commit -am two
echo three >> a.txt; git commit -am three
git log --oneline
a2e7ddb three
9a55164 two
24b4168 one
Task 2 · Lost by a reset
git reset --hard HEAD~2
HEAD is now at 24b4168 one
Predict first: what does
git fsck --unreachableprint now? Andgit fsck --unreachable --no-reflogs?
What you see
The first prints nothing: a reflog line still points at three, so for fsck nothing is unreachable. The second
ignores reflogs and lists the 6 objects of two and three:
unreachable blob 814f4a422927b82f5f8a43f8fab6d3839e3983f2
unreachable tree 6218aaa5fc1a58f5b32cbee55bc0cb0954022787
unreachable commit a2e7ddbc99d0a416468179766c8fdf49db9509bb
...
Put main back at three, without typing its id.
Hint
git reflog lists where HEAD has been; HEAD@{n} names a line of it.
Solution
git reflog
git reset --hard HEAD@{1}
24b4168 HEAD@{0}: reset: moving to HEAD~2
a2e7ddb HEAD@{1}: commit: three
9a55164 HEAD@{2}: commit: two
24b4168 HEAD@{3}: commit (initial): one
HEAD is now at a2e7ddb three
Task 3 · Lost with a branch
From main, make a branch feature with two commits: f1 (a file f.txt holding f1) and f2 (adds the
line f2). Switch back to main and delete feature, first with -d, then with -D:
error: The branch 'feature' is not fully merged.
If you are sure you want to delete it, run 'git branch -D feature'.
Deleted branch feature (was 8b68bea).
Newer git words the refusal differently (git 2.47.3: error: the branch 'feature' is not fully merged, with the
git branch -D suggestion on hint: lines); it means the same.
Pretend the last line scrolled away. Recreate feature at f2 without that id.
Hint
ls .git/logs/refs/heads: the branch’s own reflog went with it. HEAD’s didn’t, and you made both commits on HEAD.
Solution
git switch -c feature
echo f1 > f.txt; git add f.txt; git commit -m f1
echo f2 >> f.txt; git commit -am f2
git switch main
git branch -d feature
git branch -D feature
git reflog -4
a2e7ddb HEAD@{0}: checkout: moving from feature to main
8b68bea HEAD@{1}: commit: f2
2f4ae19 HEAD@{2}: commit: f1
a2e7ddb HEAD@{3}: checkout: moving from main to feature
git branch feature HEAD@{1}
git log --oneline main..feature
8b68bea f2
2f4ae19 f1
main..feature means “commits on feature that aren’t on main”: exactly the two you rescued.
Task 4 · Lost with a stash
On main, add the line four, not committed yet to a.txt, create b.txt holding a new file and
git add it (not a.txt). git status --short shows M a.txt and A b.txt. Now:
git stash
git stash drop
git stash list
Saved working directory and index state WIP on main: a2e7ddb three
Dropped refs/stash@{0} (a017ee4dd5858879a25d79f0228c05b37bf9c614)
git stash list prints nothing. Pretend the id in the Dropped line scrolled away. Put the stash back into
git stash list, with the message rescued stash, so you can apply it whenever you like.
| Command | What it does |
|---|---|
git log -1 --format='%h %s' <id> | one commit’s short id and subject |
git stash store -m <message> <id> | adds a commit to refs/stash and its reflog: what git stash does after writing the commits |
Hint
fsck finds the stash’s commits even without --no-reflogs (lesson 3 says why). There are two; the stash is the
one whose subject starts with WIP on.
Solution
for id in $(git fsck --unreachable | awk '/commit/ {print $3}'); do git log -1 --format='%h %s' $id; done
ceae614 index on main: a2e7ddb three
a017ee4 WIP on main: a2e7ddb three
git stash store -m 'rescued stash' a017ee4
git stash list
git stash show --stat
stash@{0}: rescued stash
a.txt | 1 +
b.txt | 1 +
2 files changed, 2 insertions(+)
Both changes are in it: the edit you never staged and the new file you did. Leave it stored; the checker reads it.
Task 5 · Lost before any commit
Create notes.txt holding important notes, git add it, then git reset --hard. ls no longer shows it.
Get it back, and commit it on main with the message Recover notes.
Predict first: will git give you back the name
notes.txt?
Solution
git fsck --lost-found
ls .git/lost-found/other
dangling blob 1e60a8aaab0441e0d37da0add56720cbf0ef1782
1e60a8aaab0441e0d37da0add56720cbf0ef1782
cp .git/lost-found/other/1e60a8aaab0441e0d37da0add56720cbf0ef1782 notes.txt
git add notes.txt
git commit -m 'Recover notes'
No name: only a tree gives a blob a name, and this one never got into a tree. You chose notes.txt yourself. The id
is the same as lesson 3’s and every reader’s: the same bytes, the same blob. In a repository with more dangling
blobs, cat each one to find yours.
Task 6 · Break it: the gc that makes it gone
Make one more commit on main, doomed, adding a file doomed.txt. Save its id outside the repository, then
lose it:
git rev-parse HEAD > ../doomed-id
git reset --hard HEAD~1
HEAD is now at 53453ef Recover notes
Predict first: after each of these three steps, does
git cat-file -t $(cat ../doomed-id)still saycommit?
git gcgit reflog expire --expire-unreachable=now --all, thengit gcgit gc --prune=now
What you see
Run them in order, with git cat-file -t $(cat ../doomed-id) after each, and git count-objects -v after
steps 1 and 2:
| After | cat-file -t | Why |
|---|---|---|
1. git gc | commit | a reflog line still points at it, so gc packs it with the rest: in-pack: 27 |
2. expire, then gc | commit | no reflog line left, but its 3 object files are minutes old, younger than 2 weeks: count: 3 loose, in-pack: 24 |
3. gc --prune=now | fatal: git cat-file: could not get object info | --prune=now skips the two weeks |
On git 2.41 or newer these 3 objects go into a cruft pack instead of loose files (lesson 3, Go deeper), so your
count-objects numbers differ; cat-file -t still says commit until step 3.
The 2 weeks run on the real clock: your objects were made minutes ago, so step 2 keeps them. Now find out what’s left, in the order you would after a real loss:
git reflogandgit reflog main: no line names the doomed id.git fsck --unreachable --no-reflogs: prints nothing; there’s nothing unreachable left to find.- The only way back would be another clone that has the commit.
And what you rescued?
git stash list
git log --oneline main..feature
stash@{0}: rescued stash
8b68bea f2
2f4ae19 f1
Still there: a branch and the stash’s ref point at them, so no gc removes them. The expire removed the doomed
lines, which nothing reaches any more, but kept HEAD’s commit: f1 and commit: f2 lines: feature reaches those. Rescuing means giving lost work a name: a branch, a
tag, a stash entry, a commit. Then it’s ordinary work again.
Check your work
cd ~/git-internals-intro
./lab check p1
All 12 checks should pass.
Next: that’s the course. Back to the front page for the whole path.