supraj.dev

Interview questions & answers

Git

Branching, merging, rebasing, and recovery.

  • 70 questions
  • 11 easy
  • 31 medium
  • 28 hard

70 questions

Question 1Hard

Explain git rebase -i (interactive rebase). Describe its primary use cases and walk through an example of squashing multiple commits into one, including the steps and commands involved.

#
Show answer

git rebase -i <base-commit-hash> (or <branch-name>) allows you to rewrite commit history interactively. The <base-commit-hash> specifies the point in history where you want to start rewriting. Primary use cases include: (1) **Squashing commits**: Combining multiple small, WIP commits into a single, meaningful commit. (2) **Reordering commits**: Changing the order of commits. (3) **Editing commit messages**: Rewriting a commit message. (4) **Splitting commits**: Breaking a large commit into smaller ones. (5) **Deleting commits**: Removing unwanted commits. When you run git rebase -i, Git opens an editor with a list of commits and commands (pick, squash, edit, reword, drop, fixup). To squash multiple commits: 1. Identify the commits you want to squash. Let's say you have commit-A, commit-B, commit-C, and you want to squash B and C into A. 2. Run git rebase -i <commit-parent-of-A>. This opens an editor with commit-A, commit-B, commit-C listed. 3. Change the actions: pick <hash-A> commit-A; squash <hash-B> commit-B; fixup <hash-C> commit-C. squash combines the commit into the previous one and prompts for a new commit message. fixup combines and discards the commit's message. 4. Save and close the editor. Git will then apply the changes. If you chose squash, a new editor will open to combine commit messages. If conflicts arise, resolve them, git add ., and git rebase --continue. The result is a cleaner, linear history with fewer, more atomic commits.

Question 2Medium

What are Git hooks, and how can they be used to enforce code quality or automate CI/CD tasks? Give examples of a pre-commit hook and a post-receive hook.

#
Show answer

Git hooks are scripts that Git executes automatically before or after events like committing, pushing, or receiving pushed commits. They are categorized as client-side (run on the developer's machine) or server-side (run on the remote repository). They reside in the .git/hooks directory of a repository. To activate, remove the .sample extension from the example files or create new scripts. For **enforcing code quality**, a pre-commit hook (client-side) can run linters, formatters, or unit tests before a commit is finalized. Example (.git/hooks/pre-commit): #!/bin/bash; echo 'Running linting...'; pylint --rcfile=.pylintrc *.py || { echo 'Pylint failed! Aborting commit.'; exit 1; }. This script runs Pylint and aborts the commit if it fails. For **automating CI/CD tasks**, a post-receive hook (server-side) can trigger deployments or notifications after new code is pushed to the central repository. Example (.git/hooks/post-receive): #!/bin/bash; while read oldrev newrev refname; do if [[ "$refname" == "refs/heads/main" ]]; then echo 'Main branch updated, triggering deploy...'; curl -X POST https://ci.example.com/trigger?branch=main; fi; done. This hook checks if the main branch was updated and then triggers a CI/CD pipeline via a webhook. Hooks are powerful but can be bypassed (client-side) or require careful management (server-side) to ensure consistency across teams.

Question 3Medium

How do you use git bisect to find the commit that introduced a bug? Walk through the steps, including how to handle non-binary outcomes (e.g., "skip").

#
Show answer

git bisect uses a binary search algorithm to efficiently find the commit that introduced a bug within a range of commits. Steps: 1. **Start bisecting**: git bisect start. 2. **Mark a known bad commit**: git bisect bad <commit-with-bug> (usually HEAD). 3. **Mark a known good commit**: git bisect good <commit-before-bug-existed>. Git will then check out a commit roughly in the middle of the good and bad range. 4. **Test the current commit**: Run your tests. If the bug is present, run git bisect bad. If the bug is not present, run git bisect good. Git will again check out a new commit, narrowing the search range. 5. **Handle non-binary outcomes**: If a commit cannot be tested (e.g., it doesn't build, or the bug's environment isn't reproducible), use git bisect skip. Git will then pick another commit, ignoring the skipped one. 6. **Repeat**: Continue testing and marking commits as good/bad/skip until Git identifies the exact "first bad commit." 7. **End bisecting**: git bisect reset to return to your original HEAD state. For automation, you can use git bisect run <script> where <script> returns 0 for good, 125 for skip, and 1-127 (except 125) for bad. This automates the testing and marking process.

Question 4Hard

Compare and contrast Git submodules and Git subtrees. When would you choose one over the other, and what are their respective challenges?

#
Show answer

Both Git submodules and subtrees allow embedding one Git repository inside another. **Git Submodules**: - **How it works**: Records a specific commit from an external repository. The submodule is effectively a separate repository at a fixed commit. - **Pros**: Clean separation of concerns; easy to track upstream changes by updating the submodule's recorded commit. - **Cons**: Can be complex to manage (requires explicit git submodule update), especially for new developers; repository cloning is a two-step process (git clone then git submodule update --init --recursive); can lead to a detached HEAD state in the submodule, making development within it tricky; upstream changes are pulled directly, not merged. - **Use cases**: Managing third-party libraries where you rarely contribute back, or when you need strict version control of dependencies. **Git Subtrees**: - **How it works**: Embeds the contents of an external repository directly into a subdirectory of your main repository. The external repo's history is merged into your main repo's history. - **Pros**: Simpler for new developers (no special clone/update steps); history of the subtree is part of the main repo's history; easier to make changes to the subtree and push them back upstream. - **Cons**: Larger repository size due to merged history; more complex to pull upstream changes (requires a merge operation); pushing changes back upstream requires a git subtree push command. - **Use cases**: Monorepos, when you frequently modify the shared component and push changes back, or when you want the embedded project's history to be part of your main project's history. **Choice**: Choose **submodules** for external dependencies you consume but rarely modify, or when you need strict, explicit version pinning. Choose **subtrees** for shared components you actively develop and contribute to, or when you want a simpler developer experience without the complexities of submodule management.

Question 5Hard

Beyond simple git reset, how can git reflog be used to recover seemingly "lost" commits, branches, or even entire repositories? Provide a scenario where git reflog is the only way to recover.

#
Show answer

git reflog (reference log) is a powerful mechanism that records every time your HEAD (the pointer to your current commit) changes. This includes commits, resets, merges, rebases, checkouts, and even failed operations. Unlike git log, which shows only reachable commits, reflog tracks all local movements, making it the ultimate safety net for recovering "lost" work. Each entry in the reflog has an index (e.g., HEAD@{0}, HEAD@{1}) and the commit hash. **Scenario for recovery**: Imagine you're on main, create a new branch feature-A, make some commits, then accidentally delete the branch with git branch -D feature-A. You also ran git reset --hard HEAD~2 on main to remove some recent commits, thinking they were bad, and now you realize you need them back. At this point, git log won't show the deleted branch's commits or the reset commits. **Recovery steps**: 1. **View the reflog**: git reflog. This will show a history of your HEAD movements. You'll see entries like HEAD@{5}: reset: moving to HEAD~2 and HEAD@{10}: checkout: moving from feature-A to main. 2. **Identify the lost commit**: Look for the commit hash where your feature-A branch last pointed, or the commit hash of the work you reset --hard. For example, let's say HEAD@{10} was c1a2b3c (the last commit on feature-A) and HEAD@{5} was d4e5f6g (the commit before your reset --hard on main). 3. **Restore the branch/commits**: - To restore feature-A: git checkout -b feature-A c1a2b3c. - To restore main to its state before the reset --hard: git reset --hard d4e5f6g. reflog entries are typically retained for 90 days by default, after which they are garbage collected. It's crucial to understand that reflog is local to your repository; it does not exist on remote servers.

Question 6Easy

What is the difference between git merge and git rebase?

#
Show answer

merge creates a new merge commit that joins two histories, preserving exactly what happened (non-linear history). rebase replays your commits on top of another branch, producing a linear history but rewriting commit hashes. Use merge for shared/public branches; rebase to tidy up local work before pushing. Golden rule: never rebase commits you've already pushed and others have based work on.

Question 7Easy

What is the difference between git fetch and git pull?

#
Show answer

fetch downloads new commits/refs from the remote but doesn't change your working branch — you can inspect before integrating. pull is fetch + merge (or fetch + rebase with --rebase) into your current branch in one step. Fetch-then-review is safer when you want to see what changed first.

Question 8Medium

How do you undo a commit that has already been pushed?

#
Show answer

Use git revert <commit> — it creates a new commit that undoes the changes, keeping history intact and safe for shared branches. Avoid git reset + force-push on shared branches because it rewrites history others may have pulled. Reset/force is fine only on a private branch nobody else uses.

Question 9Medium

What does git cherry-pick do and when would you use it?

#
Show answer

cherry-pick applies the changes from a specific commit onto your current branch as a new commit. Useful for back-porting a single bug fix to a release branch, or pulling one commit out of a feature branch without merging the whole thing. Be mindful it duplicates the change, which can cause conflicts if that commit later gets merged too.

Question 10Hard

You committed to the wrong branch. How do you move the commits?

#
Show answer

If unpushed: note the commits, switch to the correct branch (or create it), and either cherry-pick them over, or use git rebase --onto. Then on the wrong branch, git reset --hard origin/... (or to the commit before yours) to drop them. git reflog is your safety net to recover any commit you accidentally lose during the move.

Question 11Medium

You accidentally committed a 500MB binary file three commits ago, then deleted it in the latest commit. The file is still in your repository history, bloating the clone size. How do you completely remove it from Git history on all branches without losing other commits?

#
Show answer

Use git filter-branch or (preferred) git filter-repo (faster, maintained by Git community). With git-filter-repo: git filter-repo --path path/to/bigfile.bin --invert-paths. This rewrites history, removing the file from every commit. The file is gone from the entire history. Impact: (1) All commit hashes change (history rewrite). (2) Every collaborator must rebase their branches: git rebase --onto new-main old-main their-branch. (3) Force-push is required: git push origin --force-with-lease. (4) Notify all team members to re-clone or rebase. (5) After the rewrite, run git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(rest)' | awk '/^blob/ {print $NF}' | sort | uniq -c | sort -rn | head -20 to verify no large objects remain. (6) Run git gc --prune=now to clean up unreachable objects. Alternative: BFG Repo-Cleaner (bfg --delete-files bigfile.bin). For binary files in general, use git lfs to store them outside the repository proper.

Question 12Hard

During a complex merge conflict across 50 files involving 10 developers, describe your resolution strategy, communication plan, and verification process.

#
Show answer

Strategy: (1) First, establish the merge base: git merge-base main feature-branch and review both sides of the diff: git log --oneline --left-right main...feature-branch. (2) Use a merge tool (vimdiff, Beyond Compare, git mergetool) for visual three-way merging. (3) Organize files by conflict type: auto-mergeable (deleted files, whitespace-only), simple conflicts (one side changed, one didn't), complex conflicts (both sides changed same region). Resolve simple conflicts first. (4) Communication: create a Slack/Discord channel, post the commit range, assign owners for each file domain (e.g., backend devs own API files, frontend devs own UI files). Use git checkout --ours/--theirs initially to create a working tree, then manually fix each conflicted area. (5) Verification: git diff --check for whitespace, git log --oneline --graph --left-right main...HEAD to see what's on each side. Run CI: tests, lint, build. (6) If merge is too complex, consider a "merge commit" strategy: merge main into the feature branch first (solving conflicts in private), then merge feature into main with --no-ff. (7) Post-merge: force-push the result to a review branch, have each domain owner verify their files, then finalize. Git's ort merge strategy (default since 2.33) handles renames and directory/file conflicts better than the old recursive strategy.

Question 13Hard

Explain Git's merge strategies: ort (default since 2.33), recursive, resolve, octopus, and ours. When would you explicitly choose recursive -X theirs vs -X ours, and what are the risks?

#
Show answer

ort (Ostensibly Rec's Twin): new default, written in C for performance, handles renames+tweaks correctly, no index conflicts with git log. recursive: old default (Python-based via Git v2.33+ fallback), uses a recursive algorithm for criss-cross merge histories. resolve: simple 3-way merge, fast but cannot handle multiple merge bases — rare. octopus: merges more than 2 heads at once — used for topic branch merges but fails on conflicts. ours: keeps current branch content entirely, records merge but ignores incoming changes — used to mark a merge without actually taking changes (e.g., after reverting a feature). -X theirs auto-resolves conflicts by taking the incoming branch's version of conflicting hunks — useful for automated merges where you trust the incoming branch (e.g., cherry-pick backport). -X ours takes current branch's version. Risks: both -X theirs and -X ours silently discard the other side's changes in conflicted regions. This can introduce subtle bugs if a conflict represents a non-trivial integration point. Only use them when: (1) merging a hotfix back into main with known-safe conflicts (e.g., version number bumps); (2) during git rebase where you know your changes are correct and upstream conflicts are noise. Never use them without code review of the resulting diff.

Question 14Easy

How do you initialize a new Git repository and connect it to a remote?

#
Show answer

git init creates a new local repo. git remote add origin <url> links it to a remote. git push -u origin main sets the upstream and pushes. Most projects start with git clone <url> which does all three in one step.

Question 15Easy

What does git status show that git log does not?

#
Show answer

git status shows the working tree and index state: tracked/untracked files, staged changes, merge conflicts. git log shows commit history. They complement each other — use status to see what is about to be committed and log to see what was committed.

Question 16Easy

What is the difference between git add ., git add -A, and git add -p?

#
Show answer

git add . stages new and modified files in the current directory and below. git add -A stages all changes across the entire repo, including deleted files. git add -p (patch mode) interactively lets you stage individual hunks within a file.

Question 17Easy

What is a gitignore file and why is it important?

#
Show answer

A .gitignore file tells Git which files or patterns to ignore (not track). Common entries: build outputs (dist/, node_modules/), environment files (.env), OS files (.DS_Store), IDE configs (.idea/, .vscode/). Without it, generated files and secrets may accidentally be committed.

Question 18Easy

How do you create and switch to a new branch in one command?

#
Show answer

git checkout -b <branch-name> (classic) or git switch -c <branch-name> (modern, since Git 2.23). Both create the branch and switch to it immediately.

Question 19Medium

What is a detached HEAD state and how do you recover?

#
Show answer

Detached HEAD means you're checked out at a specific commit rather than a branch ref — any new commits won't be reachable from a branch. Recover by creating a branch at the current commit: git checkout -b new-branch-name. Common causes: git checkout <hash>, git checkout origin/main, or git rebase conflicts.

Question 20Medium

How do you amend the most recent commit to fix a typo in the message or add a missing file?

#
Show answer

For a message: git commit --amend -m "Fixed message". For a missing file: git add missing-file && git commit --amend --no-edit. Do NOT amend commits that have already been pushed to a shared branch — it rewrites history.

Question 21Medium

What is a tracking branch and how do you set it up?

#
Show answer

A tracking branch links a local branch to a remote branch so git push/git pull know where to sync without specifying the remote. Set it during push: git push -u origin <branch>. After that, plain git push and git pull work. git branch -vv shows tracking relationships.

Question 22Medium

How does git stash work and when would you use it?

#
Show answer

git stash temporarily shelves uncommitted changes, leaving a clean working tree. Useful when you need to switch branches mid-task. git stash pop restores the latest stash and removes it; git stash apply restores without removing. git stash list shows all stashes. git stash push -m "message" names them.

Question 23Medium

How do you revert a merge commit that has already been pushed?

#
Show answer

git revert -m 1 <merge-commit> tells Git which parent to keep (mainline) and creates a new commit undoing the merge. Unlike git reset, revert is safe on shared branches because it doesn't rewrite history. If you later need to re-merge, revert the revert commit.

Question 24Medium

What is the difference between a fast-forward merge and a three-way merge?

#
Show answer

Fast-forward: if the target branch hasn't diverged, Git simply moves the branch pointer forward — no merge commit. Three-way merge: when branches have diverged, Git creates a merge commit joining both histories. Use --no-ff to force a merge commit (useful for feature branches to preserve history).

Question 25Medium

How do you rename a branch locally and on the remote?

#
Show answer

Locally: git branch -m <old-name> <new-name>. Remote: push the new name and delete the old: git push origin -u <new-name> && git push origin --delete <old-name>. Update local clones of other developers: they fetch with git fetch --prune and switch to the new branch.

Question 26Medium

How do you find which commit introduced a bug using git blame?

#
Show answer

git blame <file> shows each line annotated with the commit hash, author, and timestamp of the last modification. Useful for finding 'who changed this line and when'. Combine with git log -p <commit> to see the full diff. git blame -L 10,20 <file> limits to a specific line range.

Question 27Medium

How do you compare changes between two branches or commits?

#
Show answer

git diff branch-a..branch-b shows changes on branch-b relative to branch-a. git log --oneline --left-right branch-a...branch-b shows which commits are unique to each side. git diff --stat summarizes file-level changes. For compare against the merge base: git diff branch-a...branch-b.

Question 28Medium

What is git clean and when would you use it?

#
Show answer

git clean removes untracked files from the working tree. git clean -n dry-runs (shows what would be deleted). git clean -f forces deletion of files. git clean -fd also removes untracked directories. git clean -fx removes files matched by .gitignore as well. Always dry-run first to avoid accidental loss.

Question 29Medium

How do you apply the same commit to multiple branches?

#
Show answer

Use git cherry-pick <commit-hash> — it applies the diff of a specific commit onto the current branch as a new commit. Common uses: backporting a bug fix to a release branch, or picking a single change from a feature branch without merging the whole thing. Watch for duplicate conflicts if the same commit is later merged.

Question 30Hard

How does Git's internal object model work (blobs, trees, commits, tags)?

#
Show answer

Git is fundamentally a content-addressable filesystem. Four object types: (1) Blob — stores file content, identified by SHA-1 of its content. (2) Tree — maps filenames to blobs (or nested trees), like a directory listing. (3) Commit — points to a tree, has parent references, author, committer, and message. (4) Tag — points to a commit (lightweight) or to an object with metadata (annotated). All objects are stored in .git/objects/ as compressed files keyed by hash. git cat-file -p <hash> inspects any object.

Question 31Hard

How does Git handle large files and what is Git LFS?

#
Show answer

Git stores every version of every file in the object store, which balloons with large binaries. Git LFS (Large File Storage) replaces large files with text pointers in Git and stores the actual content on a remote server (GitHub, GitLab). Files matching patterns in .gitattributes are auto-tracked by LFS. Benefits: clone times stay fast, diffs don't load the binary, storage is offloaded to the LFS server. LFS does have bandwidth quotas on most hosting platforms.

Question 32Hard

How do you completely remove a large file from Git history using git filter-repo?

#
Show answer

git filter-repo --path large-file.bin --invert-paths rewrites every commit, stripping the file from all history. This changes every commit hash — a force-push is required. Afterward: git reflog expire --expire=now --all && git gc --prune=now --aggressive to reclaim storage. All collaborators must rebase onto the new history. For multiple repos, use --refs to target specific branches. git filter-repo is the maintained successor to git filter-branch, written in Python and much faster.

Question 33Hard

How does git bisect run automate binary search?

#
Show answer

git bisect run <script> automatically executes the script at each bisect step. The script should exit 0 (good), 125 (skip — commit cannot be tested), or 1-127 (bad, except 125). Example: git bisect start HEAD v1.0 && git bisect run make test finds which commit broke the build. For flaky tests, return 125 to skip. The output shows the first bad commit hash and message.

Question 34Hard

What is a shallow clone and when would you use it in CI?

#
Show answer

A shallow clone (git clone --depth 1) fetches only the latest commit without history. In CI it dramatically reduces clone time on large repos. Tradeoffs: you cannot git blame, git bisect, or git log beyond the depth. Use --depth N for the last N commits, --shallow-since=<date> for commits since a date, or --single-branch to limit to one branch. For monorepos, combine shallow clone with --sparse for checkout of specific directories only.

Question 35Hard

Explain Git's refspec format and how it controls push/fetch behavior.

#
Show answer

A refspec maps remote refs to local refs in the format [+]<src>:<dst>. The optional + enables force-update. Default fetch refspec: +refs/heads/*:refs/remotes/origin/*. Default push: refs/heads/<branch>:refs/heads/<branch>. Custom refspecs let you fetch only specific branches (fetch = +refs/heads/main:refs/remotes/origin/main), push to a different remote branch name, or fetch pull requests (+refs/pull/*/head:refs/remotes/origin/pr/*).

Question 36Hard

How do you recover from a failed interactive rebase?

#
Show answer

If you encounter conflicts during git rebase -i and panic: (1) git rebase --abort returns to the state before rebase started. (2) If you made partial progress and want to continue after fixing conflicts: git add . && git rebase --continue. (3) If you've already committed bad changes: use git reflog to find the commit before rebase started and git reset --hard HEAD@{N}. The reflog always has your back during rebase operations.

Question 37Hard

What is git worktree and how is it useful for multitasking?

#
Show answer

git worktree add ../path branch-name checks out a branch in a separate directory while keeping your current worktree untouched. Benefits: (1) Work on two branches simultaneously without stashing or cloning twice. (2) Run tests on one branch while coding on another. (3) Review a PR in a dedicated directory. git worktree list shows all worktrees. git worktree prune cleans up after deleting a worktree's directory.

Question 38Hard

How does Git's commit-graph feature improve performance?

#
Show answer

The commit-graph (git commit-graph write) stores commit metadata (parents, tree, generation number) in a binary file under .git/objects/info/commit-graph. This accelerates git log --graph, git merge-base, git rev-list, and reachability queries by avoiding decompression and parsing of individual commit objects. In large repos, operations can be 5-10x faster. Generation numbers enable topological ordering without walking the entire DAG. Git 2.18+ automatically writes commit-graphs during git gc.

Question 39Hard

How do you sign commits and tags with GPG/SSH, and why is this important in CI/CD?

#
Show answer

Commits: git commit -S -m "message". Tags: git tag -s v1.0 -m "v1.0". Configure Git with user.signingkey and set git config commit.gpgsign true to sign automatically. CI/CD importance: verify signed commits on protected branches (git verify-commit HEAD), gate merges on signature verification, and prove provenance in supply chain security. GitHub displays a Verified badge for signed commits. SSH signing (Git 2.34+) is simpler than GPG for most teams.

Question 40Hard

How do you use git archive to export a clean copy of a repository?

#
Show answer

git archive --format=zip --output=project.zip HEAD creates a ZIP or tar of the repository at the specified commit, without .git directory or untracked files. This is the correct way to distribute source code releases. git archive --format=tar --prefix=myproject/ v1.0 | gzip > myproject-v1.0.tar.gz creates a standard tarball. You can also archive a subdirectory: git archive HEAD:src/.

Question 41Hard

What is the difference between git log --all, git log --branches, and git log --remotes?

#
Show answer

git log --all shows commits reachable from any ref (branches, tags, remotes). git log --branches shows only local branches. git log --remotes shows only remote-tracking branches. Use --graph --oneline --decorate with any to visualize the full commit topology. git log --branches --not --remotes finds commits on local branches not yet pushed.

Question 42Hard

How does Git's sparse checkout work and when would you use it in a monorepo?

#
Show answer

Sparse checkout lets you check out only a subset of directories from a repository. Enable with git sparse-checkout init --cone, set patterns with git sparse-checkout set dir1/ dir2/, then clone with --sparse. In a monorepo with hundreds of projects, each CI pipeline only needs its own sources — sparse checkout reduces checkout time and disk usage. The cone mode (--cone) is much faster than the older non-cone mode.

Question 43Hard

What is the difference between git push --force and git push --force-with-lease?

#
Show answer

--force blindly overwrites the remote ref, potentially destroying commits others have pushed. --force-with-lease checks that the remote ref is at the commit you expect before pushing — it protects against overwriting someone else's work. Always prefer --force-with-lease (or --force-if-includes) over --force. These are a safety net for force-push scenarios like rebased feature branches.

Question 44Medium

How do you find commits that modified a specific line in a file?

#
Show answer

git log -L <start>,<end>:<file> follows line history across renames. git blame <file> | grep <pattern> shows who last changed each matching line. git log -S <string> -- <file> (pickaxe) finds commits that added or removed a specific string. git log -G <regex> does the same with regex matching. These are essential for forensic debugging.

Question 45Medium

What is the difference between HEAD^, HEAD~, HEAD~2, and HEAD@{2}?

#
Show answer

HEAD^ = first parent of HEAD (same as HEAD~). HEAD~2 = grandparent (two commits back following first-parent). HEAD^2 = second parent of a merge commit. HEAD@{2} = where HEAD was 2 moves ago (from reflog — time-based, not ancestry-based). ~ traverses first-parent ancestry; ^ selects specific parent in merges.

Question 46Medium

How do you set up a Git pre-commit hook to run linters automatically?

#
Show answer

Create .git/hooks/pre-commit (executable). Example: #!/bin/sh; npm run lint || exit 1. To share hooks with the team, use pre-commit framework with .pre-commit-config.yaml or store scripts in .githooks/ and run git config core.hooksPath .githooks. The hook runs before each commit — if it exits non-zero, the commit is blocked.

Question 47Hard

How does Git's rerere (reuse recorded resolution) work?

#
Show answer

git config rerere.enabled true records how you resolve merge conflicts and automatically reuses the same resolution the next time Git encounters the same conflict. The recorded resolutions are stored in .git/rr-cache/. Useful for long-lived feature branches that are repeatedly rebased onto main — the same conflicts appear each time, and rerere resolves them automatically. git rerere gc prunes stale cache entries. git rerere forget <path> clears a specific recorded resolution.

Question 48Hard

How do you use git replace to replace one commit with another?

#
Show answer

git replace <object> <replacement> creates a ref in refs/replace/ that tells Git to substitute one object for another during operations like git log or git blame. Use cases: (1) replacing a commit message; (2) fixing a bad commit without rebasing; (3) grafting history (connecting two disjoint histories). The replacement is local — share with git push origin refs/replace/*. --graft creates a graft replacement to change parent pointers. git replace -l lists active replacements.

Question 49Hard

What is git fsck and how do you recover from a corrupted repository?

#
Show answer

git fsck checks the object database for integrity and finds dangling objects (unreachable blobs/commits). Recovery: (1) git fsck --full identifies missing or corrupted objects. (2) If a commit is dangling, git cherry-pick <hash> or git branch recover <hash> saves it. (3) For missing objects, try git fetch --refetch or re-clone from a remote. (4) For packfile corruption, git unpack-objects < .git/objects/pack/*.pack then git gc to rebuild. (5) Worst case: reclone and cherry-pick any unpushed commits found in git fsck --lost-found.

Question 50HardSecurity

An access key was committed and pushed six commits ago. What is the right order of actions?

#

The repository is private, but it has forks and open pull requests.

Show answer

First revoke and rotate the key, and check its usage logs for abuse; once pushed, assume it is compromised. That step protects you even if the history cleanup is imperfect.

Then remove it from history with a tool like git filter-repo, which Git's own documentation recommends over filter-branch. Force-push, ask collaborators to re-clone, and remember forks, cached views and pull request refs may keep the old commits, so follow the hosting provider's guidance for those. Finally, turn on secret scanning with push protection so the next leak is blocked before it lands.

Trade-offs

Rewriting history disrupts everyone with a clone; for a key that is already revoked, some teams accept leaving it in history.

Common mistake

Adding a commit that deletes the key and calling it fixed.

Follow-up

How would you find every other secret already in the repository's history?

Question 51MediumSecurity

How do you sign commits, and what does a "Verified" badge actually prove?

#

A compliance review asks you to prove who authored changes to the deployment repository.

Show answer

Commit author name and email are just text, so anyone can claim to be anyone. Signing attaches a cryptographic signature; Git supports GPG, and since 2.34 also SSH keys, which most engineers already have: set gpg.format ssh, point user.signingkey at the key and enable commit.gpgsign.

GitHub shows "Verified" when the signature matches a signing key registered to that account. It proves the commit was made with that key, not that the code is safe or reviewed. Require signed commits on protected branches, protect keys (hardware-backed if possible), and keep review rules too.

Trade-offs

Mandatory signing adds setup friction for every developer and bot, so automate key distribution.

Common mistake

Treating "Verified" as proof that a change was reviewed.

Follow-up

How would you handle signing for commits made by CI bots?

Question 52MediumWorkflow

Two pull requests pass CI separately but break main together. How do you prevent that?

#

One PR renames a function; another, tested against an older main, adds a new call to the old name.

Show answer

Each PR was tested against the main branch as it was when CI ran, not against main plus the other PR. A merge queue fixes that: instead of merging directly, PRs join a queue, and CI tests each one combined with the latest main and the PRs ahead of it. Only combinations that pass are merged; a failing PR is removed from the queue.

On GitHub, required workflows must also run on the merge_group event or the queue waits forever. Keep queue CI fast, since it is on the critical path.

Trade-offs

A queue keeps main green but adds waiting time; batching several PRs per run helps when CI is slow.

Common mistake

Requiring PRs to be up to date with main and making everyone rebase repeatedly instead.

Follow-up

How would you handle a flaky test that keeps knocking PRs out of the queue?

Question 53EasyHistory

After a repository-wide reformat, git blame shows one commit for every line. How do you fix that?

#

A formatter commit touched 3,000 files. Blame now points to it everywhere.

Show answer

List the formatting commit's full hash in a file, conventionally .git-blame-ignore-revs, and commit it. Run git config blame.ignoreRevsFile .git-blame-ignore-revs (or pass --ignore-revs-file) and blame will attribute those lines to the commit before the reformat. GitHub's blame view reads that file automatically when it sits at the repository root.

Keep pure formatting changes in their own commits, separate from logic changes, so they can be ignored cleanly.

Trade-offs

Ignoring a commit hides it from blame, so do it only for mechanical changes.

Common mistake

Mixing formatting and behaviour changes in one commit, so it can no longer be ignored safely.

Follow-up

How would you roll out a new formatter across many repositories with minimal disruption?

Question 54HardPerformance

Cloning your monorepo takes 20 minutes in CI and on new laptops. Someone proposes --depth 1 everywhere. When is a shallow clone right, and when is a partial clone better?

#

The repository has ten years of history and many large generated files in old commits. CI jobs build one commit; some jobs run git describe or diff against main; developers need full history for blame and bisect.

Show answer

A shallow clone (--depth) truncates history to the given number of commits, and it implies --single-branch unless you say otherwise. It is fast and fine for a job that only builds one commit. It breaks anything that needs history: git describe cannot reach older tags, merge-base against main may not exist, and change detection based on diffs to main fails or silently compares against the wrong thing.

A partial clone (--filter) keeps the full commit history but asks the server to leave out some objects until they are needed. --filter=blob:none omits all file contents, which are then fetched on demand; --filter=blob:limit=1m omits only large blobs; --filter=tree:0 omits trees too. The remote that will supply missing objects later is called a promisor remote.

The trade-off is on-demand fetching. You must stay online, and Git's docs warn that dynamic fetches tend to be slow because objects are fetched one at a time, with possible repeated authentication, when an operation touches many missing objects. Checkout batches its prefetch, but a full git log -p or blame over a big history pulls a lot. The server must also support the filter capability.

Recommendation: blobless partial clones for developers and for CI jobs that need history (versioning, diffs against main); shallow clones only for jobs that build a single commit and never look back; and fetch tags or deepen explicitly when a job needs them.

Trade-offs

Shallow clones are the smallest and fastest but lose history; blobless clones keep history and stay fast to clone, but later operations can trigger many small fetches.

Common mistake

Using --depth 1 in a CI job that computes versions or changed files from history, and getting silently wrong results.

Follow-up

How would you also use sparse checkout to limit the working tree for one team in the same monorepo?

Full history, contents on demand · shell
git clone --filter=blob:none https://git.example.com/platform/monorepo.git
# CI job that builds one commit and nothing else
git clone --depth 1 --branch main https://git.example.com/platform/monorepo.git
Question 55MediumPerformance

In a very large repository, git status and git fetch are slow for every developer, and a foreground git gc occasionally freezes someone's terminal for minutes. What would you roll out?

#

Hundreds of engineers, one large repo, laptops on macOS and Linux. Nobody has configured anything beyond defaults.

Show answer

Two built-in tools address this. git maintenance start registers the repository and schedules background maintenance through the platform scheduler: cron on POSIX, user systemd timers on Linux when available, launchd on macOS and scheduled tasks on Windows. With the default incremental strategy it runs prefetch and commit-graph hourly, loose-objects and incremental-repack daily, pack-refs weekly, and leaves full gc disabled. It also turns off automatic foreground maintenance in that repo, so nobody's command stops for a repack. The prefetch task downloads new objects into refs/prefetch/ without moving your remote-tracking branches, so a later real fetch has little left to transfer.

scalar goes further for very large repositories. scalar clone clones only commit and tree objects by default (contents arrive on demand), enables sparse checkout with only top-level files, configures background maintenance, and sets options such as changed-path Bloom filters in the commit-graph and gc.auto=0. scalar register applies its settings to an existing clone.

Roll it out with the onboarding script rather than a wiki page, measure git status and fetch times before and after, and explain sparse checkout to teams, because files outside their cone not appearing is the main support question you will get.

Trade-offs

Background maintenance and Scalar make large repos fast, but they add scheduler entries on every laptop and, with Scalar, a sparse and partial clone that engineers must understand.

Common mistake

Setting gc.auto=0 to stop the freezes without scheduling any other maintenance, so the repository slowly degrades.

Follow-up

How would you measure whether commit-graph and Bloom filters actually sped up history queries such as git log -- path?

Background maintenance for an existing clone, or a Scalar enlistment · shell
git maintenance start
# or, for a new large-repo enlistment
scalar clone https://git.example.com/platform/monorepo.git
Question 56MediumSecurity

A CI job that runs Git inside a container started failing with "detected dubious ownership in repository". A teammate wants to add safe.directory = * to the repository's .git/config. Why will that not work, and what is the right fix?

#

The runner checks out code as one user, then a build container runs as root (or a different UID) on the mounted workspace and calls git describe.

Show answer

By default Git only works with repositories owned by the user running it. For a repository owned by someone else, it refuses even to parse the repository's config, let alone run its hooks. That protects you from a repository planted by another user whose config or hooks would run commands as you. In the container, Git runs as a different UID from the one that owns the checkout, so it stops.

safe.directory lists exceptions, but it is only honoured in protected configuration: system, global or command-line scope. A setting inside the repository's own config is ignored, because an untrusted repository must not be able to mark itself safe. So the teammate's change does nothing.

Best fix: run the container with the same UID as the workspace owner, so no exception is needed. If that is not possible, add a narrow exception in the container's global config for the exact workspace path, for example git config --global --add safe.directory /workspace/repo, or pass -c safe.directory=/workspace/repo on the command. Avoid *, which disables the check for every repository on that machine, and be especially careful on shared runners where other jobs' checkouts could be present. As a related note, under sudo Git also trusts the UID in SUDO_UID so make && sudo make install keeps working.

Trade-offs

Matching UIDs is the cleanest fix but needs control of the container image; a path-specific exception is quick but must be kept narrow.

Common mistake

Setting safe.directory to * on a shared CI runner.

Follow-up

What changes in Git 3.0 for bare repositories that Git discovers implicitly, and why?

Narrow exception in the container, not in the repo · shell
git config --global --add safe.directory /workspace/repo
git -C /workspace/repo describe --tags
Question 57HardCollaboration

You always push rebased branches with --force-with-lease, yet you still overwrote a colleague's commit on a shared branch. How did the lease fail, and how do you make it safe?

#

Your IDE runs git fetch in the background every few minutes. A colleague pushed a fix to the branch while you were rebasing.

Show answer

--force-with-lease without an explicit expected value requires the remote ref to equal your remote-tracking branch, on the assumption that the tracking branch shows what you have seen. A background fetch breaks that assumption: the IDE updated origin/feature to include your colleague's commit, so the lease matched, and your push replaced their work with your rebased history, which never contained it. Git's documentation warns about exactly this: the lease without an expected value interacts very badly with anything that fetches in the background.

Three fixes, best first. Add --force-if-includes alongside --force-with-lease: it checks that the tip of the remote-tracking ref is reachable from your local branch's reflog, meaning you actually integrated it, and rejects the push otherwise. Or give the lease an explicit expected value, --force-with-lease=feature:<sha-you-rebased-on>. Or, as the docs suggest, push through a separate remote that background jobs do not fetch.

Set push.useForceIfIncludes=true so it happens by default. And question the workflow: if several people push to one branch, prefer merging or stacking over rewriting shared history.

Trade-offs

force-if-includes keeps rebased workflows convenient and safe; explicit expected values are bulletproof but tedious to type.

Common mistake

Treating --force-with-lease as safe in any environment, including editors that fetch in the background.

Follow-up

How would you protect shared branches on the server side so this cannot happen at all?

Lease plus proof that you integrated the remote tip · shell
git config --global push.useForceIfIncludes true
git push --force-with-lease --force-if-includes origin feature
Question 58HardHistory

You have three stacked branches. The bottom PR was squash-merged into main, and now rebasing the next branch onto main produces conflicts on changes that are already in main. How do you move the stack cleanly?

#

Branches: auth-model -> auth-api -> auth-ui, each based on the previous one. auth-model was squash-merged as one new commit on main.

Show answer

A squash merge creates one new commit on main with different identity from your original commits. When you rebase auth-api onto main, Git replays every commit not in main, including the original auth-model commits, so they clash with their own squashed copy.

Tell Git exactly which commits to move with --onto: git rebase --onto main auth-model auth-api takes the commits in auth-api that are not in auth-model and replays only those onto main. That is the documented transplant pattern for a topic branch that was based on another branch.

For the rest of the stack, use --update-refs. When you rebase the top branch, it force-updates any other branches that point to commits being rebased, so the middle branches move with the top one in a single rebase. Set rebase.updateRefs=true to make it the default. Branches checked out in another worktree are not updated this way.

So: rebase the top of the stack with --onto main auth-model --update-refs, check the result with git range-diff, then force-push each updated branch with a lease. Teams that stack a lot often prefer merge commits or rebase-merge for stacked PRs to avoid this entirely.

Trade-offs

Squash merges keep main tidy but make stacked branches harder to maintain; merge or rebase-merge strategies keep commit identity and avoid the problem.

Common mistake

Resolving the duplicate conflicts by hand, commit by commit, and risking reintroducing code that changed in main.

Follow-up

How does git rebase --fork-point try to handle upstream branches that were rewritten?

Drop the squashed base, move the whole stack in one rebase · shell
git fetch origin
git rebase --onto origin/main auth-model auth-ui --update-refs
git push --force-with-lease --force-if-includes origin auth-api auth-ui
Question 59MediumWorkflow

Reviewers on your team want each review fix visible, but main should get a clean series of commits. How do you get both without rewriting messages by hand?

#

A pull request has five logical commits. Review produced eight small fixes, each belonging to one of the five.

Show answer

Commit each review fix with git commit --fixup=<commit>. That creates a commit whose message starts with fixup! followed by the target's title. Reviewers see each fix as its own small commit and can review just that change.

When the review is done, run git rebase -i --autosquash main. Autosquash moves every squash! , fixup! or amend! commit right after the commit it targets and changes its action: fixup commits fold in silently, squash commits combine messages, and amend commits replace the message. You can still review the todo list before it runs. Set rebase.autoSquash=true to make it the default in interactive rebases.

After the rebase, show reviewers what changed with git range-diff, so the force-push is easy to trust, and push with a lease.

The trade-off is policy, not tooling: if the team squash-merges every PR anyway, this precision is wasted. It pays off when you merge with rebase or merge commits and want each commit on main to build and make sense on its own, for example to keep git bisect useful.

Trade-offs

Fixup commits keep review incremental and history clean, but require rebasing published branches, which needs care on shared branches.

Common mistake

Squashing everything into one commit at the end and losing the logical structure reviewers approved.

Follow-up

When would you choose amend! over fixup!?

Record fixes now, fold them in at the end · shell
git commit --fixup=3f2a9c1
git rebase -i --autosquash origin/main
git range-diff origin/main @{u} HEAD
Question 60MediumWorkflow

An author force-pushed a rebased 12-commit pull request after resolving conflicts. How do you review only what actually changed since your last review?

#

The full diff against main is 3,000 lines and almost identical to what you already approved. The commits were reordered slightly and two were edited.

Show answer

git range-diff shows the differences between two versions of a patch series. It pairs up commits between the old and new range and shows, per commit, how the patch itself changed, ignoring merge commits. Reordered commits are matched, untouched commits show as equal, and edited ones show a diff of the diff.

You can give the ranges three ways: two ranges (base..old base..new), the symmetric form old...new, or <base> <old> <new>. For a reviewer, the old tip is the commit you last reviewed (from the PR's previous head, or your own remote-tracking reflog). For an author, Git's docs give the idiom right after a rebase with conflict resolution: git range-diff @{u} @{1} @ compares the upstream, the branch's previous position from the reflog, and the current tip.

This turns a frightening force-push into a short review. Ask authors to post the range-diff output in the PR after every rebase, and many forges show something similar between pushes. If range-diff shows unexpected changes in commits that supposedly only moved, that is exactly where conflict resolutions went wrong.

Trade-offs

Range-diff makes rebase-heavy workflows reviewable, but its output takes some practice to read.

Common mistake

Re-reviewing the whole diff against main, or worse, rubber-stamping it because it is too large.

Follow-up

How would you find the previous head of a PR branch if you never fetched it locally?

Compare the old and new versions of the series · shell
git range-diff origin/main 4b1e0d2 origin/feature
# author, right after a conflicted rebase
git range-diff @{u} @{1} @
Question 61MediumHistory

A feature flag check disappeared from the codebase months ago and nobody knows when. git blame cannot help because the line no longer exists. How do you find the commit?

#

The removed code contained the string isEnabled("new-checkout"). The file has been moved once since.

Show answer

Use the pickaxe options of git log. -S<string> finds commits that change the number of occurrences of that string in a file, meaning it was added or removed. git log -S'isEnabled("new-checkout")' --oneline lists the commit that introduced it and the one that removed it. Add -p to see the patch and --all to search every branch.

-G<regex> is different: it finds commits whose patch text contains added or removed lines matching the regex. The docs' example shows the distinction. If a commit rewrites a line but keeps the same string in it, -G shows that commit and -S does not, because the number of occurrences did not change. Use -S to find when something appeared or vanished, and -G to find every commit that touched lines mentioning it.

By default the pickaxe output only shows the files containing the change; --pickaxe-all shows the whole changeset, useful to see what else was removed along with the flag. -S also searches binary files, while -G ignores binary patches without a textconv filter. For a file that moved, add --follow with a single path to keep history across the rename.

Trade-offs

-S is precise for additions and removals; -G is broader and noisier but finds every edit to matching lines.

Common mistake

Grepping the current tree or blaming the file, which cannot see code that no longer exists.

Follow-up

How would you trace the full history of one function, including edits, with git log -L?

When did this string appear or disappear? · shell
git log -S'isEnabled("new-checkout")' --oneline --all
git log -G 'new-checkout' --oneline -p -- src/checkout/
Question 62MediumDebugging

You are bisecting a regression on a main branch that uses merge commits, and bisect keeps landing on half-finished commits inside feature branches that do not even build. How do you get a useful answer?

#

Feature branches contain many work-in-progress commits; only the merge commits on main were ever tested by CI.

Show answer

Start bisect with --first-parent. Bisect then follows only the first parent of each merge commit, so it walks the history of main itself. If a regression came in through a merged branch, the merge commit is reported as the cause and the branch's internal commits are ignored. Git's docs describe this as useful exactly when a merged branch contained broken or non-buildable commits but the merge itself was fine.

That gives you the PR that introduced the problem. If you need the exact commit, bisect a second time inside that branch's range, where the commits are at least related.

Automate the test with git bisect run. Make the script exit 0 for good, a non-zero code other than 125 for bad, and 125 when the commit cannot be tested, for example when it does not build. Exit code 125 makes bisect skip that commit rather than mark it bad, which is what you want for unbuildable commits. Git picked 125 because 126 and 127 are used by shells for not executable and command not found.

Trade-offs

First-parent bisect is fast and points to a PR, but stops at the merge; a second bisect inside the branch costs more time to reach one commit.

Common mistake

Marking unbuildable commits as bad, which sends bisect to the wrong answer.

Follow-up

How does a merge strategy that keeps every commit buildable make bisect more valuable?

Bisect only main's merges, skipping unbuildable commits · shell
git bisect start --first-parent HEAD v4.12.0
git bisect run sh -c 'make build || exit 125; ./scripts/check-regression.sh'
git bisect reset
Question 63MediumWorkflow

Shell scripts fail in Linux containers with /bin/sh^M: bad interpreter, and pull requests from Windows developers show every line changed. How do you fix line endings for good?

#

The team has a mix of Windows, macOS and Linux machines. Some developers set core.autocrlf, some do not. There is no .gitattributes file.

Show answer

Without attributes, conversion depends on each developer's core.autocrlf, so the repository ends up with a mix of LF and CRLF files, and scripts checked out with CRLF break on Linux. Put the rule in the repository with .gitattributes, so it travels with the code and applies to everyone.

With * text=auto, Git decides per file whether it is text; text files are normalised to LF in the index on check-in, and converted on checkout according to eol and platform. eol=lf makes files use LF in the working tree regardless of platform, which is what shell scripts and Dockerfiles need; eol=crlf suits Windows-only files such as .bat or Visual Studio project files. Mark binary files with -text so they are never touched. For reference, core.autocrlf=true is equivalent to text=auto on all files plus core.eol=crlf.

After adding the file, normalise what is already committed: from a clean working tree run git add --renormalize ., check git status, and commit that as a single dedicated commit. Add that commit to your blame ignore list so it does not hide authorship.

Trade-offs

Repository attributes make behaviour consistent for everyone, at the cost of one large normalisation commit.

Common mistake

Asking every developer to set core.autocrlf correctly instead of committing .gitattributes.

Follow-up

How would you add a CI check that rejects files committed with CRLF where LF is required?

.gitattributes · text
*        text=auto
*.sh     text eol=lf
Dockerfile text eol=lf
*.bat    text eol=crlf
*.png    -text
*.jar    -text
Question 64EasyLarge files

A deployment shipped a "model file" that was 130 bytes of text starting with version https://git-lfs.github.com/spec/v1. What happened?

#

The repository stores model weights in Git LFS. The CI image used for the release job is a minimal one built recently.

Show answer

Git LFS keeps large files out of the Git object store. What Git actually stores is a small pointer file: a version line, an oid sha256:... line and a size line. LFS's spec requires pointers to be under 1024 bytes. The real content lives on the LFS server and is downloaded by the LFS filters during checkout. The new minimal CI image did not have Git LFS installed and set up, so the checkout left the pointer files in place, and the release packaged them.

Fix the job: install Git LFS in the image, run git lfs install to set up the filters, and run git lfs pull (or enable LFS in your CI checkout step) after checkout. Then add a guard that fails the build if any file that should be large is smaller than expected or starts with the pointer's version line. git lfs ls-files lists the files LFS manages.

Watch the cost side too. Every CI checkout that pulls LFS content downloads it again unless you cache it, and LFS hosting providers usually meter storage and bandwidth. Cache the LFS objects directory between runs, and only pull LFS files in jobs that need them.

Trade-offs

LFS keeps clones small, but adds a second system that every clone, mirror and CI image must support.

Common mistake

Assuming a successful checkout means file contents are present when the repository uses LFS.

Follow-up

How would you back up LFS content along with a Git mirror?

Fetch real content and fail if pointers remain · shell
git lfs install
git lfs pull
if grep -rl "version https://git-lfs.github.com/spec/v1" models/; then
  echo "LFS pointers left in models/" >&2; exit 1
fi
Question 65MediumPlatform

Your platform team owns tooling that creates and scans thousands of repositories. What changes are planned for Git 3.0, and how do you prepare now?

#

Internal tools create repos with git init, assume the default branch is master, assume 40-character SHA-1 hashes, and read refs directly from files under .git/refs.

Show answer

Git publishes its planned breaking changes for 3.0. There is no planned release date, and Git says such boundaries are typically years apart, so this is preparation, not an emergency. For newly created repositories, the default hash function changes from SHA-1 to SHA-256 (SHA-1 is not being deprecated), the default ref storage changes from files to reftable, and the default branch name becomes main. safe.bareRepository changes its default from all to explicit, so implicitly discovered bare repositories are refused. Rust becomes a mandatory build dependency. Several old features are removed, including grafts (use git replace), git whatchanged, git pack-redundant, legacy remote shorthands, and name-rev --stdin.

Prepare your tools: never assume a branch name (read it from the remote's HEAD), never assume hash length or format, and never read .git/refs files directly; use git rev-parse, git for-each-ref and git symbolic-ref, which work with both ref backends. Test with reftable today by setting init.defaultRefFormat=reftable for your test runs, and build a test Git with the WITH_BREAKING_CHANGES switch to see 3.0 behaviour early.

Also check your hosting platform and libraries for SHA-256 and reftable support before you create such repositories in production.

Trade-offs

Testing early costs a little CI time now; finding hard-coded assumptions after the default flips costs incidents across every tool.

Common mistake

Parsing .git/refs or packed-refs by hand, which breaks as soon as a repository uses reftable.

Follow-up

Why does the move to SHA-256 need interoperability work between SHA-1 and SHA-256 repositories?

Exercise your tooling against new defaults today · shell
git config --global init.defaultRefFormat reftable
git init --object-format=sha256 /tmp/sha256-test
git -C /tmp/sha256-test symbolic-ref HEAD
Question 66MediumReliability

Your company wants a backup of every repository that does not depend on the Git host. What does git clone --mirror capture, what does it miss, and how do you prove a restore works?

#

Around 800 repositories on a hosted forge. Some use LFS. The audit asks for a tested restore procedure.

Show answer

git clone --mirror creates a bare repository that maps all refs from the source, not just branches but tags, notes and other refs, and configures a refspec so that git remote update overwrites them all on every refresh. That is the right primitive for a Git backup: one mirror per repository, refreshed on a schedule.

What it does not capture: LFS content, because the repository only holds pointer files and the real objects live on the LFS server, so back those up separately with the LFS tooling; and everything the forge keeps outside Git, such as pull requests and reviews, issues, CI settings, branch protection, webhooks and access permissions. Those need the forge's export API. Also note that a mirror refresh overwrites refs, so a force-push or deletion upstream propagates into your mirror on the next update. Keep point-in-time copies (snapshot the storage, or create dated bundles with git bundle create backup.bundle --all) so a destructive push does not destroy the backup too.

Prove restores regularly: pick repositories at random, push a mirror to an empty test repository, clone it, run git fsck, build it, and compare ref lists with the source. Record the time it takes, because that is your recovery time objective.

Trade-offs

Mirrors are cheap and complete for Git data but propagate destructive changes; dated bundles or snapshots cost storage but give real point-in-time recovery.

Common mistake

Calling a mirror a backup while it silently follows every force-push and branch deletion.

Follow-up

How would you back up pull request discussions and branch protection rules?

Create, refresh and snapshot a mirror · shell
git clone --mirror https://git.example.com/team/payments.git payments.git
git -C payments.git remote update --prune
git -C payments.git bundle create ../payments-$(date +%F).bundle --all
git -C payments.git fsck
Question 67HardPerformance

To speed up CI, someone made every job clone with --reference /cache/monorepo.git. Weeks later, builds fail with missing objects after the cache was cleaned. What went wrong, and how do you keep the speed safely?

#

Long-lived runners keep a bare cache repository on local disk. A nightly job runs git gc --prune=now on the cache. Workspaces are reused between jobs.

Show answer

--reference sets up .git/objects/info/alternates so the new clone reads objects from the reference repository instead of copying them. That is why it is fast. But the workspace now depends on the cache: when the nightly gc pruned objects in the cache that the workspace still needed, the workspace was left with references to objects it no longer has.

Use --dissociate together with --reference. The clone borrows objects only to reduce network transfer, then makes local copies of the borrowed objects and stops borrowing once the clone is done. You keep most of the network saving and lose the hidden dependency. --reference-if-able skips a missing cache with a warning instead of failing the clone, which is useful while caches are being rebuilt.

Alternatively, use cheaper patterns that create no dependency: a blobless partial clone, a shallow clone for jobs that need one commit, or a bundle URI (--bundle-uri) that seeds the clone from a pre-built bundle before fetching the rest. Whatever you choose, never run aggressive pruning on a repository that other repositories borrow from.

Trade-offs

Plain alternates are fastest and smallest on disk but fragile; dissociating costs local disk and copy time but makes each workspace self-contained.

Common mistake

Running gc with immediate pruning on a cache that live workspaces still borrow objects from.

Follow-up

How does a bundle URI change the load on your Git server during a fleet-wide CI scale-up?

Borrow for speed, then stand alone · shell
git clone --reference-if-able /cache/monorepo.git --dissociate \
  https://git.example.com/platform/monorepo.git work
Question 68EasyWorkflow

A developer on macOS renamed Readme.md to README.md, but Git shows no change. Later a Linux developer ends up with both files in the repository. Why, and how do you rename safely?

#

Default macOS file system (case-insensitive). The Linux developer created README.md separately while Readme.md still existed in the repo.

Show answer

core.ignoreCase enables workarounds for file systems that are not case-sensitive. It defaults to false, but git clone and git init probe the file system and set it to true when appropriate. On a case-insensitive file system, renaming Readme.md to README.md in Finder or with mv looks like no change to Git, because it treats the two names as the same path.

Rename through Git instead: git mv Readme.md README.md records the rename in the index directly. On some setups a two-step rename through a temporary name is the most reliable: git mv Readme.md tmp.md && git mv tmp.md README.md.

The second problem is worse. On Linux, both names are different files, so the repository can contain both. When macOS and Windows users check that out, only one file can exist on disk, so one silently overwrites the other and git status shows a change nobody made. Fix it by removing one name on a case-sensitive machine, and prevent it with a CI check that fails when two paths in the tree differ only by case.

Trade-offs

Case-insensitive file systems are friendlier for users but hide case changes from Git; a CI guard is cheap protection for mixed teams.

Common mistake

Turning core.ignoreCase off by hand on a case-insensitive file system, which leads to confusing duplicate entries.

Follow-up

Which other path issues (reserved names, path length) bite repositories shared between Windows and Linux?

Case-only rename and a CI guard for case collisions · shell
git mv Readme.md tmp.md && git mv tmp.md README.md
git ls-files | tr "[:upper:]" "[:lower:]" | sort | uniq -d
Question 69MediumInternals

How does Git store data internally (blobs, trees, commits, refs)?

#

Two files have identical contents, and you want to know why adding them barely increases the repository size.

Show answer

Git has four object types. A blob holds file bytes only, with no filename. A tree maps names and modes to blobs or other trees, so it represents a directory. A commit points to one tree, to its parent commit or commits, and holds author, committer and message. An annotated tag is an object that points to a commit.

Objects are content-addressed: the object ID is a hash of the header plus contents, SHA-1 or SHA-256 depending on the repository. Identical file contents therefore produce the same blob ID and are stored once. New objects start as zlib-compressed loose files under .git/objects/xx/... and are later packed with delta compression into packfiles during maintenance.

A ref is a named pointer to an object ID under .git/refs/heads, refs/tags or refs/remotes. HEAD is normally a symbolic ref such as ref: refs/heads/main; in detached HEAD it holds a raw object ID. git cat-file -p <id> and git ls-tree <commit> let you inspect the graph directly.

Trade-offs

Content addressing deduplicates data beautifully but makes history rewriting change every descendant commit ID.

Common mistake

Thinking commits store diffs, or that a branch is a first-class object rather than a moving ref.

Follow-up

Why does a rename show up as a delete and an add at the object level?

Question 70EasyConfiguration

What are git config levels (system, global, local) and how do they override each other?

#

A CI container uses a different user.email from the developer laptop even though git config --list shows the laptop value at home.

Show answer

Git reads configuration in this order: system ($(prefix)/etc/gitconfig), global XDG config ($XDG_CONFIG_HOME/git/config, usually ~/.config/git/config), then ~/.gitconfig, then local ($GIT_DIR/config), then worktree config ($GIT_DIR/config.worktree, only when extensions.worktreeConfig is enabled). Command-line -c values and GIT_CONFIG_KEY_n environment variables sit above all of them. Later values win, so local overrides global, and global overrides system.

include.path and includeIf.<condition>.path splice in more files at that point, with conditions such as gitdir:, onbranch: and hasconfig:remote.*.url: — useful for per-organisation or per-worktree settings. Some options marked as protected configuration are only honoured in system, global or command scope.

Use git config --show-origin --list to see which file supplied each value, or add --show-scope to label the scope. Writes go to local config by default and to exactly one file at a time.

Trade-offs

Worktree config is powerful for per-branch settings but only applies when the extension is enabled in each worktree.

Common mistake

Assuming global overrides local, or that ~/.gitconfig and the XDG file are mutually exclusive.

Follow-up

How would you set a different commit signing key for one repository without touching global config?