Skip to content
$ lynuxpro
← Git

LESSON 18 OF 21 · EXPERT · 20 MIN

Git internals

HOW IT WORKSGit's object model

hashrefs/heads/maina branchcommitauthor, messageparent committreea folderblobapp.py contentstreedocs/blobguide.md
1/4

A branch is a small file containing a commit hash.

$ cat .git/refs/heads/main

Most Git confusion disappears once you see what Git actually stores. Underneath the commands, Git is a simple content-addressable database of four kinds of objects, plus a few small files called references that point into it. This lesson opens the .git folder and uses Git's low-level "plumbing" commands to look at blobs, trees, commits and refs, so that branches, resets, rebases and the reflog all make obvious sense.

In simple words

  • Object: how Git stores everything: blobs (file contents), trees (folders), commits and tags.
  • Hash: a unique ID calculated from an object's content. If the content changes, the ID changes.
  • Reference: a tiny file holding a commit hash. Branches and tags are references.
  • Porcelain vs plumbing: porcelain commands are the friendly everyday ones. Plumbing commands are the low-level building blocks.

Two layers: porcelain and plumbing

  • Porcelain commands are the friendly ones you use daily: add, commit, switch, merge.
  • Plumbing commands expose the internals: cat-file, hash-object, ls-tree, rev-parse, update-ref. Scripts and tools use them because their output is stable.

Set up

git config --global user.name "Leela Kumar"mkdir internalscd internalsgit initmkdir docsprintf 'print("hi")\n' > app.pyprintf '# Guide\n' > docs/guide.mdgit add .git commit -m "Add app and guide"
SHELLbashutf-8 · 9L

What is inside .git

.git/├── HEAD            which branch you are on├── config          repository settings and remotes├── objects/        the database: every blob, tree, commit and tag├── refs/│   ├── heads/      one file per branch, containing a commit hash│   ├── tags/       one file per tag│   └── remotes/    remote-tracking branches like origin/main├── index           the staging area (a binary file)├── hooks/          hook scripts└── logs/           the reflog
OUTPUTterminalutf-8 · 11L

References are tiny files

cat .git/HEADcat .git/refs/heads/maingit rev-parse HEAD
SHELLbashutf-8 · 3L
ref: refs/heads/main5e1f1b112a35d39e18d785ae6453d1fcb00221e35e1f1b112a35d39e18d785ae6453d1fcb00221e3
OUTPUTterminalutf-8 · 3L

That is all a branch is: a file containing a commit hash. HEAD usually contains a symbolic reference to the current branch. Switch branches and watch it change:

git switch -c feature/xcat .git/HEADgit switch main
SHELLbashutf-8 · 3L
Switched to a new branch 'feature/x'ref: refs/heads/feature/xSwitched to branch 'main'
OUTPUTterminalutf-8 · 3L

In detached-HEAD state, .git/HEAD contains a commit hash directly instead of ref: ….

(For speed, Git sometimes packs many refs into one file, .git/packed-refs. git rev-parse and git show-ref always give the right answer.)

The four object types

ObjectContainsNamed by
blobthe raw content of one file (no name, no permissions)hash of the content
treea folder listing: mode, type, hash and name of each entryhash of the listing
commitone tree, parent commit(s), author, committer, messagehash of all that
tag (annotated)an object hash, tag name, tagger, messagehash of all that

Every object's name is the hash (SHA-1, or SHA-256 in repositories created with that option) of its content. This is what "content-addressable" means.

Look at a commit

git cat-file -t HEADgit cat-file -p HEAD
SHELLbashutf-8 · 2L
committree 5999233c9280f9c503073a7703f36122c7e23974author Leela Kumar <learner@lynuxpro.dev> 1795166170 +0000committer Leela Kumar <learner@lynuxpro.dev> 1795166170 +0000Add app and guide
OUTPUTterminalutf-8 · 6L

A commit is just a few lines of text: the hash of a tree (the snapshot), the parent commit(s) (none for the first commit), who and when, and the message. -t prints the type, -p pretty-prints the content.

Follow it to the tree

git cat-file -p HEAD^{tree}
SHELLbashutf-8 · 1L
100644 blob fcd199aa5edc5decd1b207203028c43e765adc22	app.py040000 tree 8ff9b580432618ffd84ddc69173f6a4eb42dcd34	docs
OUTPUTterminalutf-8 · 2L

The root tree lists app.py as a blob and docs as another tree. 100644 is a normal file, 100755 an executable, 040000 a folder, 120000 a symlink. git ls-tree HEAD shows the same thing.

And to the blob

git cat-file -p HEAD:app.pygit hash-object app.py
SHELLbashutf-8 · 2L
print("hi")fcd199aa5edc5decd1b207203028c43e765adc22
OUTPUTterminalutf-8 · 2L

git hash-object computes the name a file would have as a blob. It matches the hash in the tree, because the name is the content's hash. (git hash-object -w actually writes it into the database.)

Why this design matters

The object model explains Git's behaviour:

  • Snapshots, not diffs. Each commit points to a complete tree. Unchanged files reuse the same blob (same content, same hash), so a new commit stores only what changed. Diffs are calculated when you ask for them.
  • Deduplication. Two identical files anywhere in history are stored once.
  • Integrity. A commit's hash covers its tree, which covers every blob, and its parent, which covers all earlier history. Change one byte anywhere and every hash after it changes, so corruption or tampering is detectable.
  • Immutability. Objects never change. "Amending" or "rebasing" creates new commits; the old ones remain until garbage collection, which is why the reflog can recover them.
  • Cheap branches. A branch is a 41-byte file. Creating one copies nothing.
  • Fast switching. Switching branches means reading another tree and updating only the files whose blob hashes differ.

How commands map to the model

CommandWhat it does to objects and refs
git add filewrites a blob, records it in the index
git commitwrites trees from the index, writes a commit, moves the current branch ref
git branch xcreates refs/heads/x containing the current commit hash
git switch xrewrites HEAD, updates working tree and index to x's tree
git reset --soft Amoves the branch ref to A, nothing else
git mergewrites a commit with two parents (or just moves the ref, for fast-forward)
git rebasewrites new commits with new parents, moves the ref
git tag -awrites a tag object, creates refs/tags/…
git gcpacks objects into compressed packfiles, deletes old unreachable ones

Storage: loose objects and packfiles

New objects are first stored as individual zlib-compressed loose files under .git/objects/ab/cdef… (the first two hex characters form the folder name). Periodically, git gc (or background git maintenance) packs them into packfiles, which also store similar objects as deltas of each other. That is how a repository with years of history stays small.

git count-objects -vH
SHELLbashutf-8 · 1L

Useful plumbing for scripts

git rev-parse --short HEAD               # short hash, for image tagsgit rev-parse --abbrev-ref HEAD          # current branch namegit rev-parse --show-toplevel            # repository rootgit diff --name-only origin/main...HEAD  # changed files, for CIgit status --porcelain                   # stable, script-friendly statusgit for-each-ref --format='%(refname:short)' refs/heads/   # list branches
SHELLbashutf-8 · 6L
git rev-parse --short HEADgit rev-parse --abbrev-ref HEAD
SHELLbashutf-8 · 2L

CI pipelines use exactly these to tag images with the commit hash and to build only what changed.

Real-world scenario: "the repository is corrupt"

After a disk filled up during a push, a self-hosted runner reported error: object file .git/objects/3f/… is empty. Knowing the object model, the engineer understood that one loose object had been truncated, not the whole repository. git fsck listed the broken object, and because every clone has the full database, re-fetching from the server (git fetch origin after removing the empty file, or simply re-cloning the runner's cache) restored it. No history was lost, which is exactly what content-addressed storage with full clones guarantees.

Common mistakes

  • Editing files inside .git by hand (other than with care for experiments). Use plumbing commands like git update-ref.
  • Thinking commits store diffs, and being surprised that switching between distant branches is fast.
  • Believing amend or rebase "edits" commits. They create new ones.
  • Parsing porcelain output in scripts (git status, git branch); use --porcelain or plumbing commands.

Practice

  1. Print .git/HEAD and the file for your current branch, and compare with git rev-parse HEAD.
  2. Use git cat-file -p to walk from HEAD to its tree, to a subtree, to a blob.
  3. Check that git hash-object on a file matches the blob hash in the tree.
  4. Make a second commit that changes only one file, then compare the two root trees: which entries changed?
  5. Create a branch and watch .git/HEAD change when you switch.

Cheat sheet

cat .git/HEAD                     current branch (symbolic ref)git rev-parse HEAD | --short | --abbrev-ref HEADgit cat-file -t | -p <object>     type / contentgit cat-file -p HEAD^{tree}       the commit's treegit cat-file -p HEAD:path         a file in a commitgit ls-tree HEAD                  list the root treegit hash-object [-w] file         blob hash (and store it)git count-objects -vH             database sizegit fsck                          check integritygit gc                            pack objects
OUTPUTterminalutf-8 · 10L

Key takeaways

  • Git stores four object types (blob, tree, commit, tag), each named by the hash of its content.
  • Branches and tags are tiny files containing hashes; HEAD points to the current branch.
  • Commits are snapshots that reuse unchanged blobs, which makes Git small, fast and tamper-evident.
  • Objects are immutable: amend and rebase create new commits, which is why the reflog can recover old ones.
  • Plumbing commands like rev-parse and cat-file are the stable interface for scripts and CI.