Git as a graph
Commits, trees, blobs, refs, the index, and why understanding the graph makes every command obvious.
Most people learn Git as a list of commands to type when they want something to happen: add, commit, push, and a memorised incantation for when it goes wrong. That works until the day it does not, and then there is nothing to reason from.
There is a smaller thing to learn instead. Git stores snapshots in a graph, and every command you will ever run either adds a node to that graph or moves a pointer around in it. Learn the graph and the commands stop needing to be memorised, because you can work out what each one must do.
A repository is a graph, not a folder of versions
The mental model most beginners arrive with is a stack of saved versions, like a document's revision history. It is the wrong shape, and it makes branch and merge look like magic.
What Git actually keeps is a set of objects, each named by the hash of its own contents, plus a handful of tiny files that point into that set. Nothing is ever edited. New objects are added, and pointers move.
That single design decision explains almost everything else: why a commit hash changes when you amend it, why a branch is instant to create, why rebasing produces different commits, and why almost nothing you do is actually destructive.
Three kinds of object, and one of them is your file
Start with a file. Git turns its contents into an object called a blob:
$ echo "hello" > greeting.txt
$ git hash-object greeting.txt
ce013625030ba8dba906f756967f9e9ca394464aNow the part worth pausing on. That hash is not a property of your repository, or your machine, or the file's name. It is a property of the bytes:
$ echo "hello" | git hash-object --stdin
ce013625030ba8dba906f756967f9e9ca394464a
$ echo "hello" > copy.txt
$ git hash-object copy.txt
ce013625030ba8dba906f756967f9e9ca394464aSame content, different name, same object. Every Git repository on earth holding a file whose content is hello and a newline is storing it under that exact hash. This is why copying a file costs Git nothing, and why a rename is not stored as a rename — Git works it out afterwards by noticing the same blob under a new name.
A blob has no name and no path. So a second object type holds those: a tree is a directory listing that maps names to blobs and to other trees.
$ git cat-file -p HEAD^{tree}
100644 blob ce013625030ba8dba906f756967f9e9ca394464a greeting.txtAnd a commit points at one tree, plus the commit or commits that came before it:
$ git cat-file -p HEAD
tree 57e9529754dc514a3ec10db2ff882018fbe1fcbf
author Demo <a@b.c> 1767241800 +0530
committer Demo <a@b.c> 1767241800 +0530
Add a greetingThat is a whole commit. A pointer to a complete snapshot of the project, a parent, two names with timestamps, and a message. The commit above has no parent line, which is exactly what makes it a root commit — and why there is nothing before it to move back to.
Notice also that author and committer are separate fields. They are usually the same person, and they stop being the same the moment somebody rebases or cherry-picks your work: the author stays you, the committer becomes them.
A branch is a file with forty characters in it
Here is where the mystery usually is, and here is the whole answer:
$ cat .git/refs/heads/main
0ca842bc5ee2e0977c1f3e8305290a629e143abdThat is the branch. Not a copy of the code, not a directory, not a container that commits live inside. A file holding one hash. Creating a branch writes forty-one bytes, which is why it is instant — and why "branch less, branches are expensive" is advice imported from a different version-control system.
HEAD is one more pointer, and it usually points at a branch rather than at a commit:
$ cat .git/HEAD
ref: refs/heads/mainRead those two files together and you can state what a commit does in one sentence: write the objects, then rewrite the file that HEAD names. Everything in Git that looks like it is moving your code is moving a pointer.
Under the hood: how git log walks the graph
A commit object does not just point at one tree — it also lists the hash of its parent commit (a merge commit lists two, or more for an octopus merge). That is the entire mechanism git log runs on: start at the hash a ref names, print the commit, follow the parent line to the next commit, and repeat until a commit has no parent (a root commit). There is no separate "history" data structure anywhere in .git — history is just commit objects pointing backward at other commit objects, which is what makes a repository a directed acyclic graph (DAG): every edge points from a commit to something older, so there is nothing to walk into a cycle with.
$ git cat-file -p HEAD | head -2
tree 57e9529754dc514a3ec10db2ff882018fbe1fcbf
parent 22e4f03a9c8b0e1d6f4a2b3c5d7e8f9a0b1c2d3ePlain git log follows that parent chain in roughly reverse-chronological order; git log --graph draws the same walk with lines showing where branches forked and rejoined — it is drawing the shape of the parent pointers, not computing anything Git did not already have stored. Exactly how ties are broken when two commits share a timestamp is an implementation detail rather than something worth memorising; --topo-order is the flag that asks for the graph-consistent ordering instead, on the rare occasion the default order is confusing.
The same mechanism answers a question this lesson has not asked yet: where did two branches diverge? git merge-base branchA branchB walks backward from both tips through their parent pointers until it finds a commit reachable from both — the nearest common ancestor in the DAG. Rebase and merge both start there, which is the next lesson's subject.
The index is the third state, and it is why status has two columns
Between the files you are editing and the last commit there is a third place, and most confusion about git status is really confusion about this. The index — also called the staging area — holds the version your next commit will contain.
So a file has three versions at once, and git status reports two comparisons in two columns:
$ echo "hello there" > greeting.txt
$ git status --short
M greeting.txt
$ git add greeting.txt
$ git status --short
M greeting.txtThe letter did not change. The column did. The right column is working tree versus index; the left is index versus last commit. git add did not save anything permanently; it moved the change one column to the left.
The two diff commands split along the same line, and this is the answer to "why does git diff show nothing when I clearly changed something":
$ git diff --stat
← nothing: the working tree now matches the index
$ git diff --cached --stat
greeting.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)edit the file. You change the bytes on disk. Git has done nothing at all — it does not watch your editor, and it has not stored this version anywhere. If the disk died now, the change is gone.
git add. The blob is written NOW, at add time, not at commit time. The content is already safe inside .git before you have typed a commit message — which is what makes adding early genuinely worth doing.
git commit. A tree and a commit object are written, and then .git/refs/heads/main is rewritten to hold the new commit's hash. That last move IS the commit.
git branch fix. Forty-one bytes are written to .git/refs/heads/fix. No objects, no copying, no snapshot taken. This is why a branch per task costs nothing worth counting.
git switch fix. Only HEAD changed. Your files were rewritten out of objects Git already had — nothing was created and nothing was destroyed.
Detached HEAD is not an error
Check out a commit instead of a branch and Git prints a wall of text that reads like a warning. It is not one. Look at what actually changed:
$ git checkout 0ca842b
$ cat .git/HEAD
0ca842bc5ee2e0977c1f3e8305290a629e143abdHEAD now holds a hash directly instead of ref: refs/heads/main. That is the entire meaning of "detached": HEAD is not pointing at a branch, so there is no branch file to rewrite when you commit.
Which is the real risk, and it is worth stating precisely: commits you make here are perfectly valid objects, but nothing points at them. Switch away and they become unreachable — not deleted, but with no name to find them by. If you made something you want, give it a name before you leave:
git switch -c experiment # names the commit you are sitting onStash and tags: two more refs
A stash is a commit you did not name: git stash push -m "wip: rate limit" records the working tree and the index as a pair of commit objects, resets both to HEAD, and puts the pair on the refs/stash list. git stash list shows the list, git stash apply stash@{1} replays one without dropping it, and pop does both — which is the trap: pop on a conflict leaves the stash in place and the conflict in your tree, and pop in a repository whose stash stack another checkout also pushes to can hand you someone else's work. Prefer a real commit on a WIP branch when the work will outlive the afternoon; a stash is for the ten minutes between "I need to switch branches" and "I am back".
A tag is a ref that does not move: v1.14.2 pointing at one commit forever, where a branch pointer advances. A lightweight tag is just the pointer; an annotated tag (git tag -a v1.14.2 -m "...") is its own object with an author, a date and a message, and it is the one to use for releases because it can be signed and because git describe counts from it (v1.14.2-7-g3f2a9c1: seven commits past the tag, at that hash) — the version string a good /actuator/info prints. Tags are not pushed by default; git push origin v1.14.2 publishes one. The CI/CD course's rule that a deployment is traceable to a commit is a tag or a SHA on the image, and the tag is the one a human can read.
The reflog is the undo you did not know you had
Because Git only ever adds objects and moves pointers, "losing work" almost always means a pointer moved and you do not know where it was before. Git records every move of HEAD:
$ git reset --hard HEAD~1
$ git log --oneline
0ca842b Add a greeting
$ git reflog
0ca842b HEAD@{0}: reset: moving to HEAD~1
22e4f03 HEAD@{1}: commit: Say more
0ca842b HEAD@{2}: commit (initial): Add a greetinggit log says the commit is gone. It is not gone — the branch merely stopped pointing at it. 22e4f03 is right there, and git reset --hard 22e4f03 puts it back.
This is the most valuable paragraph in this lesson for the day something goes wrong. A hard reset, a bad rebase, a branch deleted too early, an amend that swallowed a commit — in every one of them the objects still exist and the reflog holds the hash. Entries do expire (ninety days for reachable commits, thirty for unreachable ones, by default), so the window is long but not infinite.
Try it yourself
Trace the graph by hand
- Create a repo and make three commits on
main:A,B,C. - From
B, create and switch to a branchfeature, then commitDandEon it. - Before running anything, predict what
git merge-base main featurewill print. - Run it, then run
git log --oneline --graph --allto see the shape.
Why the answer is B, not A or C
feature branched off at B, so walking backward from feature's tip through parent pointers (E → D → B → A) and backward from main's tip (C → B → A) both reach B before either reaches A. B is the first commit both chains have in common — the nearest common ancestor — so git merge-base main feature prints B's hash. A is also reachable from both, but it is not the nearest one; C, D and E are each reachable from only one tip. This is exactly the computation git merge and git rebase run before either one touches a single line of your files.
Misconceptions
- "A commit stores a diff." It stores a full snapshot — a tree pointing at blobs for every file, most of them the same unchanged blobs the parent's tree already pointed at. Git computes diffs on demand by comparing two snapshots; it never stores one, which is also why detecting a rename costs nothing and requires nothing special to have been recorded beforehand.
- "
git logwalks a straight line of history." It walks a DAG. A merge commit has two parents, so the history of a repository with merges is a graph with forks and joins, not a line —--graphis popular precisely because the default output hides that shape.
Sources
- Pro Git (Chacon & Straub), Chapter 10, "Git Internals" — the object model, refs and packfiles.
git help log,git help merge-base— Git's own documentation for the traversal and common-ancestor commands.- The Git project,
Documentation/technical/— the on-disk object and pack formats.