Senior engineering skills
Git in Depth
The model behind the commands you already type, drawn as graphs: objects, pointers, the three areas, the four ways to integrate work, and how to get back anything you "lost". Every terminal session was run with Git 2.51 on throwaway repositories of a small bank project, so your commit hashes will differ.
The model
Part 1 of 6 · objects, pointers and the three areas
Commits are snapshots
A commit stores the whole project as a tree, plus a pointer to its parent. Diffs are computed when you ask, never stored.
| Object | Holds | Named by |
|---|---|---|
| blob | File contents, no name | SHA-1 of its own content, so identical content is stored once and nothing can change without its name changing |
| tree | A directory: names, modes, blob and tree ids | |
| commit | One tree, parent ids, author, message |
Interview point: a commit id covers its parents, so changing any ancestor changes every id after it. That is why rebase and amend create new commits.
Branches, HEAD and detached HEAD
A branch is a file holding one commit id. HEAD is a file naming the current branch, and committing moves that branch forward.
- Creating a branch writes 41 bytes. Deleting one deletes the label, not the commits.
HEAD~1is the first parent,HEAD~2its parent.HEAD^2is the second parent of a merge.
Detached HEAD. HEAD is detached when it holds a commit id instead of a branch name. New commits made there belong to no branch.
Keep the work: run git switch -c rescue before leaving. If you already left, the commit is still in the reflog.
Working tree, index, repository
The index (staging area) is the next commit, being built. git status -s shows two columns: index on the left, working tree on the right.
git reset mode | Branch pointer | Index | Working tree |
|---|---|---|---|
--soft X | moves to X | kept | kept |
--mixed X (default) | moves to X | reset to X | kept |
--hard X | moves to X | reset to X | reset to X |
Trap: git restore file and reset --hard throw away uncommitted edits, and no reflog holds those.
Everyday precision
Part 2 of 6 · staging, undoing, searching and comparing exactly what you mean
Stage by hunk: add -p
git add -p asks about each change separately, so one edited file can become two clean commits. Here the deposit check is staged and the unfinished transfer is left out.
ystage,nskip,ssplit,eedit the hunk by hand,qquit.- The same flag works on
restore -p,reset -pandstash -p.
restore and switch replace checkout
checkout did two unrelated jobs: move HEAD, and overwrite files. Since Git 2.23 each job has its own command.
| Intent | Now | Old |
|---|---|---|
| Change branch | git switch main | git checkout main |
| Create and change | git switch -c fix | git checkout -b fix |
| Previous branch | git switch - | git checkout - |
| Look at an old commit | git switch --detach v1.0 | git checkout v1.0 |
| Discard edits to a file | git restore f | git checkout -- f |
| Unstage a file | git restore --staged f | git reset HEAD f |
| File as it was in a commit | git restore --source=v1.0 f | git checkout v1.0 -- f |
Stash
A stash is a commit kept on a private stack instead of a branch. Name every one, or the list becomes unreadable.
| Command | Does |
|---|---|
stash push -u | Also takes untracked files (plain stash leaves them behind) |
stash push -p / -- path | Stashes chosen hunks or paths only |
stash pop / apply | Restore and drop / restore and keep |
stash branch name | New branch at the stash's base commit, then pop: the fix when pop conflicts |
Log forms worth knowing
git log is a query over the commit graph: choose which commits, then how to print them.
| Form | Finds |
|---|---|
-S"text" | Commits that changed how many times text occurs: when it was added or removed |
-G"regex" | Commits whose diff has a changed line matching the regex |
--follow -- file | History of one file across renames |
-L :func:file | History of one function |
--first-parent | Only the main line, one entry per merged branch |
--author, --since, --grep | Filter by person, date, message |
Two dots, three dots
a..b means "reachable from b but not from a". a...b means "on either side but not both".
| Command | Result |
|---|---|
git log main..statement | B C D: what the branch adds |
git log statement..main | E: what the branch is missing |
git log --left-right main...statement | E marked <, B C D marked > |
git diff main..statement | Tip against tip: also shows E undone |
git diff main...statement | A against D: only the branch's own work, what a pull request shows |
Trap: the dots mean different things to log and diff. For diff, three dots is the one you usually want.
Diff forms
Every diff compares two of: working tree, index, a commit. Know which two.
| Command | Compares |
|---|---|
git diff | Index and working tree: not yet staged |
git diff --staged | HEAD and index: what commit would record |
git diff HEAD | HEAD and working tree: everything uncommitted |
git diff a b -- path | Two commits, one path |
git diff --stat / --name-only | Summary instead of patch |
git diff --word-diff | Changed words, for prose and long lines |
git show X | Commit X against its parent |
Integrating work
Part 3 of 6 · four ways to land a branch, and how to rewrite history safely
Fast-forward
If main has not moved since the branch started, merging only slides the main pointer forward. No new commit is made.
git merge transfer: main and transfer both at D.Flags: --ff-only refuses anything else, and --no-ff forces a merge commit even here.
Merge commit
When both sides have new commits, git merge creates a commit with two parents. The next three chapters all start from this graph.
git merge transfer: M has parents E and D.Squash
merge --squash stages the branch's total change and you commit it once, with one parent. The branch is not recorded as merged.
Trap: do not keep working on a squashed branch. Git does not know C and D are in main, so the next merge conflicts with itself.
Rebase
Rebase replays the branch's commits on top of the new base, as new commits with new ids. History ends up linear, and main can then fast-forward.
git rebase main on transfer: C' and D' are copies. The old C and D are unreachable.65405fcbecame060d100: same change, different parent, different id.- Conflicts arrive one commit at a time: fix,
git add,git rebase --continue.--abortputs everything back.
Which one, when
| Method | History on main | Use when | Cost |
|---|---|---|---|
| Fast-forward | Linear, every commit | Branch is already on top of main | No record that a branch existed |
| Merge commit | Graph, every commit | Long-lived or shared branches, release merges | Noisy graph without --first-parent |
| Squash | Linear, one commit per branch | Small pull requests with messy commits | Loses the steps, weaker bisect and blame |
| Rebase, then fast-forward | Linear, every commit | Your own branch with commits worth keeping | Rewrites ids, so only before others build on it |
Common team rule: rebase your own branch to update it, squash or merge it into main through the pull request, never rebase main.
Interactive rebase
git rebase -i main opens a todo list of your commits, oldest first. Edit the list and Git replays it: reorder lines, or change the verb.
A second pass with the list edited by hand: move one line up, squash it, and reword another.
| Verb | Effect |
|---|---|
pick | Keep as is |
reword | Keep the change, edit the message |
squash | Fold into the line above, combine messages |
fixup | Fold into the line above, drop this message |
edit | Stop here to amend or split |
drop | Remove the commit |
Habit: set git config rebase.autoSquash true and answer review comments with commit --fixup.
The golden rule and force-with-lease
Never rewrite commits that other people have built on: amend, rebase and reset all replace commits, and their copies still point at the old ones. On your own pushed branch a rewrite needs a force push, and --force-with-lease is the safe form.
| Flag | Overwrites the remote branch |
|---|---|
--force | Always. The colleague's commit above would be gone. |
--force-with-lease | Only if the remote is still where your origin/branch says it is |
--force-if-includes (add to the lease) | Only if you have also integrated what you last fetched |
Trap: a background git fetch (many editors do this) updates origin/branch and makes the lease pass. In this run, git fetch followed by the same push went through as a forced update and removed the colleague's commit.
Cherry-pick
Cherry-pick copies one commit's change onto the current branch as a new commit. The usual job is a hotfix to a release branch.
-xrecords where the copy came from. Use it on release branches.- The copy and the original are different commits: prefer a merge when you want the whole branch.
Revert versus reset
Revert adds a commit that undoes an earlier one: safe on shared branches. Reset moves the branch pointer back: a rewrite, for local commits only.
git revert C: history grows, C stays visible.git reset --hard B: main moves back, C is left to the reflog.Trap: reverting a merge needs -m 1 (keep parent 1's side). To bring that branch back later you must revert the revert, because Git still counts its commits as merged.
Conflicts and recovery
Part 4 of 6 · reading conflicts, and getting back what looks lost
What a conflict is
A merge compares three versions: the base and the two tips. A conflict is one region that both tips changed differently from the base.
- Top block is ours (the branch you are on), bottom is theirs (the branch coming in).
- The
baseblock shows what each side changed. Make it the default:git config merge.conflictStyle zdiff3.
Trap: during a rebase the sides swap. "Ours" is the branch you are rebasing onto, "theirs" is your own commit being replayed.
Resolving, aborting, rerere
Edit the file to the final text, remove the markers, stage it, commit. Or back out completely.
| Need | Command |
|---|---|
| List files still in conflict | git diff --name-only --diff-filter=U |
| Take one side for a whole file | git checkout --ours f / --theirs f |
| Start the file's conflict again | git checkout --conflict=zdiff3 f |
| Give up | git merge --abort, git rebase --abort, git cherry-pick --abort |
rerere: git config rerere.enabled true records each resolution and replays it when the same conflict appears again. It pays off when you rebase a long branch repeatedly.
Reflog: nothing committed is lost
The reflog is a local diary of every position HEAD has held. A commit that no branch reaches is still there, by default for at least 30 days.
- Git prints the old id when it deletes a branch. That line alone is enough to restore it.
- The reflog is per clone and never pushed. A fresh clone has none.
- Before a risky rewrite,
git branch backupcosts nothing.
Undo table
| Mistake | Not pushed | Already pushed and shared |
|---|---|---|
| Wrong commit message | git commit --amend -m "..." | Leave it, or agree a force push |
| Forgot a file | git add f, then git commit --amend --no-edit | A new commit |
| Committed to the wrong branch | git branch right, then git reset --hard HEAD~1 | git revert there, git cherry-pick here |
| Bad merge | git reset --hard ORIG_HEAD | git revert -m 1 <merge> |
| Bad rebase | git reset --hard ORIG_HEAD, or pick the id from git reflog | Same, then push --force-with-lease |
| Committed a secret | Amend or interactive rebase to drop it | Rotate the secret first. Rewriting history comes second. |
Pushed secret: it is compromised the moment it is pushed, and clones, forks and caches keep it whatever you rewrite. Scrubbing history uses the separate git filter-repo tool plus a force push (not run for this page).
Bisect
Give Git one good commit, one bad commit and a script that exits 0 or 1. It binary-searches the history: 8 commits take 3 runs, 1000 take 10.
- Keep the script outside the repository, so checkouts do not change it.
- Exit code 125 means "cannot test this commit, skip it".
-Bmatters: without it a stale__pycache__file made the first attempt on this page blame the wrong commit.
Remotes and teams
Part 5 of 6 · fetch, tracking, tags and how teams agree to use them
Fetch, pull and tracking branches
origin/main is your local copy of where the remote's main was at the last fetch. Fetch updates only that copy, and pull is fetch plus an integration into your branch.
pull --rebasereplays your local commits on top of the remote's, so no "Merge branch main" commits appear.- Make it the default:
git config pull.rebase true, orpull.ff onlyto be told when you have diverged.
Tracking and pruning. A local branch can name an upstream. That is what bare git push, git pull and the ahead/behind counts use.
- Set the upstream on first push:
git push -u origin name. - Remote-tracking branches are never removed unless you prune:
git config fetch.prune true.
Tags
A lightweight tag is a pointer that never moves. An annotated tag is a real object with tagger, date and message, and can be signed.
- Use annotated tags for releases:
git describeignores lightweight ones by default. - Tags are not pushed by
git push. Name the tag, or use--follow-tags.
Team workflows
| Trunk-based | GitHub flow | Git flow | |
|---|---|---|---|
| Long-lived branches | main | main | main, develop, release and hotfix branches |
| Feature branch life | Hours to a day or two | Days, one pull request each | Days to weeks |
| Unfinished work | Behind feature flags | Stays on the branch | Stays on develop |
| Release | Any green commit on main | Every merge to main deploys | Cut a release branch, stabilise, tag |
| Needs | Fast CI, flags, strong tests | CI and review on every pull request | Discipline about merge directions |
| Fits | Services deployed continuously | Most web teams | Versioned software with several releases in support |
Interview point: the shorter a branch lives, the smaller its merge. Long-lived branches are where integration pain comes from, whatever the workflow is called.
A good commit, a good pull request
A commit is one logical change that builds and passes tests on its own. That is what makes revert, cherry-pick and bisect work.
| Good | Avoid | |
|---|---|---|
| Subject | Imperative, about 50 characters, says what changes | "fix", "wip", "review comments" |
| Body | Why, and what was wrong before | Repeating the diff in words |
| Scope | One change. Refactor and behaviour in separate commits. | Formatting mixed into a bug fix |
| Pull request size | Reviewable in one sitting, a few hundred lines | A week of work in one request |
| Pull request text | Problem, approach, how it was tested, risk and rollback | Title only |
Hooks, ignore, attributes
A hook is an executable in .git/hooks/ that Git runs at a fixed moment. A non-zero exit from pre-commit stops the commit.
- Hooks are not cloned. Share them with
git config core.hooksPath hooksor a hook manager, and repeat the check in CI because--no-verifyskips them. .gitignoreonly affects untracked files. For a file already tracked, rungit rm --cached ffirst..gitattributessets per-path rules: line endings, binary, diff and merge drivers.
Worktrees
A worktree is a second working directory on the same repository, with its own branch checked out. Fix production in one folder while your feature stays untouched in the other, with no stash.
Rule: one branch can be checked out in only one worktree at a time.
Internals and recap
Part 6 of 6 · reading the object store, and a one-page summary
Walking from a commit to a blob
git cat-file -p prints any object. Three calls take you from a commit to a file's bytes, which is the object diagram for real.
- The file name lives in the tree, not the blob. A rename is a new tree pointing at the same blob.
- Blob and tree ids depend only on content, so these are the same on your machine. Commit ids include the timestamp, so those differ.
gc and packfiles
git gc moves loose objects (one compressed file each) into a packfile that stores similar objects as deltas, and prunes unreachable objects once they are old enough. Git runs it automatically.
Link to recovery: gc is what finally deletes a "lost" commit, after its reflog entry expires (90 days by default, 30 once the commit is unreachable).
Cheat sheet
| Question | Short answer |
|---|---|
| What is a commit? | A snapshot (tree) plus parent ids. Immutable, named by its hash. |
| What is a branch? | A movable pointer to one commit |
| What is HEAD? | A pointer to the current branch, or to a commit when detached |
| What is staged? | git diff --staged |
| What does my branch add? | git log main..HEAD, git diff main...HEAD |
| When was this string introduced? | git log -S"text" |
| Update my branch from main? | git fetch, then git rebase origin/main |
| Tidy commits before review? | commit --fixup, then rebase -i --autosquash |
| Push after a rewrite? | git push --force-with-lease, own branch only |
| Undo something shared? | git revert (-m 1 for a merge) |
| Undo something local? | git reset, --soft to keep the changes staged |
| Lost a commit or a branch? | git reflog, then git branch name <id> |
| Which commit broke it? | git bisect start bad good, git bisect run script |
| Stuck in a merge or rebase? | --abort |
| Two branches at once? | git worktree add |
Back to Senior Skills.