Learnings

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

The model

A commit stores the whole project as a tree, plus a pointer to its parent. Diffs are computed when you ask, never stored.

Three object types. An unchanged file is the same blob in both trees.
ObjectHoldsNamed by
blobFile contents, no nameSHA-1 of its own content, so identical content is stored once and nothing can change without its name changing
treeA directory: names, modes, blob and tree ids
commitOne 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

The model

A branch is a file holding one commit id. HEAD is a file naming the current branch, and committing moves that branch forward.

Commits point back at parents. Branches and HEAD are labels on top.
  • Creating a branch writes 41 bytes. Deleting one deletes the label, not the commits.
  • HEAD~1 is the first parent, HEAD~2 its parent. HEAD^2 is 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.

HEAD points straight at C2. No branch will move on commit.

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 model

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.

Each command copies content one step, forward or back.
git reset modeBranch pointerIndexWorking tree
--soft Xmoves to Xkeptkept
--mixed X (default)moves to Xreset to Xkept
--hard Xmoves to Xreset to Xreset 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

Everyday precision

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.

  • y stage, n skip, s split, e edit the hunk by hand, q quit.
  • The same flag works on restore -p, reset -p and stash -p.

restore and switch replace checkout

Everyday precision

checkout did two unrelated jobs: move HEAD, and overwrite files. Since Git 2.23 each job has its own command.

IntentNowOld
Change branchgit switch maingit checkout main
Create and changegit switch -c fixgit checkout -b fix
Previous branchgit switch -git checkout -
Look at an old commitgit switch --detach v1.0git checkout v1.0
Discard edits to a filegit restore fgit checkout -- f
Unstage a filegit restore --staged fgit reset HEAD f
File as it was in a commitgit restore --source=v1.0 fgit checkout v1.0 -- f

Stash

Everyday precision

A stash is a commit kept on a private stack instead of a branch. Name every one, or the list becomes unreadable.

CommandDoes
stash push -uAlso takes untracked files (plain stash leaves them behind)
stash push -p / -- pathStashes chosen hunks or paths only
stash pop / applyRestore and drop / restore and keep
stash branch nameNew branch at the stash's base commit, then pop: the fix when pop conflicts

Log forms worth knowing

Everyday precision

git log is a query over the commit graph: choose which commits, then how to print them.

FormFinds
-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 -- fileHistory of one file across renames
-L :func:fileHistory of one function
--first-parentOnly the main line, one entry per merged branch
--author, --since, --grepFilter by person, date, message

Two dots, three dots

Everyday precision

a..b means "reachable from b but not from a". a...b means "on either side but not both".

A is the merge base. main has E, statement has B, C, D.
CommandResult
git log main..statementB C D: what the branch adds
git log statement..mainE: what the branch is missing
git log --left-right main...statementE marked <, B C D marked >
git diff main..statementTip against tip: also shows E undone
git diff main...statementA 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

Everyday precision

Every diff compares two of: working tree, index, a commit. Know which two.

CommandCompares
git diffIndex and working tree: not yet staged
git diff --stagedHEAD and index: what commit would record
git diff HEADHEAD and working tree: everything uncommitted
git diff a b -- pathTwo commits, one path
git diff --stat / --name-onlySummary instead of patch
git diff --word-diffChanged words, for prose and long lines
git show XCommit X against its parent

Integrating work

Part 3 of 6 · four ways to land a branch, and how to rewrite history safely

Fast-forward

Integrating work

If main has not moved since the branch started, merging only slides the main pointer forward. No new commit is made.

Before: main at B, transfer two commits ahead.
After 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

Integrating work

When both sides have new commits, git merge creates a commit with two parents. The next three chapters all start from this graph.

Before: diverged. main added E, transfer added C and D.
After git merge transfer: M has parents E and D.

Squash

Integrating work

merge --squash stages the branch's total change and you commit it once, with one parent. The branch is not recorded as merged.

After: S holds the same change as C and D, with no link to them.

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

Integrating work

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.

After git rebase main on transfer: C' and D' are copies. The old C and D are unreachable.
  • 65405fc became 060d100: same change, different parent, different id.
  • Conflicts arrive one commit at a time: fix, git add, git rebase --continue. --abort puts everything back.

Which one, when

Integrating work

MethodHistory on mainUse whenCost
Fast-forwardLinear, every commitBranch is already on top of mainNo record that a branch existed
Merge commitGraph, every commitLong-lived or shared branches, release mergesNoisy graph without --first-parent
SquashLinear, one commit per branchSmall pull requests with messy commitsLoses the steps, weaker bisect and blame
Rebase, then fast-forwardLinear, every commitYour own branch with commits worth keepingRewrites 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

Integrating work

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.

VerbEffect
pickKeep as is
rewordKeep the change, edit the message
squashFold into the line above, combine messages
fixupFold into the line above, drop this message
editStop here to amend or split
dropRemove the commit

Habit: set git config rebase.autoSquash true and answer review comments with commit --fixup.

The golden rule and force-with-lease

Integrating work

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.

FlagOverwrites the remote branch
--forceAlways. The colleague's commit above would be gone.
--force-with-leaseOnly 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

Integrating work

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.

  • -x records 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

Integrating work

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

Conflicts and recovery

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 base block 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

Conflicts and recovery

Edit the file to the final text, remove the markers, stage it, commit. Or back out completely.

NeedCommand
List files still in conflictgit diff --name-only --diff-filter=U
Take one side for a whole filegit checkout --ours f / --theirs f
Start the file's conflict againgit checkout --conflict=zdiff3 f
Give upgit 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

Conflicts and recovery

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 backup costs nothing.

Undo table

Conflicts and recovery

MistakeNot pushedAlready pushed and shared
Wrong commit messagegit commit --amend -m "..."Leave it, or agree a force push
Forgot a filegit add f, then git commit --amend --no-editA new commit
Committed to the wrong branchgit branch right, then git reset --hard HEAD~1git revert there, git cherry-pick here
Bad mergegit reset --hard ORIG_HEADgit revert -m 1 <merge>
Bad rebasegit reset --hard ORIG_HEAD, or pick the id from git reflogSame, then push --force-with-lease
Committed a secretAmend or interactive rebase to drop itRotate 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

Conflicts and recovery

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".
  • -B matters: 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

Remotes and teams

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.

Fetch is always safe. The second step is the one that can conflict.
  • pull --rebase replays 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, or pull.ff only to 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

Remotes and teams

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 describe ignores lightweight ones by default.
  • Tags are not pushed by git push. Name the tag, or use --follow-tags.

Team workflows

Remotes and teams

Trunk-basedGitHub flowGit flow
Long-lived branchesmainmainmain, develop, release and hotfix branches
Feature branch lifeHours to a day or twoDays, one pull request eachDays to weeks
Unfinished workBehind feature flagsStays on the branchStays on develop
ReleaseAny green commit on mainEvery merge to main deploysCut a release branch, stabilise, tag
NeedsFast CI, flags, strong testsCI and review on every pull requestDiscipline about merge directions
FitsServices deployed continuouslyMost web teamsVersioned 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

Remotes and teams

A commit is one logical change that builds and passes tests on its own. That is what makes revert, cherry-pick and bisect work.

GoodAvoid
SubjectImperative, about 50 characters, says what changes"fix", "wip", "review comments"
BodyWhy, and what was wrong beforeRepeating the diff in words
ScopeOne change. Refactor and behaviour in separate commits.Formatting mixed into a bug fix
Pull request sizeReviewable in one sitting, a few hundred linesA week of work in one request
Pull request textProblem, approach, how it was tested, risk and rollbackTitle only

Hooks, ignore, attributes

Remotes and teams

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 hooks or a hook manager, and repeat the check in CI because --no-verify skips them.
  • .gitignore only affects untracked files. For a file already tracked, run git rm --cached f first.
  • .gitattributes sets per-path rules: line endings, binary, diff and merge drivers.

Worktrees

Remotes and teams

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

Internals and recap

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

Internals and recap

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

Internals and recap

QuestionShort 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.