Shelf · Core Eng · Chapter 1

Chapter 1: Git for real teams

Every workflow habit later in this book — CI gates, code review, incident response — assumes you can read and repair git's object graph without panic. This chapter builds that from the object model up: branching strategy, safe history rewrites, conflict recovery, bisecting a regression, and the difference between a hook that feels safe and a check that actually is.

Difficulty
Priority
ce-01-01Card 1 of 6

Read the object graph, index and HEAD

MediumP1 · Must knowKnow cold12 min
git-internalsobject-modelrefshead
Needs: nothing. Start here.

Why you care

Every git command you'll ever run manipulates one of three things — the working tree, the index, or a ref — and conflating them is why "I committed but nothing changed" and "my fix vanished" happen to developers who've used git daily for years. Interviewers ask "what's the difference between git add and git commit" or "what is HEAD" not to test trivia, but because the answer predicts whether you can read git status output under pressure instead of guessing. This card is the one everything else in the chapter depends on: branching strategy, rebase, conflict recovery and bisect are all just different things you do to this same graph.

Explain like I'm 5

Git's object store is a library that catalogs every unique page by its exact fingerprint, not by title. Two students handing in byte-identical essays get filed as literally one page, referenced twice — the library never keeps a second copy of the same content. HEAD and branch names are sticky notes pointing at a particular filed page (a commit); move the sticky note and you're looking at a different page, but the page itself doesn't change, and it doesn't vanish just because no note points at it anymore — it just gets harder to find.

Core concept

Git's history is a directed graph of four object types, all addressed by the hash of their content:

  • A blob stores one file's raw bytes, nothing else — not even a filename.
  • A tree stores a snapshot of a directory: names, modes, and the hashes of the blobs/trees inside it.
  • A commit stores a tree hash (the whole snapshot), one or more parent commit hashes, and author/message metadata.
  • A tag object (from git tag -a) points at a commit and adds its own message; a lightweight tag is just a ref, no object of its own.

Refs are separate from objects: a branch is a movable pointer (a file holding a commit hash) that advances every time you commit on it. HEAD is almost always a symbolic ref, one level of indirection: it points at a branch, which points at a commit. Moving HEAD by committing normally moves the branch too.

Three things can differ from each other at any moment, and git status exists to tell you which:

  • the working tree — files on disk right now;
  • the index (a.k.a. the staging area) — what's staged to go into the next commit;
  • HEAD — the last commit already made.

git diff compares working tree to index; git diff --cached compares index to HEAD; git status summarizes both at once.

Detached HEAD happens when you check out a specific commit hash (or tag) instead of a branch name: HEAD then points straight at a commit, with no branch in between. It's completely safe to look around in — but any commit you make there has no branch pointing at it, so it's invisible to git log on every existing branch and eligible for eventual garbage collection once you leave.

Decision rule: before you do anything that rewrites history or checks out something unusual, run git status first. If it doesn't say what you expect (extra staged files, "detached HEAD", unmerged paths), stop and figure out why before committing or resetting anything.

Under the hood

Git addresses every object by the SHA-1 hash of its type-tagged, zlib-compressed content (conceptually "blob <size>\0<content>" for a blob), which is why identical content anywhere in history is stored exactly once. New objects start as loose files under .git/objects/<first-two-hex>/<remaining-38-hex>; git gc (and every push/fetch) periodically rolls many loose objects into a single delta-compressed packfile, which is why a fresh clone's .git can be far smaller than the sum of every version of every file ever committed. Refs are plain text files under .git/refs/heads/<name> holding a 40-hex-char hash, and HEAD is usually the one-line file ref: refs/heads/<name> — that line is the symbolic-ref indirection. Freshness note: newer Git versions support SHA-256 object hashing as an opt-in repository format, but SHA-1 remains the default you'll meet almost everywhere in 2026.

Minimal example Content addressing: same bytes, same blob

PythonTwo identical files hash to one blobruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


git("init", "-q", "-b", "main")
os.makedirs("dir_a")
os.makedirs("dir_b")
with open("dir_a/config.json", "w") as f:
    f.write('{"retries": 3}\n')
with open("dir_b/config.json", "w") as f:
    f.write('{"retries": 3}\n')

hash_a = git("hash-object", "-w", "dir_a/config.json")
hash_b = git("hash-object", "-w", "dir_b/config.json")
print("same content -> same blob hash:", hash_a == hash_b)
print("hash length:", len(hash_a))
print("object type:", git("cat-file", "-t", hash_a))
Output
same content -> same blob hash: True
hash length: 40
object type: blob

In production Working tree, index and HEAD after a staged-only edit, then a detached checkout

PythonThree states of the same file, then detaching HEADruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args, check=True):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=check)


ident = ["-c", "user.name=CI Bot", "-c", "user.email=ci@example.com"]

git("init", "-q", "-b", "main")
with open("etl_config.py", "w") as f:
    f.write("BATCH_SIZE = 5000\n")
git("add", "etl_config.py")
git(*ident, "commit", "-q", "-m", "add batch size config")

# edit the working tree, then stage it, but do not commit
with open("etl_config.py", "w") as f:
    f.write("BATCH_SIZE = 10000\n")
git("add", "etl_config.py")

status = git("status", "--short").stdout.strip()
staged = git("diff", "--cached", "--stat").stdout.strip()
unstaged = git("diff", "--stat").stdout.strip()
print("status:", status)
print("staged change present:", bool(staged))
print("unstaged change present:", bool(unstaged))

head_ref = git("symbolic-ref", "HEAD").stdout.strip()
print("HEAD points at:", head_ref)

commit_hash = git("rev-parse", "HEAD").stdout.strip()
git(*ident, "checkout", "-q", commit_hash)
detached = git("symbolic-ref", "-q", "HEAD", check=False)
print("detached HEAD (no symbolic ref):", detached.returncode != 0)
Output
status: M  etl_config.py
staged change present: True
unstaged change present: False
HEAD points at: refs/heads/main
detached HEAD (no symbolic ref): True

See it happen Working tree to commit, then HEAD detaches

git addhash objecttree entrygit commitbranch advancesHEAD -> refdetached: HEAD -> commitworking treeetl_config.pyindex (staged)blobtreecommitrefs/heads/mainHEAD
  1. Editing etl_config.py only changes the working tree; the index and the last commit still describe the old content.
  2. `git add` hashes the file into a blob and records it in the index.
  3. `git commit` writes a tree over the index and a commit over that tree, then the branch ref moves to point at it.
  4. HEAD is a symbolic ref: it points at the branch, which points at the commit — one extra hop of indirection.
  5. `git checkout <hash>` instead points HEAD straight at a commit, bypassing the branch entirely: detached HEAD.
  6. Any commit made here has no branch pointing at it, so it's invisible to `git log` on every existing branch the moment you check out something else.
Notice: the commit and tree objects never move once written; only the sticky notes — branch and HEAD — move, and detached HEAD is what it looks like when HEAD's note comes unstuck from any branch.
Scenario A

In your world

The situation

Your ETL repo's Jenkins job stamps every Postgres load with git rev-parse HEAD for audit, and a teammate debugging a discrepancy checks out last month's commit directly: git checkout a1b2c3d.

What actually breaks

They find the bug and fix it right there, without noticing the "You are in 'detached HEAD' state" warning git status already printed. Jenkins builds main, not this commit, so the fix never ships. A week later the commit is unreachable from any branch, and git log on main shows no trace it ever existed.

What you'd do on Monday

Before making any change while not on a named branch, check first, and land on a branch immediately if you're going to keep the work:

Shell
git status                                     # look for "HEAD detached at <hash>"
git symbolic-ref -q HEAD || echo "not on a branch"
git checkout -b fix/audit-mismatch a1b2c3d     # now the commit has a home
Scenario B

Imagine you work at GitLab

a 1.2M-commit monorepo

The numbers

Illustrative: a monorepo the size of GitLab's own gitlab-org/gitlab is on the order of 1.2M commits; even if each commit touches only ~3 files, that's roughly 1.2M × (1 commit object + ~3-5 tree objects + ~2 blob objects) ≈ 8-10M objects before any packing. Content addressing means a config file that's byte-identical across 50,000 of those commits is stored as exactly one blob, not 50,000 copies.

What the Scenario-A answer does here

The Scenario A habit of running git status/git log on a clone still works, but "just git clone it, same as always" does not scale the same way: cloning a repo this size with no flags pulls every object in every version of every file ever committed — minutes, not seconds, and gigabytes of .git that are almost entirely history nobody asked for today.

What flips at this scale

At this scale the object graph stops being something you fetch in full. Shallow clones (--depth), partial clone (--filter=blob:none) and sparse checkout become the default for CI runners and new laptops, and a dedicated git service (GitLab runs Gitaly in front of its repositories) mediates access instead of every client talking to a bare repo directly.

The trade-off you'd defend

I would default new clones and CI checkouts to --filter=blob:none plus a sparse checkout of only the paths a job actually touches, trading the ability to browse the entire history offline for clone times that don't grow with the repo's entire past.

Illustrative figures for the arithmetic; not GitLab-published numbers.

Gotchas

git added a file but git diff still shows nothing for it

Symptom

You expect git diff to show a staged change and it shows nothing at all.

Cause

git diff compares the working tree to the index; once a change is staged, that particular comparison is clean by definition.

Fix

Use git diff --cached (or --staged) to see what's actually about to be committed; use plain git diff for what isn't staged yet.

A detached-HEAD commit "disappears" after checking out a branch

Symptom

You made a commit, ran git checkout main, and git log on main shows nothing you just did — it feels deleted.

Cause

The commit was made while HEAD pointed directly at a commit, not a branch, so no branch ever referenced it.

Fix

git reflog still remembers the hash; git branch recovery/<name> <hash> gives it a home again.

"detached HEAD" gets skimmed past

Symptom

Work continues normally for a while, then someone can't find their commits later.

Cause

git status's warning is easy to miss mid-debugging, especially when you weren't planning to commit anything.

Fix

Treat "detached HEAD" in git status as a hard stop: branch first (git checkout -b <name>) the moment you intend to keep anything.

Tricky questions

Does git add copy the file into the commit right away?
Most people say

Yes, git add commits the file.

Actually

git add only stages it — it writes a blob and updates the index. Nothing joins history until git commit writes a tree and a commit object over that index.

Is HEAD the same thing as "the latest commit"?
Most people say

Yes, HEAD is just a name for the newest commit.

Actually

HEAD is a ref — usually a pointer to a branch, which itself points at a commit. Check out a different branch, or a commit directly (detached HEAD), and what HEAD points at changes with no new commit made at all.

Scenario question

You're handed a bug report: "I committed my fix but it's not on GitHub and now I can't find it anywhere, even in git log." The teammate insists they ran git commit. Where do you look, and what likely happened?

Model answer

I'd ask first whether they were on a named branch when they committed, but I wouldn't wait for the answer — git reflog shows every commit HEAD has pointed at recently, detached or not, so I'd run that immediately. My working guess is they were in detached HEAD, probably from an earlier git checkout <hash>, when they committed: the commit exists as a real object, but no branch references it, so git log on any branch won't show it. The fix is git branch recovery/<name> <hash-from-reflog>, then merge or cherry-pick from there. I do this before touching anything else, because further commits or a git gc push reflog entries further from HEAD@{0} and, eventually, past the default ~30-day expiry for entries no branch references.

Interview corner

CommonWhat's the difference between the working tree, the index and HEAD?
“I'd say the working tree is the files on disk right now, the index is what's staged to go into the next commit, and HEAD points at the last commit that's already there. git diff compares tree-vs-index, git diff --cached compares index-vs-HEAD, and git status tells me which of those three actually differ.”
TrickWhat happens if you commit while in detached HEAD?
“The commit is created for real, with a real hash, but no branch points at it. If I check out a branch afterward without saving it somewhere, it becomes unreachable and eventually eligible for garbage collection. I always branch first if I plan to keep anything from a detached state.”
Experience checkWhere has understanding refs versus objects actually helped you debug something?
“I had a Jenkins job tagging Postgres loads with a commit hash that didn't match anything in git log on any branch. Knowing that HEAD and branches are just movable pointers, and that the object itself doesn't vanish when a pointer moves off it, is what sent me to git reflog instead of assuming the audit data was fabricated.”
CommonHow would you inspect a specific commit without changing your working tree?
“git show <hash> for the diff and message, git cat-file -p <hash> if I need the raw object, and git log -p -- <path> for a file's history — none of that touches the working tree or the index.”

Memory hook

A branch is a sticky note pointing at a commit; the commit doesn't move or vanish just because you moved the note.

If you remember only one thing:

If git status says detached HEAD, branch before you commit.

Self-check

  1. What are the three states git status/diff compare?

    The working tree, the index (staged), and HEAD's commit; diff and diff --cached compare different pairs of these.

  2. Why does git log show different commits after git checkout <hash> than it did before?

    Because HEAD now points directly at that commit (detached HEAD) instead of following a branch ref to wherever that branch's tip is.

  3. What makes two files' content hash to the same blob?

    Byte-identical content — git addresses objects by content, not by filename or path.

Prove it

Create a repo, make three commits, check out the first commit's hash directly, and make a fourth commit there. Show with git log on the original branch that it's invisible, then recover its hash with git reflog and paste both outputs.

ce-01-02Card 2 of 6

Choose a team branching strategy

MediumP2 · Very likelyTalk about it11 min
branchingtrunk-basedmerge-vs-rebasebranch-protection

Why you care

Your team's actual git pain — three-week branches, reviews nobody can finish, merges that silently drop someone's fix — is almost never a merge-vs-rebase problem; it's a branch-lifetime problem wearing a merge-vs-rebase costume. Interviewers ask about branching strategy because the answer reveals whether you've actually shipped on a team, not just used git solo. Get this wrong, and every other git skill in this chapter — conflict resolution, rebase, PR hygiene — is spent fighting a problem the workflow itself created.

Explain like I'm 5

Branches are lanes on a highway. A short-lived lane merges back in minutes after it opened, so the road hasn't changed much. A long-lived lane that rejoins after three weeks means the main road has moved — new exits, new lane markings — while you were off on your own, and merging back in is a much bigger negotiation than it would have been on day one.

Core concept

Three questions decide a team's branching strategy, and none of them is really "merge or rebase":

  • How long does a branch live before it rejoins? Short-lived (hours to a couple of days) branches diverge from the mainline by a handful of commits; long-lived (weeks) branches diverge by hundreds. Integration difficulty scales with that gap, not with the number of branches in flight.
  • Trunk-based development versus release branches. Trunk-based: everyone merges small changes to one mainline frequently, and unfinished behavior hides behind a feature flag instead of a branch. Release branches: a branch is cut at release time and only fixes land on it while mainline keeps moving — this suits software with slow, versioned releases (an installed client, a firmware image) more than a continuously deployed service.
  • Merge or rebase, and where. Rebasing your own unpushed branch onto the latest mainline keeps your diff small and current; merging a finished feature into mainline preserves the fact that it happened as one reviewed unit. The rule that doesn't bend: never rebase a branch other people have already pulled from, because rebase gives old commits new hashes, and anyone with the old ones now has to reconcile diverged history by hand (Rewrite local commits and transplant fixes).

Branch protection is what actually makes any of this a rule rather than a request: a hosting platform can require passing checks and review before a merge to a protected branch is even possible, independent of who's pushing or what they meant to do.

Decision rule: default to short-lived branches and frequent small merges to mainline; reach for a release-branch model only when you genuinely ship discrete, versioned builds rather than deploy continuously.

Minimal example Rebase gives an identical change a new hash

PythonSame diff, different commit id after rebaseruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")
open("a.txt", "w").write("1\n")
git("add", "a.txt")
git(*ident, "commit", "-q", "-m", "base")

git("checkout", "-q", "-b", "feature")
open("b.txt", "w").write("2\n")
git("add", "b.txt")
git(*ident, "commit", "-q", "-m", "add b")
before = git("rev-parse", "feature")

git("checkout", "-q", "main")
open("a.txt", "w").write("1.1\n")
git("add", "a.txt")
git(*ident, "commit", "-q", "-m", "tweak a")

git("checkout", "-q", "feature")
git(*ident, "rebase", "main")
after = git("rev-parse", "feature")
print("commit id changed after rebase:", before != after)
Output
commit id changed after rebase: True

In production Merge keeps two parents; rebase makes history linear

PythonSame divergence, two different shapes of historyruns
import subprocess, os


def git(cwd, *args, check=True):
    return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=check)


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]


def build_repo(path):
    os.makedirs(path)
    git(path, "init", "-q", "-b", "main")
    with open(os.path.join(path, "app.py"), "w") as f:
        f.write("VERSION = 1\n")
    git(path, "add", "app.py")
    git(path, *ident, "commit", "-q", "-m", "base")
    git(path, "checkout", "-q", "-b", "feature")
    with open(os.path.join(path, "feature.py"), "w") as f:
        f.write("FLAG = True\n")
    git(path, "add", "feature.py")
    git(path, *ident, "commit", "-q", "-m", "add flag")
    git(path, "checkout", "-q", "main")
    with open(os.path.join(path, "app.py"), "w") as f:
        f.write("VERSION = 2\n")
    git(path, "add", "app.py")
    git(path, *ident, "commit", "-q", "-m", "bump version")


def parent_count(path):
    out = git(path, "rev-list", "--parents", "-n", "1", "HEAD").stdout.strip()
    return len(out.split()) - 1


build_repo("merged")
git("merged", *ident, "merge", "-q", "--no-edit", "feature")
print("merge commit parents:", parent_count("merged"))

build_repo("rebased")
git("rebased", "checkout", "-q", "feature")
git("rebased", *ident, "rebase", "main")
git("rebased", "checkout", "-q", "main")
git("rebased", *ident, "merge", "-q", "--ff-only", "feature")
print("rebase+ff-only parents:", parent_count("rebased"))
print("history is linear:", parent_count("rebased") == 1)
Output
merge commit parents: 2
rebase+ff-only parents: 1
history is linear: True

See it happen The same divergence, merged versus rebased

A: baseB: bump version(main)C: add flag(feature)C, rebasednew hash
  1. main and feature diverged from the same commit A: B is on main, C is on feature.
  2. `git merge feature` (from main) creates M with two parents, B and C; both B and C keep their original hashes untouched.
  3. Compare: `git rebase main` on feature instead discards C's old identity and creates Cr, a new commit with the same diff, parented on B.
  4. History after the rebase path is linear, A - B - Cr; the original C is now orphaned unless a branch or the reflog still points at it.
Notice: merge adds a new node with two parents and keeps both originals; rebase produces a new node that replaces one of the originals, which is why rebase needs a rule about who's allowed to have already pulled the old one.
Scenario A

In your world

The situation

Your team's feature/reprice-orders branch has been open for three weeks, 46 commits, touching the same pricing module that four other people also changed on main in that window.

What actually breaks

The eventual PR shows 46 commits and a 200-file diff nobody can meaningfully review. Merging it either explodes into a wall of conflicts, or — worse — resolves cleanly and silently reverts someone else's later fix to the same function, because both changes touched the same lines and git picked a mechanically valid but logically wrong resolution.

What you'd do on Monday

Cut the branch's lifetime, not just its size. Rebase onto main daily so conflicts show up small and often, and land plumbing changes behind a flag instead of a long branch.

Shell
git fetch origin
git rebase origin/main        # daily, in small doses, on your own not-yet-shared branch
Scenario B

Imagine you work at Meta

~8,000 commits/day into one mainline

The numbers

Illustrative: a large trunk-based org running roughly 8,000 commits/day into one mainline across thousands of engineers averages one commit every ~11 seconds during the working day. Even a 1-hour average review-and-merge latency per change means roughly 8,000 ÷ 24 ≈ 330-350 changes are concurrently "in flight" at any given moment — which is why short-lived branches (hours, not weeks) are a scale requirement, not a style preference.

What the Scenario-A answer does here

The Scenario A habit of finishing a branch before opening a PR still applies in spirit, but "my branch has been open for three weeks and touches 40 files" does not survive this cadence: mainline has moved thousands of commits in that time, so the eventual merge is effectively a rewrite, and rebase-vs-merge stops being a taste question and becomes a merge-conflict-probability question.

What flips at this scale

At this scale, teams flip to trunk-based development with feature flags: small commits merge to mainline within hours, behind a flag, so "integrate" and "release" become separate events. Branch protection enforces required checks on mainline itself, instead of relying on any one engineer's rebase discipline.

The trade-off you'd defend

I would defend trunk-based small commits plus flags over long-lived feature branches, trading the comfort of an isolated branch for conflicts that are small and frequent instead of rare and enormous.

Illustrative figures for the arithmetic; not Meta-published numbers.

Gotchas

A clean auto-merge that's still wrong

Symptom

Two branches merge with zero conflicts, but a teammate's earlier fix to a function is gone.

Cause

Git's merge is line-based — if the two changes don't touch the exact same lines, it merges mechanically without understanding that one change logically depended on the other.

Fix

Don't treat "no conflicts" as "definitely correct" on a branch that diverged a long time; run the tests, and for long-diverged branches, review the merge diff itself.

A rebase mid-review

Symptom

A reviewer's comments reference line numbers that no longer exist after you force-push a rebase.

Cause

Rebasing a PR branch under active review changes every commit hash, so the reviewer's diff view is now stale.

Fix

Once a PR is under active review, prefer adding new commits over rebasing; save the squash-and-clean-up for right before merge.

Branch protection that isn't actually configured

Symptom

Someone pushes straight to main "by accident" and it just works.

Cause

The rule was agreed on in a meeting or a doc but never actually turned on in the hosting platform's settings.

Fix

Verify branch protection directly in the repo settings; don't infer it from a policy document or a chat message.

Tricky questions

Does rebasing lose the commits that merging would keep?
Most people say

Yes, rebase throws the original commits away.

Actually

The original commits become unreachable from the rebased branch, but they still exist as objects — findable via reflog — until eventually garbage collected. Nothing is deleted immediately; it's just no longer referenced by that branch.

Is trunk-based development the same as "no branches at all"?
Most people say

Yes, everyone just commits straight to main.

Actually

Trunk-based means branches exist but are short-lived — hours, not weeks — and merge to main frequently. It's not the absence of branches; it's a strict limit on how long one lives before rejoining.

Scenario question

You're handed a repo where every feature branch lives for four to six weeks and PRs regularly carry 100+ file diffs. Leadership asks you to "fix our git workflow." What do you actually change?

Model answer

I wouldn't start with a merge-vs-rebase rule; I'd start with branch lifetime, because that's the actual root cause of the 100-file diffs. I'd push for trunk-based development — small commits merged to main within a day or two, using feature flags to hide unfinished behavior instead of hiding it in a long-lived branch. Branch protection then enforces required checks on main, so "when to merge" stops depending on any one person's judgment. The trade-off is that this needs flag-cleanup discipline and CI fast enough to run on every small merge, so I'd sequence it: fast CI first, then trunk-based habits, then retire the old long-lived branches.

Interview corner

CommonMerge or rebase: how do you choose?
“For bringing a shared branch's changes onto my own feature branch before I open a PR, I rebase, because I want a clean, linear diff for review. For integrating a finished feature into main, I usually merge, because it preserves the fact that it happened as one unit and doesn't rewrite history other people may have already pulled.”
TrickIs rebase always 'safer' than merge because it avoids merge commits?
“No — rebase rewrites commit hashes, so doing it on a branch other people have already pulled forces everyone else to reconcile diverged history. My actual rule is: rebase freely on branches only I have; never rebase branches other people are also working from.”
Experience checkWhat's gone wrong on a long-lived feature branch you've worked on?
“I've seen a three-week branch whose eventual merge either explodes into dozens of conflicts, or, worse, resolves cleanly but silently drops someone else's later change to the same function, because git's merge is line-based, not intent-based.”
DesignHow would you introduce trunk-based development to a team used to long branches?
“I'd start with feature flags so incomplete work can merge to main safely, then shrink branch lifetime to under a day, then add required CI checks as branch protection on main, so 'is this safe to merge' stops being a judgment call.”

Memory hook

Branch lifetime is the actual lever; merge versus rebase just decides what the join looks like once you pull it.

If you remember only one thing:

Long-lived branches don't cause conflicts, time does — shrink the time.

Self-check

  1. What's the structural difference between a merge commit and a rebased commit?

    A merge commit has two parents; a rebased commit has one parent and a new hash, even though its diff is unchanged.

  2. Why is rebasing a shared branch risky?

    It rewrites commit hashes, so anyone who already pulled the old ones now has diverged history to reconcile by hand.

  3. What does branch protection enforce that a personal habit can't?

    A server-side rule (required checks, required review) that applies no matter who is pushing or what their local git settings are.

Prove it

In one repo, diverge main and a feature branch by two commits each, merge them into a copy, and show the merge commit has two parents with git log --graph. In a second copy, rebase the feature branch onto main and show the resulting history is linear. Paste both git log --graph --oneline outputs.

ce-01-03Card 3 of 6

Rewrite local commits and transplant fixes

MediumP3 · Role-dependentKnow cold12 min
rebasecherry-pickinteractive-rebasehistory-rewrite

Why you care

Knowing that rebase and cherry-pick create new commits, never edit old ones, is the difference between confidently cleaning up a branch before a PR and permanently confusing a shared release branch. It's a favorite interview probe — does cherry-pick create a duplicate, what actually changes when you rebase — because the honest answer (everything downstream gets a new hash) is exactly the fact that trips up developers who've only ever clicked "squash and merge" in a UI. This card is what makes Resolve conflicts and recover lost work's recovery techniques make sense: rewriting history is safe locally and risky once shared, and you need to know which side of that line you're on.

Explain like I'm 5

A commit is a sealed, tamper-evident envelope: the seal is made from the letter inside plus which envelope came before it. Cherry-pick photocopies the letter and seals it in a brand-new envelope with a new seal number; rebase re-seals a whole stack of envelopes onto a different starting point. The letters read exactly the same. Every envelope is new.

Core concept

Two tools solve two different problems, and both create new commit objects rather than editing old ones — git commits are immutable once made:

  • git rebase replays a range of your own commits onto a new base, one at a time. git rebase main while on a feature branch rewrites every commit on that branch to descend from main's current tip instead of the old base.
  • Interactive rebase (git rebase -i <base>) opens an editable list of pick lines, one per commit, letting you reorder, drop, reword (edit the message only), squash (combine into the previous commit, keeping both messages) or fixup (combine into the previous commit, discarding this one's message) before replaying.
  • git cherry-pick <hash> takes one existing commit's diff and re-applies it as a brand-new commit wherever you currently are — usually a different branch. The resulting tree can be identical to the original; the commit itself is not, because its hash also depends on its parent and timestamp (Read the object graph, index and HEAD).

Both tools can hit the exact same conflicts a merge would, one commit at a time, and both let you inspect, fix, and continue (--continue) or bail out entirely (--abort) if it's going badly.

The one non-negotiable: never rewrite (rebase, amend, or force-push over) commits that other people have already pulled, unless the whole team knows and is ready to reconcile. Local, not-yet-pushed commits are yours to tidy freely; shared history is a contract.

Decision rule: use interactive rebase to clean up your own branch before opening a PR (squash the debugging trail into meaningful commits); use cherry-pick to move a specific, finished fix across branches without dragging along everything else that branch has accumulated.

Under the hood

A commit's hash is computed from its exact content: the tree hash, the parent hash(es), the author/committer name, email and timestamp, and the message — change one byte of any of those and every downstream hash changes too. That's why git commit --amend, git rebase and git cherry-pick all produce brand-new hashes even when the resulting file contents are identical: the parent pointer or the timestamp differs, so the whole chain of hashes past that point changes as well. This is also why rewriting a commit that has children rewrites every descendant commit's hash whether you touch their content or not — git rebase is doing exactly that, one commit at a time, replaying each child onto its new parent.

Minimal example Cherry-pick copies content, not identity

PythonSame tree, different commit idruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")
open("base.txt", "w").write("0\n")
git("add", "base.txt")
git(*ident, "commit", "-q", "-m", "base")

git("checkout", "-q", "-b", "hotfix")
open("fix.txt", "w").write("patched\n")
git("add", "fix.txt")
git(*ident, "commit", "-q", "-m", "fix null pointer")
fix_hash = git("rev-parse", "hotfix")

git("checkout", "-q", "main")
open("unrelated.txt", "w").write("main kept moving\n")
git("add", "unrelated.txt")
git(*ident, "commit", "-q", "-m", "unrelated main work")   # so the pick has a different parent
git(*ident, "cherry-pick", fix_hash)
picked_hash = git("rev-parse", "main")

print("same file contents (blob):",
      git("rev-parse", "hotfix:fix.txt") == git("rev-parse", "main:fix.txt"))
print("same commit id:", fix_hash == picked_hash)
Output
same file contents (blob): True
same commit id: False

In production A scripted squash: the non-interactive shape of interactive rebase

GIT_SEQUENCE_EDITOR gets the path to the same todo file an editor would open for git rebase -i; a script can rewrite it exactly like a human would, which is how CI-safe automation does "interactive" rebases without a human at a keyboard.

PythonTurning three WIP commits into one with fixupruns
import subprocess, os, pathlib, sys

def git(*args, env=None):
    e = dict(os.environ)
    if env:
        e.update(env)
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True, env=e).stdout.strip()


root = pathlib.Path(".").resolve()
os.makedirs("repo")
os.chdir("repo")
ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")
open("base.py", "w").write("VERSION = 1\n")
git("add", "base.py")
git(*ident, "commit", "-q", "-m", "base")

for i, msg in enumerate(["wip: try one thing", "wip: fix typo", "wip: actually fix it"], start=1):
    open(f"note{i}.txt", "w").write(f"{i}\n")
    git("add", f"note{i}.txt")
    git(*ident, "commit", "-q", "-m", msg)

before = int(git("rev-list", "--count", "HEAD"))

# Non-interactive stand-in for opening an editor and marking lines 2-3 "fixup":
# GIT_SEQUENCE_EDITOR receives the todo file path and rewrites it like a script would.
editor = pathlib.Path("seqedit.py").resolve()
editor.write_text(
    "import sys, pathlib\n"
    "p = pathlib.Path(sys.argv[1])\n"
    "seen = 0\n"
    "out = []\n"
    "for l in p.read_text().splitlines():\n"
    "    if l.startswith('pick '):\n"
    "        seen += 1\n"
    "        l = l if seen == 1 else l.replace('pick', 'fixup', 1)\n"
    "    out.append(l)\n"
    "p.write_text('\\n'.join(out) + '\\n')\n"
)
base_commit = git("rev-parse", "HEAD~3")
subprocess.run(["git", *ident, "rebase", "-i", base_commit], check=True,
                capture_output=True, text=True,
                env={**os.environ, "GIT_SEQUENCE_EDITOR": f'"{sys.executable}" "{editor}"'})

after = int(git("rev-list", "--count", "HEAD"))
print("commits before squash:", before)
print("commits after squash:", after)
print("kept the first commit's message:", git("log", "-1", "--format=%s") == "wip: try one thing")
Output
commits before squash: 4
commits after squash: 2
kept the first commit's message: True

See it happen What cherry-pick actually copies

same treecherry-pickbasemain tipF: null-check fix(hotfix)F picked onto main
  1. hotfix branches off base with commit F, a one-line null-check fix.
  2. main has moved on its own, with unrelated commits; F is not part of main's history yet.
  3. `git cherry-pick F` (run while on main) re-applies F's diff on top of main's tip, producing a new commit with the same file contents but a new hash and a new parent.
  4. F and its cherry-picked copy now have identical trees but different commit ids — exactly what makes cherry-pick a copy, not a move.
Notice: the dashed "same tree" edge and the "cherry-pick" edge point at the same node from two different commits — one fact about content, one fact about identity, and they disagree on purpose.
Scenario A

In your world

The situation

A hotfix for a null-pointer crash lands on main, and the same fix needs to go out on release/3.4, which is currently deployed and can't take main's other 80 unreleased commits.

What actually breaks

Someone merges all of main into release/3.4 to "grab the fix," which also pulls in 80 unrelated, half-tested commits into a branch that's supposed to be frozen for release. The next deploy ships things nobody signed off on.

What you'd do on Monday

Transplant just the one commit.

Shell
git log --oneline main -3       # find the fix's hash, e.g. 9f1c2ab
git checkout release/3.4
git cherry-pick 9f1c2ab
git push origin release/3.4
Scenario B

Imagine you work at Google

a fix cherry-picked across 12 release branches

The numbers

Illustrative: a platform security fix needs to land on, say, 12 actively maintained release branches, with roughly 800 commits of divergence between the oldest and newest branch. Cherry-picking one small fix across 12 branches is 12 cherry-picks, each a few lines, versus asking every branch owner to manually re-derive the same six-line diff independently.

What the Scenario-A answer does here

The Scenario A cherry-pick command still works per branch, but "cherry-pick it 12 times by hand, one terminal tab per branch" doesn't scale past a handful of branches: it's easy to cherry-pick onto the wrong branch, or miss one, with no single command confirming all 12 actually landed.

What flips at this scale

At this scale, teams script the transplant: a small tool iterates the branch list, cherry-picks the known-good commit hash onto each, opens a review per branch, and a tracking issue lists every branch plus its landing status — because "did every branch get the fix" is the real question, not "how do I cherry-pick."

The trade-off you'd defend

I would automate the per-branch cherry-pick and verify it with git branch --contains <hash> against the full branch list, trading a bit of tooling investment for a guarantee that no supported branch silently misses a security fix.

Illustrative figures for the arithmetic. Cherry-picking a fix across many maintained branches is standard practice in large platform projects such as Android/AOSP, but the branch count and commit numbers here are mine, not Google-published.

Gotchas

Rewriting shared commits makes collaborators' histories diverge

Symptom

After you rebase or force-push a branch, teammates' git pull reports diverged branches or unexpected conflicts on commits they didn't even touch.

Cause

Rebase gives every rewritten commit a new hash; anyone who already had the old commits now has a different, incompatible view of the same branch.

Fix

Only rebase branches you're the sole owner of. If a shared branch genuinely must be rewritten, tell everyone first and have them re-base their own work on top afterward (git pull --rebase, not the default merge pull).

Cherry-pick "duplicate" confusion

Symptom

After merging a branch you already cherry-picked a fix from, you expect either a conflict or a duplicate commit, and get a different result than you expected either way.

Cause

The cherry-picked commit and the original have identical trees but different hashes; git's merge machinery may recognize the result as already present (a no-op) or may still show it as a distinct change, depending on the merge strategy and what else changed nearby.

Fix

Don't assume either outcome — check the actual resulting diff after the merge, not just whether git reported a conflict.

Interactive rebase abandoned mid-way

Symptom

You're stuck in a "rebase in progress" state and can't switch branches.

Cause

A conflict during an interactive rebase pauses it; the repository stays in a special state until you resolve and --continue, or bail out.

Fix

git rebase --abort returns you exactly to where you started if you want out; only use --continue once every conflict in the current step is resolved and staged.

Tricky questions

Is git cherry-pick the same as copy-pasting the diff by hand?
Most people say

Pretty much — it just applies the same text changes.

Actually

It replays the change through git's merge machinery, so it can conflict, and unlike a manual copy-paste it preserves the original commit's message and authorship by default — it's a real commit operation, not a text operation.

Does git rebase -i let you edit a commit's content without changing its identity?
Most people say

Yes, reword or editing a commit just updates it in place.

Actually

Every rewritten commit gets a brand-new hash, even reword, which only changes the message. There's no in-place edit in git — only "replace with a new commit that looks similar."

Scenario question

You're handed a request: "squash my last five commits into one before you open the PR, but don't lose the WIP history in case review asks about a specific step."

Model answer

I'd do the squash on the PR branch with an interactive rebase (or the reset --soft plus recommit equivalent), because that's what makes the diff reviewable as one unit. To keep the step-by-step history available without polluting the PR, I'd branch or tag the pre-squash tip first — git branch archive/pre-squash-<ticket> — before rewriting anything. The trade-off is one extra disposable branch to clean up later, in exchange for never having to answer "can you get that back" with "no."

Interview corner

CommonWhat does git cherry-pick actually do?
“It takes the diff a commit introduced and re-applies it as a brand-new commit wherever I currently am. Same content, new parent, new hash — it's a copy, not a move.”
TrickIf I cherry-pick a commit and later merge the branch it came from, do I get a duplicate?
“Usually not a duplicate commit, but git might see it as a conflict or a no-op, because the resulting tree is already identical, depending on the merge strategy. I still check the diff afterward, because the commit ids are genuinely different objects underneath.”
Experience checkWhen have you used interactive rebase for real?
“Cleaning up a branch before opening a PR — squashing three 'fix typo' commits into the one they were fixing, so the reviewer sees one coherent change instead of my debugging trail.”
DesignHow would you safely backport a security fix to five old release branches?
“I'd cherry-pick the exact commit hash onto each branch individually, then verify with git branch --contains <hash> that all five actually have it, tracked in one issue instead of trusting five separate memories.”

Memory hook

Cherry-pick photocopies a commit into a new envelope; rebase re-seals a whole stack of envelopes onto a new base.

If you remember only one thing:

Same diff, new hash, every time you rewrite or transplant a commit.

Self-check

  1. Does cherry-picking a commit change its file contents?

    No — the resulting tree is identical; only the commit's identity (hash, parent) changes.

  2. Why shouldn't you casually rebase a branch other people have pulled?

    Every commit gets a new hash, so their existing history diverges from yours and has to be manually reconciled.

  3. What's the practical difference between git commit --amend and a fresh commit?

    --amend replaces the tip commit with a new one (new hash) carrying your changes, instead of adding a second commit on top of it.

Prove it

Create a commit on a hotfix branch and cherry-pick it onto main. Print both commits' hashes and both commits' tree hashes (git rev-parse <ref>^{tree}), and show the trees match while the commit hashes differ.

ce-01-04Card 4 of 6

Resolve conflicts and recover lost work

MediumP2 · Very likelyKnow cold11 min
merge-conflictsreflogrecoveryreset-revert-restore

Why you care

A merge conflict resolved by "whoever's turn it is picks a side," and a reset --hard that looks like it deleted three days of work, are two of the most common ways a competent developer loses real work or ships a real bug — quietly, with a green build. Interviewers probe conflict resolution and reflog recovery because both separate people who understand git's model from people who've memorized a sequence of commands that usually works. This card is the safety net under everything else in the chapter: rebase, cherry-pick and even trunk-based merging all eventually produce a conflict or a mistake, and this is how you get out of it without losing anything.

Explain like I'm 5

A merge conflict is two people editing the same paragraph of a shared document, and the editor refusing to guess whose sentence should win. Reflog is that document's undo history sitting quietly in the background even after you "delete" a paragraph — it's not a backup, it's more like a browser's back button: genuinely useful, temporary, and not something to build a real safety plan around.

Core concept

A merge conflict means git found two changes to the same lines (or the same file, deleted on one side and edited on the other) and refuses to guess which one you want:

  • Conflicted files show <<<<<<<, =======, >>>>>>> markers around both versions; git status marks them unmerged (UU, or AA, DU, and similar, depending on the exact conflict type).
  • Resolve by intent, not by picking a side: read both changes, understand what each was trying to do, and write the version that satisfies both. git checkout --ours/--theirs mechanically picks a whole file and should be a last resort, not a default.
  • After editing, git add the resolved file — this is what tells git "resolved," regardless of whether markers are technically gone — and run the relevant tests before committing. A syntactically clean resolution can still be logically wrong.

Losing work and recovering it is a separate, related skill:

  • git reflog records every commit HEAD has pointed at recently, even across a reset --hard or an abandoned rebase. Entries still reachable from some branch keep the default 90-day expiry (gc.reflogExpire), but entries that are now unreachable from any branch — exactly the "lost commit" case this card is about — default to a shorter 30-day expiry (gc.reflogExpireUnreachable).
  • The recovery habit: the moment you realize something's missing, create a branch at the recovered hash before doing anything else (git branch recovery/<name> <hash-from-reflog>), so it's safe from whatever you run next while investigating.
  • reset moves a branch pointer (and optionally the index/working tree) with no new commit — fine for your own unpushed history, dangerous on anything shared. restore undoes changes in the working tree or index for specific files, without moving any branch. revert adds a brand-new commit that undoes an earlier one's changes — the only one of the three that's safe on already-shared history.

Reflog is not a backup policy: it's local-only, time-limited, and gone the moment a repo is deleted or freshly re-cloned. Anything that must survive belongs on a remote.

Minimal example A conflict that needs a decision, not a tool

PythonA merge conflict, resolved by intentruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


def git_ok(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True)


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")
open("config.py", "w").write("TIMEOUT = 30\n")
git("add", "config.py")
git(*ident, "commit", "-q", "-m", "base timeout")

git("checkout", "-q", "-b", "raise-timeout")
open("config.py", "w").write("TIMEOUT = 90\n")
git("add", "config.py")
git(*ident, "commit", "-q", "-m", "raise timeout for slow vendor")

git("checkout", "-q", "main")
open("config.py", "w").write("TIMEOUT = 45\n")
git("add", "config.py")
git(*ident, "commit", "-q", "-m", "raise timeout for retries")

r = git_ok(*ident, "merge", "-q", "--no-edit", "raise-timeout")
print("merge reports conflict:", r.returncode != 0)
status = git("status", "--short")
print("conflict marker in file:", "<<<<<<<" in open("config.py").read())
print("git flags file as unmerged:", status.startswith("UU"))

# resolve by intent: the vendor genuinely needs 90s; keep it, then finish the merge
open("config.py", "w").write("TIMEOUT = 90\n")
git("add", "config.py")
git(*ident, "commit", "-q", "-m", "merge: keep 90s vendor timeout")
print("merge commit exists:", git("cat-file", "-t", "HEAD") == "commit")
Output
merge reports conflict: True
conflict marker in file: True
git flags file as unmerged: True
merge commit exists: True

In production Reflog recovers what reset --hard "lost", and revert is the safe undo

PythonLose three commits, recover one from reflog, then revert safelyruns
import subprocess, os

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")

for i, msg in enumerate(["load", "transform", "validate"], start=1):
    open(f"step{i}.py", "w").write(f"STEP = {i}\n")
    git("add", f"step{i}.py")
    git(*ident, "commit", "-q", "-m", msg)

lost_commit = git("rev-parse", "HEAD")
git(*ident, "reset", "-q", "--hard", "HEAD~1")   # oops: meant to unstage, not rewind

print("HEAD after the mistake:", git("log", "-1", "--format=%s"))
print("validate commit missing from log:",
      lost_commit not in git("log", "--format=%H").split())

recovery_point = git("reflog", "-1", "--format=%H", "HEAD@{1}")
print("reflog still remembers it:", recovery_point == lost_commit)
git("branch", "-q", "recovery/validate", recovery_point)
git(*ident, "merge", "-q", "--ff-only", "recovery/validate")
print("HEAD after recovery:", git("log", "-1", "--format=%s"))

# reset moved a local pointer with no new commit; revert instead adds one,
# which is the version safe to use once history is already shared
git(*ident, "revert", "--no-edit", "HEAD")
print("revert added a new commit:", git("log", "-1", "--format=%s").startswith("Revert"))
print("total commits now:", int(git("rev-list", "--count", "HEAD")))
Output
HEAD after the mistake: transform
validate commit missing from log: True
reflog still remembers it: True
HEAD after recovery: validate
revert added a new commit: True
total commits now: 4

See it happen Mistake, reflog, recovery

yougitrefloggit reset --hard HEAD~1HEAD now at 'transform'git reflogHEAD@{1} = validate commitgit branch recovery/validate <hash>recovery/validate created
  1. You meant to unstage a file but rewound the branch by a whole commit instead.
  2. The 'validate' commit is no longer reachable from any branch — but it isn't deleted yet.
  3. Reflog remembers every place HEAD has pointed on this machine; an unreachable commit like this one defaults to a 30-day expiry.
  4. The lost commit's exact hash is sitting right there.
  5. Create a branch at the recovered commit before running anything else.
  6. The commit is safe again; now merge or cherry-pick from the recovery branch.
Notice: nothing about the recovery required knowing the commit's content in advance — the reflog gave up the hash, and everything after that is the same branch-and-merge mechanics as any other commit.
Scenario A

In your world

The situation

Two people edit pricing_config.py at the same time: one raises a timeout, the other changes a retry count. Your merge shows a conflict.

What actually breaks

Under deadline pressure, someone runs git checkout --theirs pricing_config.py to "make the conflict go away" without reading either change, stages it, and commits. The retry-count fix silently disappears; nobody notices until retries start failing again in production weeks later.

What you'd do on Monday

Resolve by intent, not by side: open the file, understand both changes, write the version that keeps both, then test before committing.

Shell
git status                       # confirms which files are still "both modified"
# edit pricing_config.py by hand to keep both the new timeout and the new retry count
git add pricing_config.py
pytest tests/test_pricing_config.py
git commit                       # only after tests pass
Scenario B

Imagine you work at Zomato

~3 merge conflicts a day on one config repo

The numbers

Illustrative: a 25-engineer team merging into one service's config repo roughly 60 times a day produces on the order of 60 merge opportunities daily. If even 5% conflict, that's 3 conflicts a day, each costing 10-15 minutes to resolve by hand — cheap, until one botched resolution ships a wrong discount percentage to production.

What the Scenario-A answer does here

The Scenario A fix (resolve by intent, then test) still works, but "whoever merges last just picks their version to make the conflict go away" does not: at 3 conflicts a day, a few coin-flip resolutions a month will silently drop a teammate's fix, with no error anywhere to catch it.

What flips at this scale

At this frequency, teams add a rule that a resolved conflict must run the affected tests before it can be pushed, and treat git status showing unmerged files as a hard stop, not a courtesy. Some also route config changes through a smaller number of owners specifically to cut the conflict rate, not just to resolve conflicts faster.

The trade-off you'd defend

I would defend mandatory test-before-push on any resolved conflict over trusting the resolver's judgment alone, trading a slightly slower merge for not shipping a silently wrong config value.

Illustrative figures for the arithmetic; not Zomato-published numbers.

Gotchas

Picking a whole side instead of resolving by intent

Symptom

A conflict "resolves" cleanly with --ours/--theirs, but a feature that was working stops working a few days later.

Cause

One side's entire change was discarded wholesale, including parts that weren't actually in conflict with the other side's intent.

Fix

Read both changes before resolving; use --ours/--theirs only when you're certain one side should fully lose, not as a default shortcut.

Reflog isn't forever

Symptom

A commit you were sure git reflog would recover isn't there.

Cause

Reflog entries for commits no branch references expire in about 30 days by default, and are local-only — they don't survive a fresh clone or, eventually, a git gc.

Fix

Recover from reflog as soon as you notice something's missing, and don't rely on it as a substitute for pushing work-in-progress to a remote.

reset --hard on a branch others have pulled

Symptom

A teammate's next git pull on the same branch reports it's diverged, or silently reintroduces the commits you just removed.

Cause

reset --hard rewrites a branch's history locally; pushing that over a shared branch leaves everyone else's copy based on commits that no longer exist upstream.

Fix

On shared branches, undo with git revert, which adds a new commit instead of erasing old ones.

Tricky questions

After resolving a conflict and running git add, must the <<<<<<< markers actually be gone?
Most people say

Git checks that the conflict markers are removed before letting you commit.

Actually

Git doesn't parse your file for markers at all — git add just means "I've resolved this," even if you accidentally leave a marker in. That's exactly why running tests before committing matters.

Is git reflog a project-wide history, like git log --all?
Most people say

Yes, it shows everything anyone on the team has done.

Actually

Reflog is per-clone and local: it only records where your HEAD has pointed, on your machine. It has nothing to do with anyone else's actions, and it isn't shared by pushing or pulling.

Scenario question

You're handed a report: "I ran git reset --hard origin/main to clean up my branch and now three days of commits are gone." What do you do, in order?

Model answer

First, I don't run anything that checks out new commits yet, since that's how you can accidentally push an old-enough reflog entry further away. I run git reflog on their machine to find the commit hash HEAD pointed at right before the reset. Then I immediately create a recovery branch at that hash: git branch recovery/<name> <hash>. Only after that branch exists do I look at what's actually on it and decide whether to rebase it back onto main or cherry-pick the useful pieces. The trade-off I'd flag afterward: reflog saved this today, but an unreachable commit like this one typically expires in about 30 days and is local-only, so it is not a substitute for pushing work-in-progress to a remote branch.

Interview corner

CommonWalk me through resolving a merge conflict.
“git status tells me which files are still unmerged. I open each one, understand what both sides were trying to do, edit it to reflect both intents, then git add it. Before committing I run the relevant tests, because a syntactically valid resolution can still be logically wrong.”
TrickIs git reset --hard a safe way to undo a bad merge on a shared branch?
“Not if anyone else already pulled it — reset moves the branch pointer locally, and pushing that history change forces everyone else to reconcile. On shared history I'd use git revert, which adds a new commit undoing the changes and is safe to push.”
Experience checkTell me about a time you recovered lost commits.
“Someone ran reset --hard one commit too many. I ran git reflog, found the hash HEAD had pointed at right before, branched from it immediately, and only then decided whether to rebase it back in. The key habit is making a recovery branch before touching anything else.”
DesignHow would you reduce how often your team hits merge conflicts, not just resolve them faster?
“I'd check whether a small number of files are contention points — often shared config — and either split them or restrict who edits them directly, plus shrink how long branches diverge before merging, since conflict rate tracks branch lifetime pretty closely.”

Memory hook

Resolve a conflict by intent, not by picking a side; recover lost work from the reflog, but don't mistake it for a backup.

If you remember only one thing:

reset moves a pointer, revert adds a commit — pick based on whether the history is already shared.

Self-check

  1. What do the two letters in git status --short's UU mean?

    Both sides — index and working tree — have unresolved changes to that file; it's unmerged.

  2. Why does git reflog still show a commit that git log doesn't?

    git log only shows commits reachable from the current ref; reflog records every place HEAD has pointed, reachable or not, until it expires.

  3. When would you use revert instead of reset to undo a bad commit?

    When the commit has already been pushed or pulled by someone else; revert adds a new commit instead of rewriting history others depend on.

Prove it

Create a merge conflict between two branches on purpose, resolve it, and commit. Then run git reset --hard HEAD~2 to simulate losing that work, recover it via git reflog and a new branch, and paste the git log --oneline output before the reset, after the reset, and after recovery.

ce-01-05Card 5 of 6

Locate a regression with bisect

MediumP3 · Role-dependentTalk about it11 min
git-bisectregressiondebuggingbinary-search

Why you care

"Something in the last N commits broke this" is one of the most common real debugging situations, and reading every diff by hand doesn't scale past a handful of commits. Interviewers ask about git bisect specifically to see whether you reach for a systematic tool or just start guessing, and the follow-up question — what if your test is flaky — separates people who've actually run it from people who've only heard of it. This card matters on its own because, unlike the rest of the chapter, it's a tool you use after something already went wrong in production, not a habit you practice daily.

Explain like I'm 5

Guessing a number between 1 and 1,000 by asking "higher or lower" cuts the search in half every question, about 10 questions instead of up to 1,000 guesses. git bisect plays that exact game with commits: you tell it "good" or "bad," and it checks out the middle of whatever's left.

Core concept

git bisect turns "which of these N commits broke it" into a binary search over commits instead of a linear scan:

  • git bisect start, then tell it one known-good and one known-bad revision (git bisect good <ref>, git bisect bad <ref>). It checks out a commit roughly in the middle of what's left.
  • You report the verdict — git bisect good or git bisect bad — and it checks out the new midpoint of the now-smaller range. About log2(N) rounds instead of N.
  • git bisect run <script> automates the whole loop: the script must exit 0 for good, and any code in 1-127 except 125 counts as bad, with 125 reserved to mean "can't tell, skip this one" (an unbuildable or genuinely untestable revision) rather than guessing. Any exit code outside 0-127 (for example 130, from a SIGINT) doesn't get scored as bad at all — it aborts the whole bisect run instead.
  • git bisect skip does the same thing manually, and if too many consecutive commits get skipped right at the true boundary, bisect can run out of information and report an ambiguous range ("could be any of...") instead of a single commit — skip narrows the search, it doesn't guarantee resolving it.
  • git bisect reset ends the session, restores your original HEAD, and cleans up the bisect state.

The entire technique depends on one thing that has nothing to do with git: a deterministic check. A test that's flaky 5% of the time will occasionally mislabel a commit, and bisect has no way to detect that its input was wrong — it will converge confidently on the wrong commit.

Decision rule: reach for bisect when the candidate range is large enough that log2(N) actually beats reading diffs by hand, and only after you have, or can build, a check that gives the same answer every time on the same commit.

Under the hood

git bisect doesn't literally test the numeric midpoint of a flat commit list; it walks the commit graph (using cached generation-number/commit-graph data when available) to pick the commit that best halves the reachability between the current good and bad boundaries, which matters once branches and merges are involved and not just a straight line. That's also why the "roughly N steps" estimate it reports can shift slightly as you answer: each good/bad narrows the actual graph range, not a pre-computed flat array.

Minimal example Bisect checks out the midpoint, not the tip

PythonBisect moves in halves, not one commit at a timeruns
import subprocess, os, pathlib

os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")

commits = []
for i in range(1, 5):
    pathlib.Path("job.py").write_text(f"# revision {i}\n")
    git("add", "job.py")
    git(*ident, "commit", "-q", "-m", f"revision {i}")
    commits.append(git("rev-parse", "HEAD"))

git("bisect", "start")
git("bisect", "bad", commits[3])
git("bisect", "good", commits[0])
midpoint = git("rev-parse", "HEAD")
print("bisect checks out a midpoint, not the tip:", midpoint == commits[1] or midpoint == commits[2])

git("bisect", "good")
current = git("rev-parse", "HEAD")
print("next candidate is the remaining half:", current in (commits[2], commits[3]))

git("bisect", "reset")
print("HEAD back on the branch tip:", git("rev-parse", "HEAD") == commits[3])
Output
bisect checks out a midpoint, not the tip: True
next candidate is the remaining half: True
HEAD back on the branch tip: True

In production A skipped, unbuildable revision can leave bisect's answer ambiguous

PythonAn untestable commit right at the boundary breaks full resolutionruns
import subprocess, os, pathlib, sys

root = pathlib.Path(".").resolve()
os.makedirs("repo")
os.chdir("repo")


def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()


ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")

good_body = "def add(a, b):\n    return a + b\n"
bad_body = "def add(a, b):\n    return a - b\n"
broken_body = "def add(a, b:\n    return a + b\n"          # a revision that never builds
bodies = {i: good_body for i in range(1, 7)}
bodies.update({i: bad_body for i in range(7, 11)})
bodies[6] = broken_body   # the build was broken right at the edge of the real regression

commits = []
for i in range(1, 11):
    pathlib.Path("calc.py").write_text(f"# revision {i}\n{bodies[i]}")
    git("add", "calc.py")
    git(*ident, "commit", "-q", "-m", f"revision {i}")
    commits.append(git("rev-parse", "HEAD"))

checker = root / "check.py"
checker.write_text(
    "import sys\n"
    "src = open('calc.py').read()\n"
    "ns = {}\n"
    "try:\n"
    "    exec(compile(src, 'calc.py', 'exec'), ns)\n"
    "except SyntaxError:\n"
    "    sys.exit(125)\n"            # 125 = "cannot tell, skip this revision"
    "sys.exit(0 if ns['add'](2, 3) == 5 else 1)\n"
)

git("bisect", "start")
git("bisect", "bad", commits[-1])
git("bisect", "good", commits[0])
r = subprocess.run(["git", "bisect", "run", sys.executable, str(checker)],
                    capture_output=True, text=True)

print("bisect could not fully resolve on its own:", r.returncode != 0)
print("both remaining candidates are the broken build and its successor:",
      commits[5] in r.stdout and commits[6] in r.stdout)

git("bisect", "reset")
print("bisect metadata removed:", not pathlib.Path(".git/BISECT_START").exists())
print("HEAD restored to tip:", git("rev-parse", "HEAD") == commits[-1])
Output
bisect could not fully resolve on its own: True
both remaining candidates are the broken build and its successor: True
bisect metadata removed: True
HEAD restored to tip: True

See it happen The bisect protocol

yougit bisectgit bisect startgit bisect bad HEADgit bisect good v2024.03.01checks out a midpoint of the unknown rangegit bisect badchecks out the new midpointgit bisect goodcommit X is the first bad commit
  1. Begin a search between a known-good and a known-bad revision.
  2. Mark the current tip as bad.
  3. Mark an older, confirmed-good revision.
  4. It jumps to roughly the middle of what's left, not the middle of the file's whole history.
  5. You run the deterministic check yourself and report the verdict.
  6. The search halves again using only the verdicts you've given so far.
  7. Report the next verdict.
  8. Roughly log2(N) steps found it, instead of testing all N commits by hand.
Notice: every message from git bisect is a checkout, and every message from you is a verdict — the whole protocol is just that exchange, repeated until the range is one commit wide.
Scenario A

In your world

The situation

The nightly ETL job's row-count reconciliation started failing intermittently sometime in the last 60 commits, and nobody flagged which change did it.

What actually breaks

Someone starts reading all 60 diffs top to bottom "to be safe," burning half a day, and still isn't sure which commit is the actual cause, because three of the diffs touch the reconciliation code.

What you'd do on Monday

Write one deterministic check, then let bisect search.

Shell
git bisect start
git bisect bad HEAD
git bisect good v2024.03.01
git bisect run python check_reconciliation.py
git bisect reset
Scenario B

Imagine you work at Postman

bisecting a 400-commit regression window

The numbers

Illustrative: a collection-runner regression is somewhere across 400 commits merged since the last verified-good release. Testing each commit by hand at 5 minutes each is up to 2,000 minutes, over 33 hours; git bisect needs about log2(400) ≈ 9 tests, roughly 45 minutes at the same 5 minutes each.

What the Scenario-A answer does here

The Scenario A bisect setup still works, but "run the flaky end-to-end suite as the bisect check" does not: a test that fails 1 time in 20 for reasons unrelated to the regression will mislabel a good commit as bad, and bisect will converge on the wrong commit with complete confidence.

What flips at this scale

At this scale you invest in a narrow, deterministic reproduction — one request, one assertion, no network flakiness — before bisecting, because the cost of a wrong bisect answer is a whole extra round of debugging on the wrong commit, not just a slower search.

The trade-off you'd defend

I would spend 15 minutes writing a minimal, deterministic repro before running an automated bisect over 400 commits, trading upfront time for a search whose answer I can actually trust.

Illustrative figures for the arithmetic; not Postman-published numbers.

Gotchas

A flaky check poisons the whole search

Symptom

git bisect confidently reports a commit as the cause, but the diff has nothing to do with the actual bug.

Cause

The check used for at least one good/bad verdict was nondeterministic and happened to give the wrong answer once.

Fix

Verify the check is deterministic on a couple of known commits before trusting a bisect run over dozens of them; narrow the repro if the original test is flaky.

Forgetting to reset bisect state

Symptom

The repo stays checked out on some arbitrary commit in the middle of history, and normal branch commands feel broken.

Cause

git bisect checks out commits directly (detached HEAD) throughout the search and doesn't restore your branch until told to.

Fix

Always run git bisect reset when you're done, even if you found the answer manually and didn't finish the automated flow.

Too many skips right at the real boundary

Symptom

Bisect reports "the first bad commit could be any of" instead of a single hash.

Cause

The commit that would have definitively split good from bad was itself unbuildable and got skipped, leaving genuine ambiguity.

Fix

Fix or work around the build issue for that one commit if possible, or manually decide between the reported candidates using their diffs directly.

Tricky questions

Does git bisect test commits in a fixed order decided in advance?
Most people say

Yes, it picks a schedule of commits before you start answering.

Actually

It picks the next commit to test based on your previous answer, narrowing the remaining range each time — the exact sequence depends entirely on what you report as good or bad.

Does git bisect skip count as "good" toward finding the first bad commit?
Most people say

It's treated like "good," just softer.

Actually

It's neither good nor bad — the commit is excluded from consideration entirely. If enough skips cluster right at the true boundary, bisect can run out of information and report an ambiguous range instead of one commit.

Scenario question

You're handed "find which of these ~200 commits broke the checkout flow," and the only reproduction is a manual click-through in a browser that takes 3 minutes and is right about 90% of the time.

Model answer

I'd spend the first hour turning that manual click-through into a deterministic, scriptable check, even a rough one, because a 90%-reliable predicate will make bisect converge on a wrong commit with full confidence, and I'd have no way to tell. Once I have something deterministic, I wrap it in a script that exits 0 or 1 and run git bisect start / bad / good / run script.sh, which needs roughly log2(200) ≈ 8 tests instead of up to 200. The trade-off is the hour spent on the check, but it's cheaper than debugging the wrong commit after a flaky bisect confidently points at it.

Interview corner

CommonHow does git bisect work?
“I'd tell it one known-good and one known-bad commit; it checks out the midpoint of what's left, I report good or bad, and it halves the remaining range each time — roughly log2(N) steps instead of N.”
TrickWhat happens if your bisect check is flaky?
“It'll mislabel a commit, and bisect will converge on the wrong one with total confidence, since it has no way to know the check lied. Before bisecting seriously, I make sure the check is deterministic, even if that means writing a narrower repro than the original bug report.”
Experience checkHave you used git bisect run?
“Yes, with a small script that exits 0 or 1 based on one specific assertion, not the full test suite, because I want it fast and deterministic. I've also used git bisect skip for a couple of commits that genuinely didn't build.”
DesignWould you always reach for bisect, or when would you skip it?
“If I already have a strong hypothesis from the diff of the last few commits, I'd just check those directly. Bisect earns its cost when the candidate range is large enough that log2(N) actually beats guessing, and when I have or can build a check that's fast and reliable.”

Memory hook

Bisect is 20 questions played against your own commit history.

If you remember only one thing:

A flaky check makes bisect confidently wrong — fix the check before you trust the answer.

Self-check

  1. Roughly how many tests does bisect need for 500 commits?

    About log2(500) ≈ 9, versus up to 500 for a linear scan.

  2. What exit code tells git bisect run to skip a commit instead of marking it good or bad?

    125.

  3. Why can a flaky test make bisect worse than useless?

    It can mislabel a good commit as bad, or vice versa, and bisect has no way to detect the lie — it converges confidently on the wrong commit.

Prove it

Write 10 commits where a function's return value silently changes on commit 6. Write a deterministic checker script and run git bisect start, bad, good, run <script>. Paste the output line naming the first bad commit, then git bisect reset.

ce-01-06Card 6 of 6

Make PRs and hooks useful safeguards

EasyP2 · Very likelyTalk about it10 min
pull-requestsgit-hookscode-reviewci-gates

Why you care

A pre-commit hook that only exists on your laptop, and a PR that gets rubber-stamped with "looks good," are both safeguards that feel real and aren't. Interviewers ask about code review and hooks because the answer to "where does this actually get enforced" reveals whether you understand the difference between a convention and a guarantee. This closes the chapter because everything before it — clean history, sensible branches, resolved conflicts — only stays true on a team if something server-side actually checks for it.

Explain like I'm 5

A pre-commit hook is a smoke detector in your own kitchen: useful, but if you remove the battery — or someone moves in and never installs one — it stops protecting anyone. A PR review and a CI gate are the building's fire code: checked by someone else, before the building goes up, regardless of whose kitchen it is.

Core concept

A pull request and a git hook solve the same problem — catch a mistake before it ships — at two different layers with very different guarantees:

  • PR hygiene: small, single-purpose diffs review faster and more accurately than large ones; a description that states why, not just what, lets a reviewer evaluate intent, not just syntax; and evidence (test output, a screenshot, a specific scenario checked) turns "looks fine" into "verified this."
  • Git hooks (pre-commit, pre-push, and others) are scripts under .git/hooks/ that run automatically at specific points. They're fast, local, and give immediate feedback.
  • Hooks are never cloned or pushed — .git/hooks is local repository metadata, not tracked content, so a fresh clone starts with none installed, and --no-verify skips whichever ones are there anyway.
  • Because of that, hooks can speed up feedback but cannot enforce a shared rule. Anything that must always be true — a required check, a required review — has to live server-side: branch protection on the hosting platform, enforced in CI, gating the merge button itself.

Decision rule: use local hooks for fast, optional feedback that saves round trips to CI (lint, obvious secrets, formatting); put the same checks in CI as required status checks if they must actually block a merge, because that copy is the only one that runs regardless of whose machine, whose clone, or whose habits are involved.

Minimal example Hooks live in .git/hooks and are never cloned

PythonA hook that exists in one clone and not the otherruns
import subprocess, os, pathlib


def git(*args, **kw):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True, **kw).stdout.strip()


os.makedirs("origin")
os.chdir("origin")
git("init", "-q", "-b", "main")
open("f.txt", "w").write("1\n")
git("add", "f.txt")
git("-c", "user.name=Dev", "-c", "user.email=dev@example.com", "commit", "-q", "-m", "init")
pathlib.Path(".git/hooks/pre-commit").write_text("#!/bin/sh\nexit 1\n")
os.chdir("..")

git("clone", "-q", "origin", "clone")
print("hook exists in the original repo:", pathlib.Path("origin/.git/hooks/pre-commit").exists())
print("hook exists in the clone:", pathlib.Path("clone/.git/hooks/pre-commit").exists())
Output
hook exists in the original repo: True
hook exists in the clone: False

In production A pre-commit hook that blocks a real mistake, and how --no-verify bypasses it

PythonA hook that catches a leaked key, and the flag that skips itruns
import subprocess, os, pathlib, stat


def git(*args, check=True):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=check)


os.makedirs("repo")
os.chdir("repo")
ident = ["-c", "user.name=Dev", "-c", "user.email=dev@example.com"]
git("init", "-q", "-b", "main")

hook = pathlib.Path(".git/hooks/pre-commit")
hook.write_text(
    "#!/bin/sh\n"
    "if git diff --cached | grep -q 'AKIA'; then\n"
    "  echo 'blocked: looks like an AWS access key' >&2\n"
    "  exit 1\n"
    "fi\n"
)
hook.chmod(hook.stat().st_mode | stat.S_IEXEC)

pathlib.Path("settings.py").write_text("AWS_KEY = 'AKIAABCDEFGHIJKLMNOP'\n")
git("add", "settings.py")
blocked = git(*ident, "commit", "-q", "-m", "add settings", check=False)
print("hook blocked the commit:", blocked.returncode != 0)
print("stderr:", blocked.stderr.strip())

pathlib.Path("settings.py").write_text("AWS_KEY = 'from-env'\n")
git("add", "settings.py")
allowed = git(*ident, "commit", "-q", "-m", "read key from env", check=False)
print("clean commit succeeds:", allowed.returncode == 0)

bypassed = git(*ident, "commit", "--allow-empty", "--no-verify", "-q", "-m", "bypass")
print("bypass with --no-verify succeeds even with a real violation:", bypassed.returncode == 0)
Output
hook blocked the commit: True
stderr: blocked: looks like an AWS access key
clean commit succeeds: True
bypass with --no-verify succeeds even with a real violation: True
Scenario A

In your world

The situation

Your local pre-commit hook blocks commits with an obvious print()-debugging leftover, and it's caught a dozen slip-ups this quarter.

What actually breaks

A teammate joins, clones the repo, and never runs the one-time pre-commit install step. Their commits skip the check with no error, no warning; the first anyone hears about it is a print() line showing up in a production log.

What you'd do on Monday

Never rely on a hook that only lives on some machines. Put the same check in the PR pipeline as a required status check, so it blocks the merge button regardless of whose laptop it is.

Shell
pre-commit install                    # local convenience, easy to forget on a new clone
# CI (Jenkinsfile or .github/workflows/ci.yml) runs the same check as a required status
# check on the PR — that copy is the one that actually protects main
Scenario B

Imagine you work at Freshworks

required checks across ~90 PRs a day

The numbers

Illustrative: a 40-engineer product team merging around 90 pull requests a day cannot have every reviewer manually re-run linting and tests. If a manual check takes 4 minutes and gets skipped 10% of the time under deadline pressure, that's roughly 9 unchecked merges a day reaching mainline.

What the Scenario-A answer does here

The Scenario A fix (a local pre-commit hook) still catches obvious mistakes on a developer's own machine, but "we trust everyone's local hook is installed and enabled" does not hold: hooks live in .git/hooks, are never cloned, and a new laptop or a --no-verify habit silently removes the safeguard with no error anywhere.

What flips at this scale

At this scale the hook's job shifts from enforcing to speeding up feedback: the same checks become mandatory in CI on the PR itself, gating the merge button, and the local hook becomes an optional convenience that fails fast before anyone even pushes.

The trade-off you'd defend

I would keep local hooks for fast, optional feedback and make CI the only place a check can actually block a merge, trading a few extra minutes of CI queue time for a guarantee that no single missing hook lets a bad change through.

Illustrative figures for the arithmetic; not Freshworks-published numbers.

Gotchas

A local hook is absent from another clone and cannot enforce a shared release gate

Symptom

A check that's been reliably blocking bad commits on your machine does nothing on a teammate's, or in CI, with no error anywhere.

Cause

.git/hooks is local repository metadata; it is never committed, cloned, or pushed, so every clone starts with zero hooks installed.

Fix

Treat hooks as optional local speed-up only; put anything that must always run as a required CI check that gates the merge, not as a hook.

--no-verify becomes a habit

Symptom

A hook that should have caught something didn't, and nobody remembers disabling it.

Cause

--no-verify silently skips all hooks for that one commit or push, with no log entry pointing back at who did it or why.

Fix

If bypassing a hook is sometimes legitimate, make that an explicit, logged, reviewable action — a PR comment, a documented override — rather than a silent flag.

A PR that's technically reviewed but not really

Symptom

A bug ships that a five-minute look at the diff would have caught, despite an "Approved" review.

Cause

Large scope and a vague description make it easy to approve without actually tracing the logic; the review became a formality.

Fix

Push back on PR size and description quality as a reviewer, not just on the code — a reviewer can't meaningfully evaluate what they can't reasonably read.

Tricky questions

Does a required PR review guarantee the code was actually checked?
Most people say

Yes, if it shows "Approved," someone verified it.

Actually

It guarantees someone clicked approve — the platform can't tell a five-second rubber stamp from a careful read. The actual guarantee it enforces is procedural (a human in the loop), not a claim about review quality.

Does removing a pre-commit hook file stop it from ever running again for anyone?
Most people say

Yes, deleting it from the repo removes the check for everyone.

Actually

Hooks live in .git/hooks, which was never tracked by the repo in the first place — deleting a hook script from your working directory only affects your own clone. Anyone else's installed hook, or the absence of one, is entirely independent.

Scenario question

You're handed a request: "add a pre-push hook that stops anyone from pushing straight to main." Is that the right fix?

Model answer

I'd push back a little: a pre-push hook is local, so it protects only the machine it's installed on, and anyone can bypass it with --no-verify or simply not install it. The actual guarantee needs to live server-side — branch protection on main requiring a PR and passing status checks, enforced by the hosting platform, not by client-side git. I'd still add the local hook as a fast, optional convenience that catches the mistake before a push even leaves the laptop, but I'd tell leadership the real control is the branch protection rule, and I'd verify it's actually turned on rather than assuming it is.

Interview corner

CommonWhat's the difference between a pre-commit hook and a CI check?
“A pre-commit hook runs locally, is opt-in, and lives in .git/hooks, which is never cloned or shared. A CI check runs on the server for every push or PR and can actually gate the merge button. I use hooks for fast local feedback and CI for the real enforcement.”
TrickIf everyone on the team has the hook installed, is that enough to enforce a rule?
“I'd say no — hooks are per-clone, so a new machine, a fresh CI runner, or someone's --no-verify all bypass it silently with no error anywhere. Anything that must always be true needs a server-side check, not a client-side one.”
Experience checkWhat makes a pull request easy versus hard to review?
“I'd look for small scope and a clear reason in the description, plus evidence it works, like test output or a specific scenario checked. A 200-file PR with 'various fixes' as the description gets a rubber-stamp approval from me, not a real review, which defeats the point of having one.”
DesignHow would you roll out a mandatory lint check across a team without breaking everyone's workflow overnight?
“I'd add it to CI as a required check on new PRs first, in warn-only mode, then flip it to blocking once the existing backlog of violations is cleared, and offer the same check as an optional local hook so people get the feedback before they even push.”

Memory hook

A hook is a smoke detector in your own kitchen; a CI gate is the building's fire code.

If you remember only one thing:

If it must always be true, it belongs in CI, not in .git/hooks.

Self-check

  1. Are git hooks committed and shared when someone clones the repo?

    No — .git/hooks is local metadata, never cloned or pushed; each clone starts with no hooks installed.

  2. What flag skips hooks on a commit or push?

    --no-verify.

  3. Name one thing a good PR description should include that "various fixes" doesn't.

    A concrete reason for the change and evidence it works, so a reviewer can evaluate it instead of rubber-stamping it.

Prove it

Add a pre-commit hook to a test repo that blocks any commit whose staged diff contains the word "TODO". Show one commit blocked, one commit that passes after removing the TODO, and one commit that bypasses the hook with --allow-empty --no-verify. Paste all three outcomes.