DevOps, CI/CD and IaCVol. 8 · Part VIII
0 / 0

Shelves / DevOps, CI/CD and IaC

DL·92

Git

Git from the inside out: the content-addressed object database (blobs, trees, commits, annotated tags), hashes and packfiles, refs, HEAD and the index; then every everyday operation explained in terms of that model: commit, branch, merge (fast-forward and three-way), rebase (including interactive and --onto), cherry-pick, revert, reset and its modes, restore/switch, reflog and recovery, tags, remotes and remote-tracking branches, hooks, commit and tag signing, branching workflows, and scaling to large repositories, with object hashing in Python, Go, Rust and Java.

38 topics · ~23 min read · 32-question quiz
Updated Suggest a correction

Start here: what Git actually stores

Snapshots, not differences

Git doesn't store "changes". Each commit is a snapshot of the whole project plus a pointer to its parent commit(s). It stores this efficiently in a tiny database of objects, each named by a hash of its contents. Make one commit and look inside:

Text
$ echo "Masala dosa 80" > menu.txt; git add menu.txt; git commit -m "Add menu"
$ find .git/objects -type f
.git/objects/68/c994f2d5e035a3a86c447157a00d2e8e10637e
.git/objects/9e/062343e32388ee8636ed8fd36d1c2f37f44206
.git/objects/d9/6b399f0cf14ecb3017aa90f5cbf15050403077
$ git cat-file -p 68c994f…        # the commit
  tree d96b399f0cf14ecb3017aa90f5cbf15050403077
  author Asha <asha@tiffin.example> 1793338341 +0000
  committer Asha <asha@tiffin.example> 1793338341 +0000

  Add menu
$ git cat-file -p d96b399           # its tree (a directory listing)
  100644 blob 9e062343e32388ee8636ed8fd36d1c2f37f44206	menu.txt
$ git cat-file -p 9e06234           # the blob (file contents)
  Masala dosa 80
$ printf "blob 15\0Masala dosa 80\n" | sha1sum      # the blob ID is just a hash of its content
9e062343e32388ee8636ed8fd36d1c2f37f44206  -

Three objects: a blob (the file's bytes), a tree (a directory: names, modes and the IDs of blobs and subtrees) and a commit (a tree ID, parent IDs, author, committer, message). Because every ID is a hash of content, identical content is stored once, any change to a file changes its blob ID, which changes the tree's ID, which changes the commit's ID: history can't be altered without everyone noticing. (Git is migrating from SHA-1 to SHA-256 object names; repositories can already be created with --object-format=sha256.)

Branches are just names

Text
$ cat .git/HEAD; cat .git/refs/heads/main      # a branch is a file holding a commit ID
ref: refs/heads/main
68c994f2d5e035a3a86c447157a00d2e8e10637e

A branch is a small file containing one commit ID; committing moves it forward. HEAD says which branch you're on. That's why branches are instant and free: creating one writes 41 bytes.

Branching, merging and conflicts

Two lines of work diverge: one branch raises the dosa price, main adds idli. Merging them:

Text
$ git log --graph --oneline --all
* 282a7d6 Add idli
| * 08bb770 Raise dosa price
|/
* 68c994f Add menu
$ git merge price-rise
Auto-merging menu.txt
CONFLICT (content): Merge conflict in menu.txt
Automatic merge failed; fix conflicts and then commit the result.
$ cat menu.txt
<<<<<<< HEAD
Masala dosa 80
Idli 50
=======
Masala dosa 95
>>>>>>> price-rise
$ printf "Masala dosa 95\nIdli 50\n" > menu.txt; git add menu.txt; git commit -m "Merge price-rise"
$ git log --graph --oneline
*   3779653 Merge price-rise
|\
| * 08bb770 Raise dosa price
* | 282a7d6 Add idli
|/
* 68c994f Add menu

Git merges line by line against the common ancestor. Both sides changed the same region of the file, so Git couldn't choose and asked a human, marking both versions. Once resolved and committed, the merge commit has two parents, recording that both lines of work are included. (A rebase would instead replay one branch's commits on top of the other, giving a straight line of new commits; chapter sections on workflows cover when each fits.)

Almost nothing is ever lost

Text
$ git reset --hard HEAD~1   # oops: the merge is "lost"
282a7d6 Add idli
68c994f Add menu
$ git reflog | head -4
282a7d6 HEAD@{0}: reset: moving to HEAD~1
3779653 HEAD@{1}: commit (merge): Merge price-rise
282a7d6 HEAD@{2}: commit: Add idli
68c994f HEAD@{3}: checkout: moving from price-rise to main
$ git reset --hard HEAD@{1}   # recovered
3779653 Merge price-rise

reset --hard moved the branch back, but the merge commit still existed as an object. The reflog records every position HEAD has had (for 90 days by default), so moving back was one command. What can be lost is work you never committed or stashed: reset --hard overwrites uncommitted changes for good.

How deep to go in Git

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Commit, branch, merge, push and pull; read git log --graph
L2 Resolve conflicts, rebase, stash, cherry-pick, work with remotes and pull requests
L3 Explain objects, refs, the index, packfiles, merge bases and the reflog
L4 Recover lost work, bisect regressions, fix bloated history and broken branches
L5 Choose branching workflows, repository layout (mono vs poly) and policies for teams
L6 Operate Git at scale: large monorepos, partial clone, signing policy and server performance

Git's model in one paragraph

Git is a content-addressed key-value store of immutable objects, plus a small set of mutable references (names pointing to objects). Every commit is a snapshot of the whole project (not a diff), pointing to its parent commits, so history forms a directed acyclic graph (DAG). Branches are just movable pointers into that graph. Almost every command either adds objects or moves references. Once you see it this way, merge, rebase, reset and recovery stop being magic.

The object database

Four object types

All objects live in .git/objects/, named by the hash of their content:

Object Contains Analogy
blob The bytes of one file's content (no name, no permissions) File contents
tree A list of entries: mode (100644 file, 100755 executable, 120000 symlink, 040000 directory, 160000 submodule), name, and the hash of a blob or subtree A directory listing
commit Hash of the root tree, zero or more parent commit hashes, author (name, email, timestamp), committer, message, optional signature A snapshot with metadata and history
tag (annotated) Hash of the target object, type, tag name, tagger, message, optional signature A signed, named label
HEAD main commit C29fc3… commit C13a1e… parent tree T2 tree T1 blob b2README v2 tree S1 (src/) blob b1README v1 blob m1main.go unchanged src/ treeis shared by hash:no duplication
Git objects for two commits. Each commit points to a root tree (the full snapshot) and its parent. Trees point to blobs and subtrees. The second commit changed only README, so it gets a new blob and new trees on the path to it, while unchanged files and directories are shared by hash.

Because objects are named by content hash:

  • Identical content is stored once (deduplication across files, commits and branches).
  • Objects are immutable: changing anything (even one byte of a commit message) produces a different hash, so "editing" history really creates new commits.
  • Integrity: a commit hash transitively covers every tree, blob and parent beneath it. If any byte of history changed, the hash would too (a Merkle DAG, like blockchains and Merkle trees in Vol. 5 ch. 71).

How a hash is computed

An object's ID is hash(type + " " + size + "\0" + content). Historically SHA-1 (40 hex characters). SHA-1 has known collision attacks (SHAttered, 2017); Git uses a hardened SHA-1 that detects those attack patterns, and supports SHA-256 repositories (git init --object-format=sha256). Git 3.0 (planned, not yet released) is set to make SHA-256 and the reftable reference backend the defaults for new repositories, and to make Rust a required build component.

# Plumbing: create a blob and inspect objects by hand
echo 'hello' | git hash-object --stdin            # ce013625030ba8dba906f756967f9e9ca394464a
echo 'hello' | git hash-object -w --stdin         # -w writes it into .git/objects/ce/0136…
git cat-file -t ce01362                           # blob
git cat-file -p HEAD                              # commit: tree, parent, author, committer, message
git cat-file -p 'HEAD^{tree}'                     # tree entries: mode, type, hash, name
git ls-tree -r HEAD                               # every file in the snapshot
git rev-parse HEAD main origin/main               # resolve names to hashes

Storage: loose objects and packfiles

New objects are written as loose files (zlib-compressed) at .git/objects/xx/yyyy…. Periodically (and on push/fetch), Git combines them into packfiles (.git/objects/pack/*.pack + .idx), where similar objects are stored as deltas against each other: delta compression happens at storage time, even though the model is snapshots. git gc and git maintenance (background tasks: commit-graph, prefetch, incremental repack) keep repositories fast. The commit-graph file and bitmaps speed up history walks and clones.

References, HEAD and the index

Refs

A ref is a name pointing to an object hash:

Ref Example Meaning
Local branch refs/heads/main Movable pointer to a commit; advances when you commit on it
Remote-tracking branch refs/remotes/origin/main Your last-known position of main on remote origin; updated by fetch
Tag refs/tags/v1.4.2 Fixed pointer (to a commit, or to an annotated tag object)
Notes, stash, others refs/stash, refs/notes/commits Special-purpose

Refs live as files under .git/refs/ and in .git/packed-refs (or in the reftable format, which scales to millions of refs). git show-ref, git for-each-ref list them.

HEAD

HEAD says "where you are". Usually it's a symbolic ref to a branch (ref: refs/heads/main), so committing moves that branch. If you check out a commit or tag directly, HEAD points straight at a commit: detached HEAD. New commits made there belong to no branch, and are easy to lose (until the reflog saves you); create a branch (git switch -c fix) to keep them.

Revision syntax: HEAD~3 (three first-parent steps back), HEAD^2 (second parent of a merge), main@{yesterday}, @{u} (upstream), A..B (commits in B not in A), A...B (symmetric difference).

The three trees

Git juggles three versions of your files:

working directoryfiles on disk index (staging).git/index HEAD (commit)object database git add git commit git restore restore --staged git status compares working↔index and index↔HEAD git diff = working vs index · git diff --staged = index vs HEAD
Git's three trees. The working directory holds files you edit; the index (staging area) holds the snapshot you're preparing; HEAD is the last commit. git add copies working changes into the index; git commit turns the index into a new commit and moves the branch; restore and reset copy in the other directions.

The index is a binary file listing every path with its blob hash, mode and stat info. It's the next commit being prepared: git add writes blobs and updates entries; git commit writes trees from the index and a commit pointing to them. Staging lets you commit part of your changes (git add -p stages individual hunks).

Everyday operations, explained

commit

git commit creates trees from the index, a commit object with parent = HEAD, and moves the current branch to it. Good commits are small, coherent, and well described: a summary line (≤ ~50–72 chars, imperative mood: "Add retry to payment client"), a blank line, then why the change was made. Many teams use Conventional Commits (feat:, fix:, refactor:, BREAKING CHANGE:) so tools can generate changelogs and version bumps (chapter 96). --amend replaces the last commit with a new one (new hash), fine before pushing.

branch

A branch is a 41-byte file containing a commit hash. Creating one is instant; switching is fast because Git only rewrites files that differ. git switch -c feature (create and switch), git branch -d (delete if merged), git branch -vv (with upstreams and ahead/behind counts).

merge

Merging combines histories:

  • Fast-forward: if the current branch is an ancestor of the other, Git just moves the pointer forward; no new commit. --no-ff forces a merge commit (to record that a feature branch existed).
  • Three-way merge: if histories diverged, Git finds the merge base (best common ancestor, git merge-base A B), computes the changes from base→ours and base→theirs, combines them, and creates a merge commit with two parents. The default strategy is ort ("ostensibly recursive's twin", which replaced recursive in Git 2.34), and it handles renames and criss-cross merges well.
  • Conflicts occur when both sides changed the same lines (or one deleted what the other changed). Git writes conflict markers, keeps all three versions in the index (stages 1/2/3), and waits. Resolve, git add, git commit (or git merge --abort). git config merge.conflictStyle zdiff3 shows the base version too, which makes resolution much easier; git rerere remembers resolutions for repeated conflicts.

rebase

git rebase main (while on feature) replays the feature's commits on top of main: for each commit, it computes its diff and applies it to the new base, creating new commits with new hashes. The old ones remain in the database (reachable via reflog) until garbage-collected.

before A B Cmain D Efeature merge A B C Mmain D E true history; M has two parents rebase feature onto main A B C D' E'feature DE old commits: unreachable (reflog only)
Merge versus rebase. Starting from diverged branches, merge creates a merge commit joining both histories (history preserved as it happened); rebase replays the feature commits on top of main as new commits D' and E', giving a linear history but rewriting those commits.
Merge Rebase
History True record, with merge commits; can look tangled Linear and readable
Commits Unchanged (no rewriting) New commits (new hashes)
Conflicts Resolved once, in the merge commit Possibly once per replayed commit
Safe on shared branches? Yes No: never rebase commits others have based work on

The golden rule of rebasing: don't rebase commits that exist outside your repository and that others may have built on. Rebasing your own unpublished or personal feature branch onto the latest main is fine and common. After rebasing a pushed personal branch, push with git push --force-with-lease (refuses if the remote changed since your last fetch, unlike plain --force).

Interactive rebase (git rebase -i main) edits a list of commits: pick, reword, edit, squash/fixup (combine), drop, reorder. git commit --fixup <sha> + git rebase -i --autosquash folds fixes into the right commit. --update-refs moves stacked branches along. git rebase --onto newbase oldbase branch transplants a range of commits (e.g. move a feature off a branch it shouldn't have been based on).

Many teams use squash merges on pull requests (one commit per PR on main) or rebase merges, giving a linear main without anyone rewriting shared branches.

cherry-pick

git cherry-pick <sha> applies the change introduced by one commit onto the current branch as a new commit. Typical use: backporting a fix to a release branch (git cherry-pick -x <sha> records the original hash in the message). Overuse creates duplicate changes with different hashes on different branches, which can conflict later.

revert

git revert <sha> creates a new commit that undoes the changes of a previous commit. It's the safe way to undo something already pushed and shared, because history isn't rewritten. Reverting a merge commit needs -m 1 (keep the first parent's line) and has a subtlety: re-merging the same branch later won't bring the reverted changes back unless you "revert the revert".

reset

git reset <commit> moves the current branch (and HEAD) to <commit>, then optionally updates the index and working directory:

Mode Moves branch Index Working directory Use
--soft ✓ unchanged unchanged Squash the last N commits into one (changes stay staged)
--mixed (default) ✓ reset to commit unchanged Unstage; redo commits with different grouping
--hard ✓ reset reset (local changes discarded!) Throw away commits and changes completely
--keep ✓ reset reset, but refuses if it would lose local changes Safer alternative to --hard

Reset rewrites the branch, so like rebase, don't reset shared history. For files, prefer the clearer modern commands: git restore <file> (discard working changes), git restore --staged <file> (unstage), git switch <branch> (change branches); git checkout still does all of these.

reflog: the safety net

Every time HEAD or a branch moves (commit, reset, rebase, checkout, merge), Git records the old and new positions in the reflog (.git/logs/), kept locally for about 90 days by default (30 for unreachable entries).

Shell
git reflog                          # HEAD@{0}: rebase (finish)…  HEAD@{5}: commit: add retries
git reflog show feature             # history of one branch's positions
git branch rescue HEAD@{5}          # recover commits "lost" by a bad reset or rebase
git reset --hard ORIG_HEAD          # undo the last reset/rebase/merge (ORIG_HEAD is set by those commands)
git fsck --lost-found               # dangling commits and blobs (e.g. dropped stashes)

Almost nothing you committed is ever truly lost in your local repo until garbage collection, which is why "commit early, commit often" is good advice. Uncommitted work deleted by reset --hard or restore is genuinely gone (except blobs you git added, which fsck may find).

stash

git stash saves working and staged changes to a stack (as special commits on refs/stash) and cleans the working tree; git stash pop reapplies. git stash -u includes untracked files. Worktrees (git worktree add ../hotfix main) are often better than stashing: several branches checked out at once in separate directories, sharing one object database.

tag

  • Lightweight tag: just a ref to a commit (git tag v1.4.2).
  • Annotated tag: an object with tagger, date, message and optional signature (git tag -a v1.4.2 -m "Release 1.4.2", or -s to sign). Use annotated tags for releases: git describe uses them (v1.4.2-7-g3f9c2e1 = 7 commits after v1.4.2 at commit 3f9c2e1), a handy build version.
  • Tags aren't pushed by default: git push origin v1.4.2 or git push --follow-tags. Treat release tags as immutable; moving a published tag confuses everyone (and many hosting platforms can protect tags).

Remotes and remote tracking

A remote is a named URL of another repository (origin). Its branches are mirrored as remote-tracking branches (origin/main): read-only local refs updated only by fetch.

server (origin)main → F(D → F by teammates) your clone origin/main: D → F main: E (your commit on D) pull --rebase → main: F–E'push → server main = E' fetch push (fast-forward only)
Remote-tracking branches. fetch downloads new objects and moves origin/main to match the server; your local main doesn't move until you merge or rebase. pull is fetch followed by merge (or rebase). push uploads objects and asks the server to move its branch, refused if that isn't a fast-forward.
  • git fetch updates remote-tracking branches and downloads objects; it never changes your branches or working tree. Safe to run anytime.
  • git pull = fetch + merge (or + rebase with --rebase, or git config pull.rebase true; many people set pull.ff only to avoid surprise merges).
  • Upstream (tracking) configuration links a local branch to a remote one: git push -u origin feature sets it; git status then shows "ahead 2, behind 1".
  • git push uploads missing objects and asks the server to update the branch, which it accepts only if it's a fast-forward (unless forced). Prefer --force-with-lease over --force. Branch protection rules on the server prevent force-pushes and deletions on main.
  • git remote -v, git remote add upstream <url> (forks), git fetch --prune (drop tracking refs for deleted remote branches).

Hooks

Hooks are scripts Git runs at certain events:

Hook When Typical use
pre-commit Before a commit is created Format, lint, detect secrets, block large files
commit-msg After the message is written Enforce message format (Conventional Commits, ticket IDs)
prepare-commit-msg Before the editor opens Template messages (branch name → ticket ID)
pre-push Before pushing Run fast tests
post-checkout, post-merge After switching/merging Reinstall dependencies, regenerate files
pre-receive, update, post-receive Server side Enforce policies, trigger CI (hosting platforms replace these with protected branches, rulesets, webhooks)

Client hooks live in .git/hooks/ and aren't versioned or enforced: anyone can skip them with --no-verify. Share them with frameworks (pre-commit (Python-based, language-agnostic), lefthook (Go), Husky + lint-staged (Node)), set core.hooksPath to a versioned directory, and enforce the same checks in CI, which is the real gate.

YAML
# .pre-commit-config.yaml: same checks locally and in CI (pre-commit run --all-files)
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-added-large-files
        args: ["--maxkb=1024"]
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.24.0
    hooks:
      - id: gitleaks                        # block committed secrets
  - repo: local
    hooks:
      - id: gofmt
        name: gofmt
        entry: gofmt -l -w
        language: system
        types: [go]

Signing

Anyone can set user.name and user.email to anything, so author metadata proves nothing. Signing commits and tags proves who created them (or at least who controls the signing key):

  • GPG/OpenPGP: git config user.signingkey <keyid>, commit.gpgsign true, git commit -S, git tag -s. Key management is the usual pain.
  • SSH signing (Git 2.34+): reuse an SSH key: git config gpg.format ssh, user.signingkey ~/.ssh/id_ed25519.pub; verify with an allowedSignersFile. GitHub and GitLab show "Verified" for keys registered to the account.
  • X.509 / S/MIME (gpg.format x509, e.g. with corporate PKI or gitsign, which uses Sigstore's keyless signing tied to your OIDC identity and records signatures in a transparency log).
  • Verify: git log --show-signature, git verify-commit, git verify-tag. Enforce with branch rules ("require signed commits") on hosting platforms.

Signing commits is one link in supply-chain integrity; it complements signed build provenance and artefact signing (Vol. 6 ch. 81).

Branching workflows

Workflow Shape When it fits
Trunk-based development Short-lived branches (hours to a day or two) merged into main frequently; feature flags hide unfinished work; releases cut from main (or short release branches) Continuous delivery, most SaaS teams; recommended by DORA research for high performance
GitHub flow Branch → PR → review → merge to main → deploy Simple trunk-based variant
GitFlow develop, feature/*, release/*, hotfix/*, main Versioned products with scheduled releases and long stabilisation; heavy for continuous delivery
Release branches main + release/1.4 for patches, fixes cherry-picked back Software supporting multiple versions (libraries, on-prem products)
Forking workflow Contributors push to forks, open PRs upstream Open source

Stacked diffs/PRs (tools like Graphite, ghstack, Sapling, git rebase --update-refs) split big changes into small dependent reviews.

Large repositories and monorepos

  • Partial clone: git clone --filter=blob:none downloads commits and trees but fetches file contents on demand.
  • Shallow clone: --depth 1 for CI (no history; some operations like git describe need more).
  • Sparse checkout: git sparse-checkout set services/orders libs/common materialises only parts of the tree (cone mode).
  • Git LFS: large binaries stored outside the repo, with pointer files in Git. Use it for assets; don't commit generated artefacts at all.
  • Scalar (bundled with Git) configures partial clone, sparse checkout, background maintenance and filesystem monitor for huge repos.
  • Monorepo tooling: Bazel, Pants, Nx, Turborepo, Gradle and Maven reactors, Cargo and Go workspaces build only what changed.

Programmatic Git

Language Library
C libgit2 (used by many bindings)
Rust git2 (libgit2), gitoxide (gix, pure Rust, fast)
Go go-git (pure Go)
Java JGit (Eclipse, used by Gerrit and many tools)
Python GitPython (shells out to git), pygit2 (libgit2), dulwich (pure Python)
Zig / C++ libgit2 via C interop
Go
// Go (go-git): list the last 5 commits on HEAD
repo, err := git.PlainOpen(".")
if err != nil { log.Fatal(err) }
ref, _ := repo.Head()
iter, _ := repo.Log(&git.LogOptions{From: ref.Hash()})
n := 0
_ = iter.ForEach(func(c *object.Commit) error {
    fmt.Printf("%s %s\n", c.Hash.String()[:8], strings.SplitN(c.Message, "\n", 2)[0])
    n++
    if n == 5 { return storer.ErrStop }
    return nil
})

Lab: Git's storage and tools, measured

Git 2.43 on Linux, local repositories (clones over file:// with --no-local so Git uses its real transfer protocol), and git-filter-repo for history rewriting.

Experiment 1: content addressing deduplicates

Text
1,000 identical menu.txt files in 1,000 directories → blobs in the commit: 1, objects in the repo: 4

One blob for 1,000 identical files, and because the 1,000 directories had identical contents, one tree for all of them too: four objects in total (blob, subdirectory tree, root tree, commit). The same mechanism means renaming or copying files costs almost nothing, and moving a file doesn't really "move" anything: Git detects renames afterwards by comparing content.

Experiment 2: loose objects versus packfiles

A 0.6 MB CSV file; 200 commits, each changing one line:

Text
a 0.6 MB file, 200 commits each changing one line: 840K on disk; .git loose: 60M
after git gc (packfile with deltas): 356K; size-pack: 314.10 KiB

As loose objects, each commit stored a complete compressed copy of the file: 60 MB. git gc packed them into a packfile, storing most versions as deltas against similar objects: 314 KiB for the entire 200-commit history, smaller than the file itself. Snapshots are Git's model; deltas are its storage. Git packs automatically as objects accumulate, and servers send packs on clone and fetch.

Experiment 3: big files stay in history

Text
file deleted in the next commit; repository size: 51M
a fresh clone downloads: 51M
after git filter-repo removed it from every commit: 200K (all commit IDs after it changed: f77eeeb menu)

Deleting a file only stops it appearing in later snapshots; every clone still downloads the 50 MB in history, forever. Removing it means rewriting every commit that contained it (git filter-repo, the replacement for filter-branch and BFG), which changes their IDs and requires everyone to re-clone. Prevent it instead: .gitignore, pre-commit hooks or server-side limits on file size, and Git LFS (or an artifact store) for large binaries. The same applies, more urgently, to committed secrets: rotate the secret immediately, then clean history.

Experiment 4: git bisect run

256 commits; commit 177 changed 1.05 to 1.5 in the GST calculation; a two-line test checks the price:

Text
256 commits, one bad: 8 test runs to find it: 'change 177' (2 files changed, 2 insertions(+), 1 deletion(-))

Bisect binary-searches history: log₂(256) = 8 tests to find the first bad commit among 256, automatically, with any command that exits 0 for good and non-zero for bad. It works best when every commit builds and passes tests, which is one practical argument for small, self-contained commits and against long chains of "WIP" commits.

Experiment 5: partial clone

The repository from experiment 2, served with uploadpack.allowFilter:

Text
full clone of r2: 500K, 0.591 s
blobless clone (--filter=blob:none, no checkout): 236K, 0.024 s; history is complete: 201 commits

A blobless clone downloads every commit and tree but fetches file contents only when they're needed (checkout, diff, blame). It keeps full history for log and bisect while skipping old blobs, which makes large repositories (and CI jobs that need only the latest version) much faster to clone. GitHub, GitLab and Azure Repos support it; combine with sparse checkout to materialise only some directories of a monorepo.

Try it yourself

  1. Write a pre-commit hook that refuses files over 5 MB and lines matching common secret patterns; test it.
  2. Create the experiment 2 repository with git init --object-format=sha256 and compare object IDs and pack size.
  3. Rebase a feature branch with git rebase -i to squash fixup commits, then use git range-diff to compare before and after.
  4. Sign commits with an SSH key (gpg.format ssh) and configure allowed_signers so git log --show-signature verifies them.

Revision sheet: Git

Key ideas

  • Model: content-addressed objects (blob, tree, commit, annotated tag); snapshots linked by parents; SHA-1 with SHA-256 transition.
  • Refs: branches, tags, remote-tracking refs, HEAD (attached or detached), the reflog, packed refs.
  • Index (staging area): the proposed next tree; add -p for partial staging.
  • Operations: merge (fast-forward, three-way, merge base, conflicts), rebase (new commits, interactive), cherry-pick, revert, reset (soft/mixed/hard), restore, switch, stash, bisect, blame.
  • Remotes: fetch vs pull, upstream tracking, push rules, force-with-lease, protected branches, pull requests.
  • Hooks: client-side (pre-commit, commit-msg, pre-push) and server-side (pre-receive); frameworks (pre-commit, Husky, Lefthook).
  • Signing: GPG, SSH and Sigstore (gitsign) signatures; verification policies.
  • Workflows: trunk-based development, GitHub flow, GitFlow; short-lived branches and feature flags.
  • Scale: packfiles, gc, partial clone, sparse checkout, Scalar, monorepo tooling, LFS.

Numbers to remember

  • Reflog entries kept 90 days by default (30 for unreachable).
  • Lab: 1,000 identical files = 1 blob; 200 versions of a 0.6 MB file packed to 314 KiB; a deleted 50 MB file kept the repo at 51 MB until filter-repo; bisect found 1 bad commit in 256 with 8 runs; a blobless clone was half the size and 25× faster.

Pitfalls

  • Committing secrets or large binaries (history keeps them).
  • git push --force instead of --force-with-lease on shared branches.
  • Rebasing commits others have already pulled.
  • reset --hard with uncommitted work.
  • Long-lived branches that drift for weeks.
  • Commits that don't build, which breaks bisect.

Glossary

  • Blob / tree / commit: file contents / directory listing / snapshot with metadata.
  • Ref: a name pointing to an object (branch, tag).
  • Merge base: the best common ancestor of two commits.
  • Packfile: compressed, delta-encoded object storage.
  • Detached HEAD: HEAD pointing directly at a commit, not a branch.
  • Partial clone: a clone that omits some objects until needed.