Advanced Git: Rebasing

Advanced Git: Rebasing in DevOps Tools: --- A dry-stone field wall holds itself up with nothing but weight, friction and judgement. There is no mortar in it.


The Analogy: A Dry-Stone Wall Rebuilt on a New Footing

A dry-stone field wall holds itself up with nothing but weight, friction and judgement. There is no mortar in it. The waller digs a trench, beds the heaviest stones in the bottom as a footing, and then builds upward course by course, and every stone above the footing is chosen for the hole the course below it left. The waller turns a stone in their hands, finds the face that will sit flat on the two beneath it, knocks a corner off with a hammer if it rocks, and beds it. Stone four hundred is the shape it is because of stones one to three hundred and ninety-nine.

Now the drainage board re-cuts the ditch the wall stands beside, and the footing has to move eighteen inches inland. The wall cannot be dragged. It is taken down instead, stone by stone from the top, and laid out along the grass in the order it came off, so that the bottom of the wall is at one end of the line and the coping is at the other. A new footing goes into the new trench. Then the waller works back up the line from the bottom end, and every stone is dressed again for the neighbours it now has, because the course underneath it is not the course it was cut for.

From the lane the finished wall looks like the same wall. Same length, same height, same coping stones, same gate. But not one stone in it is the stone that was there before: each has been re-faced, and several have lost a corner to the hammer. If the estate office kept a numbered card for every stone, every card would have to be reissued. That is the whole of rebasing in one sentence -- the work is preserved and the identity is not.

The failure mode has two shapes. The first is the neighbour's wall, which butts into yours at one particular stone; move your wall onto a new footing and theirs now meets nothing, and unless they take theirs down too the field ends up with two walls where it had one. The second is the waller who walks off at five o'clock with the stones still lying on the grass, the trench open and the gate hanging on air. Neither of those is a wall. Both are recoverable, but only if somebody remembers the order the stones came off in, which is why the first thing to learn about a rebase is how to put it back.


Syntax or Core Structure

Rebasing needs two branches that have both moved. Build that, and read the divergence before touching it.

git init -q -b main linear
cd linear
printf 'a\n' > a.txt
git add a.txt
git commit -qm 'chore: seed'

git switch -qc feature/report
printf 'r1\n' > report.txt
git add report.txt
git commit -qm 'feat: add report'
printf 'r2\n' >> report.txt
git commit -qam 'feat: add totals row'

git switch -q main
printf 'b\n' > b.txt
git add b.txt
git commit -qm 'chore: add b'

git switch -q feature/report
git log --format='%s' main..HEAD
git rev-list --count main..HEAD
git rev-list --count HEAD..main

Output:

feat: add totals row
feat: add report
2
1

Two commits on the branch, one commit underneath it. Now rebase, and measure what the rebase did to the tip. Two questions are worth asking separately: is it still the same commit, and is it still the same change? A commit id answers the first. A patch id -- a hash of the diff alone, blind to the commit's parent, message, author and date -- answers the second.

old=$(git rev-parse HEAD)
oldpid=$(git show "$old" | git patch-id --stable | awk '{print $1}')

git rebase -q main

new=$(git rev-parse HEAD)
newpid=$(git show "$new" | git patch-id --stable | awk '{print $1}')

[ "$old" = "$new" ] && echo 'commit id: same' || echo 'commit id: different'
[ "$oldpid" = "$newpid" ] && echo 'patch id: same' || echo 'patch id: different'

Output:

commit id: different
patch id: same

Those two lines are the whole subject. The change survived intact; the commit carrying it did not. No commit was moved: git rebase read each one in turn, applied its diff to the new base, wrote a new commit, and finally pointed the branch at the last of them. The originals are still in the object store, reachable through the reflog, but nothing refers to them by name any more.

git log --format='%s'
git rev-list --count HEAD
git cat-file -p HEAD | grep -c '^parent '
git rev-list --count HEAD..main

Output:

feat: add totals row
feat: add report
chore: add b
chore: seed
4
1
0

Four commits in one straight line, one parent on the tip, and nothing left on main that the branch has not seen. The -q earns its place: without it git rebase prints a Rebasing (1/2) counter that it redraws in place with carriage returns, so any script that rebases has unreproducible output until you quiet it.


Technical Depth: Replay, Not Relocation

Two integrations, two different questions

PropertyMerging into your branchRebasing your branch
Existing commit idsunchangedevery replayed commit is rebuilt
Parents on the new tiptwo, on a real mergeone, always
Record that the work belonged togetherthe merge commit itselfnowhere, unless the messages say so
Times one clashing line can stop youonceonce per replayed commit that touches it
Safe on a branch other people haveyesno
Shape in git loga fork and a joina straight line
Undo handle immediately afterwardsgit revert -m 1git reset --hard ORIG_HEAD

Build the same divergence in a second repository and merge it instead, so the two shapes can be counted side by side.

git init -q -b main merged
cd merged
printf 'a\n' > a.txt
git add a.txt
git commit -qm 'chore: seed'

git switch -qc feature/report
printf 'r1\n' > report.txt
git add report.txt
git commit -qm 'feat: add report'
printf 'r2\n' >> report.txt
git commit -qam 'feat: add totals row'

git switch -q main
printf 'b\n' > b.txt
git add b.txt
git commit -qm 'chore: add b'

git merge --no-edit feature/report >/dev/null
git log --first-parent --format='%s'
git rev-list --count HEAD
git cat-file -p HEAD | grep -c '^parent '

Output:

Merge branch 'feature/report'
chore: add b
chore: seed
5
2

Five commits where the rebase produced four, because the merge wrote one of its own. Two parents where the rebase produced one. And --first-parent prints three subjects, which means two of the five are invisible on that path. Neither answer is wrong; they record different facts. The merge records that a branch existed and when it landed. The rebase records only what the branch contained.

Ours and theirs change sides

A conflict during a rebase populates the same three index stages a merge conflict does, but two of them have swapped meaning, because the commit being applied is yours and the thing it is being applied to is upstream.

Index stageDuring a mergeDuring a rebase
1the merge basethe parent of the commit being replayed
2, named "ours"the branch you are standing onthe new base, which is upstream's work
3, named "theirs"the branch being merged inyour own commit being replayed
git init -q -b main clash
cd clash
printf 'const rate = 0.10;\n' > rate.js
git add rate.js
git commit -qm 'chore: seed'

git switch -qc feature/rate
printf 'const rate = 0.15;\n' > rate.js
git commit -qam 'feat: raise rate to 15pc'

git switch -q main
printf 'const rate = 0.20;\n' > rate.js
git commit -qam 'feat: raise rate to 20pc'

git switch -q feature/rate
git rebase main >/dev/null 2>&1
echo "exit=$?"
git status --short
git ls-files --unmerged | awk '{print $3}'
git show :2:rate.js
git show :3:rate.js

Output:

exit=1
UU rate.js
1
2
3
const rate = 0.20;
const rate = 0.15;

Stage 2 holds 0.20, which came from main, and stage 3 holds 0.15, which is the commit being replayed. Anyone who reaches for --ours during a rebase expecting their own work gets upstream's instead. The quieting matters as much as the values: Git also prints CONFLICT (content): Merge conflict in rate.js, an abbreviated commit id and a four-line hint block, none of which is stable enough to paste into a lesson.

Resolve that conflict the obvious way -- keep the value upstream chose -- and watch what happens to the commit.

printf 'const rate = 0.20;\n' > rate.js
git add rate.js
GIT_EDITOR=true git rebase --continue
git log --format='%s'

Output:

Successfully rebased and updated refs/heads/feature/rate.
feat: raise rate to 20pc
chore: seed

The rebase reports success and exits zero, and feat: raise rate to 15pc no longer exists. Its diff against the new base was empty once the file matched 0.20, so there was nothing left to commit and the replay dropped it without comment. Resolve the same conflict the other way, writing 0.15 back, and the branch ends with three commits and rate.js reading 0.15. The conflict resolution is not a formatting choice; it decides whether your commit continues to exist.

Rewriting the recent past

git rebase -i replays commits onto their own existing base and lets a todo list decide what happens to each one. The list is one line per commit, oldest first.

VerbWhat it does to that commit
pickreplay it unchanged
rewordreplay it, then open an editor for the message only
editreplay it, then stop so the tree can be changed and the commit amended
squashfold it into the line above and edit the combined message
fixupfold it into the line above and throw its own message away
dropdo not replay it; deleting the line does the same thing
execrun a shell command at that point in the replay

Setting GIT_SEQUENCE_EDITOR to a sed script edits the todo list without a human, which is how an interactive rebase becomes reproducible.

git init -q -b main tidy
cd tidy
printf 'x\n' > x.txt
git add x.txt
git commit -qm 'chore: seed'
printf 'p1\n' > parser.js
git add parser.js
git commit -qm 'feat: parser skeleton'
printf 'p2\n' >> parser.js
git commit -qam 'wip'
printf 'p3\n' >> parser.js
git commit -qam 'wip again'
printf 'note\n' > NOTES
git add NOTES
git commit -qm 'chore: scratch notes'

GIT_SEQUENCE_EDITOR="sed -i '2,3s/^pick/squash/'" GIT_EDITOR=true git rebase -i HEAD~4 >/dev/null 2>&1
echo "exit=$?"
git log --format='%s'
git rev-list --count HEAD
cat parser.js

Output:

exit=0
chore: scratch notes
feat: parser skeleton
chore: seed
3
p1
p2
p3

Lines 2 and 3 of the todo list were the two wip commits, so they folded into the skeleton above them. Five commits became three and parser.js still holds all three lines: squashing combines commits, it does not discard changes. Now delete a line instead of changing its verb.

GIT_SEQUENCE_EDITOR="sed -i '2d'" git rebase -i HEAD~2 >/dev/null 2>&1
echo "exit=$?"
git log --format='%s'
git rev-list --count HEAD
ls

Output:

exit=0
feat: parser skeleton
chore: seed
2
parser.js
x.txt

NOTES is gone from the working tree as well as from the history, because dropping a commit drops its changes with it. That is the difference between drop and squash in one command, and it is the reason interactive rebase deserves a scratch branch the first few times.

Moving one branch off another

git rebase upstream branch replays everything in upstream..branch. When branches are stacked, that range contains the branch underneath too, which is rarely what you want. --onto separates the two ideas: the first argument is where the commits should land, the second is where the range should start.

git init -q -b main stacked
cd stacked
printf 's\n' > s.txt
git add s.txt
git commit -qm 'chore: seed'
git switch -qc feature/a
printf 'a1\n' > a.txt
git add a.txt
git commit -qm 'feat: a1'
git switch -qc feature/b
printf 'b1\n' > b.txt
git add b.txt
git commit -qm 'feat: b1'
printf 'b2\n' >> b.txt
git commit -qam 'feat: b2'

echo 'before:'
git log --format='%s'
git rebase -q --onto main feature/a feature/b
echo 'after:'
git log --format='%s'
ls

Output:

before:
feat: b2
feat: b1
feat: a1
chore: seed
after:
feat: b2
feat: b1
chore: seed
b.txt
s.txt

feature/b now sits directly on main with feature/a's commit excluded, and a.txt has left the working tree because it was never part of feature/b's own changes. feature/a itself has not moved; only feature/b was rewritten. This is the tool for the day a colleague's branch gets rejected and your branch, stacked on top of it, has to survive.


Real World Example: A Replay Plan That Forgets the Neighbours

Teams that rebase routinely want to know what a rebase will do before it does it. This script answers that from the object store only: it moves no ref, writes no commit, and touches no file. Save it beside the repository as replay-plan.sh.

#!/usr/bin/env bash
# replay-plan.sh <upstream> <branch> -- report what rebasing <branch> onto
# <upstream> would replay, without moving any ref.
set -u

upstream=$1
branch=$2

git merge-base "$upstream" "$branch" >/dev/null || { echo "plan: no common ancestor"; exit 2; }

replay=$(git rev-list --count "$upstream".."$branch")
missing=$(git rev-list --count "$branch".."$upstream")

echo "branch=$branch upstream=$upstream"
echo "replay=$replay missing=$missing"

if git merge-base --is-ancestor "$upstream" "$branch"; then
  echo "plan: already on top of $upstream, nothing to replay"
  exit 0
fi

dupes=$(git cherry "$upstream" "$branch" | grep -c '^-' || true)
echo "dupes=$dupes"

published=0
for ref in $(git for-each-ref --format='%(refname)' refs/remotes); do
  git merge-base --is-ancestor "$branch" "$ref" && published=$((published + 1))
done
echo "published=$published"

git rev-list --reverse --no-commit-header --format='%s' "$upstream".."$branch" | while IFS= read -r s; do
  echo "  replay: $s"
done

if [ "$published" -gt 0 ]; then
  echo "plan: refuse -- these commits already exist on a remote"
  exit 1
fi
echo "plan: safe to rebase"
exit 0

The scenario it has to describe is the ordinary one. A feature branch of three commits, a documentation branch stacked on top of it, an integration branch that has moved on, and -- the detail that makes it interesting -- one of the feature commits already cherry-picked onto main by somebody in a hurry.

git init -q -b main platform
cd platform
printf 'v1\n' > VERSION
git add VERSION
git commit -qm 'chore: seed platform'

git switch -qc feature/api
printf 'get\n' > api.js
git add api.js
git commit -qm 'feat: add read endpoint'
printf 'post\n' >> api.js
git commit -qam 'feat: add write endpoint'
printf 'auth\n' > auth.js
git add auth.js
git commit -qm 'feat: add token check'

git switch -qc feature/api-docs
printf 'docs\n' > api.md
git add api.md
git commit -qm 'docs: document the endpoints'

git switch -q main
printf 'v2\n' > VERSION
git commit -qam 'chore: bump to v2'
tok=$(git rev-parse feature/api)
git cherry-pick "$tok" >/dev/null 2>&1
git log --format='%s' main

git switch -q feature/api
bash ../replay-plan.sh main feature/api
echo "exit=$?"

Output:

feat: add token check
chore: bump to v2
chore: seed platform
branch=feature/api upstream=main
replay=3 missing=2
dupes=1
published=0
  replay: feat: add read endpoint
  replay: feat: add write endpoint
  replay: feat: add token check
plan: safe to rebase
exit=0

Take the plan at its word and rebase, then look at what happened to the branch that was stacked on top.

old=$(git rev-parse feature/api)
git rebase -q main 2>/dev/null
echo "exit=$?"
git log --format='%s' main..feature/api
git rev-list --count main..feature/api
git rev-list --count feature/api..feature/api-docs
git log --format='%s' main..feature/api-docs
git for-each-ref --contains "$old" --format='%(refname)'

Output:

exit=0
feat: add write endpoint
feat: add read endpoint
2
4
docs: document the endpoints
feat: add token check
feat: add write endpoint
feat: add read endpoint
refs/heads/feature/api-docs

Every line of the script is asked of the object store, never of the checkout. git rev-list --count upstream..branch is the replay count, and the same range reversed is missing, the work the branch has not caught up with yet. git merge-base --is-ancestor short-circuits the whole report when the branch is already on top, because replaying nothing is not worth describing. git cherry compares patch ids rather than commit ids, so a - in its output means "upstream already has this change under a different name". The published loop walks refs/remotes and asks whether the branch is an ancestor of each remote-tracking ref, since a commit that has left your machine must not be rewritten. The while IFS= read -r loop prints the subjects in replay order, oldest first, because that is the order the rebase will apply them.

Read against the scenario the numbers hold together. replay=3 is the three commits on feature/api, missing=2 is the version bump plus the cherry-pick that main gained, and dupes=1 is the cherry-picked commit whose patch main already carries. published=0 is honest: this repository has no remote, so refs/remotes is empty and the loop runs zero times. After the rebase, main..feature/api holds two commits, not three -- the duplicate was recognised and skipped -- so replay=3 and dupes=1 had to be read together to predict the outcome, and the script never subtracts them for you.

The analogy holds all the way through. The plan is the estate clerk walking the wall before the diggers arrive, counting stones and noting which ones the neighbour has already copied into their own wall. What the clerk does not do is walk the length of the boundary to see whose wall butts into yours -- and that is exactly the line the script never asks about.

The design flaw is not a rough edge but a question the script was built to answer and does not. It decides safety from remote-tracking refs alone, so it never notices local refs standing on the commits about to be rewritten. feature/api-docs was forked from the old tip, and after a rebase the plan called safe, git rev-list --count feature/api..feature/api-docs reports 4: one documentation commit plus three abandoned copies of work that now exists twice under two sets of ids. Merge that branch later and the three come back. The fix is one command the script already had the vocabulary for -- git for-each-ref --contains "$old" prints refs/heads/feature/api-docs before anything moves -- and the cure is git rebase --update-refs, which replays dependent branches in the same pass. Three lesser defects are worth naming. published trusts refs/remotes, which the previous lesson established is a cached note that only git fetch refreshes, so a stale clone reports 0 for a branch that has been on the server for a week. dupes rests on patch-id equality, which a single whitespace change defeats and which two different commits with identical diffs satisfy spuriously. And replay counts commits, not difficulty: three commits that all rewrite one function will stop the rebase three times, while thirty that touch thirty files will not stop it at all.


Common Mistakes

  1. Rebasing a branch other people have already pulled. The replayed commits are new objects, so a colleague who pulls afterwards gets both sets and a merge that duplicates every change. The rule is not about main specifically: it is about any commit that has left your machine.
  1. Reading "ours" as your own work during a rebase conflict. Stage 2 is the new base, which is upstream. git checkout --ours in the middle of a rebase throws away the commit you were replaying, and it does it silently.
  1. Not checking that a resolved commit still exists. Resolving in upstream's favour can leave a commit with an empty diff, and the replay drops it and reports success. Compare git rev-list --count upstream..HEAD before and after, not just the exit status.
  1. Reaching for git push --force after a rebase. It overwrites whatever is on the server, including commits somebody pushed while you were rebasing. --force-with-lease refuses unless the remote ref is still where your last fetch saw it.
  1. Starting a rebase with a dirty working tree. Git will refuse, and the usual reaction is a throwaway wip commit that then has to be unpicked. --autostash does the same job and puts the changes back afterwards, including when the rebase is aborted.
  1. Rebasing a long-lived branch that a merge would integrate once. A line both sides rewrote raises a conflict once in a merge and once per replayed commit in a rebase. Twelve commits over a contested file is twelve resolutions of nearly the same thing.
  1. Squashing every branch to one commit out of habit. It makes git log tidy and git bisect useless: the bisect lands on a commit containing a fortnight of work, which is exactly the outcome bisecting was supposed to avoid.
  1. Using git rebase --skip to get past a conflict. --skip does not skip the conflict, it discards the commit that caused it. Use it only when you have established that the change is already upstream.
  1. Forgetting the refs standing on the old commits. Stacked branches, worktrees and annotated tags all keep pointing at the pre-rebase objects. git for-each-ref --contains names them in advance; git rebase --update-refs carries the branches along.

Best Practices

  • Rebase your own unpushed work and merge everything else. The question to ask is not "is this branch shared" but "has any of this ever left my machine".
  • Push a rebased branch with git push --force-with-lease, never with --force. It costs nothing when you are right and refuses the push when somebody else has moved the ref.
  • Turn on git config rebase.updateRefs true if you keep stacked branches. Every rebase then replays the dependent branches too, which removes the whole class of failure the plan script above missed.
  • Rebase onto the integration branch little and often. Two commits of drift is one small conflict; forty is a week of them raised one commit at a time.
  • Use --autostash rather than a temporary wip commit, so an aborted rebase leaves the working tree exactly as it was.
  • Prove the branch after a rewrite, not just at its tip: git rebase -i --exec 'npm test' HEAD~5 runs the suite after every replayed commit and stops on the first one that breaks.
  • Read the divergence before rebasing. git merge-base --is-ancestor and git rev-list --count cost nothing and tell you whether there is anything to replay at all.
  • Treat git rebase --abort as the default response to a rebase you do not understand, and remember that a finished rebase is still undoable through git reset --hard ORIG_HEAD or the branch reflog for as long as the entries survive, which defaults to ninety days.

Practice Exercises

  1. Make a commit disappear, then bring it back. Reproduce the rate.js conflict, resolve it in upstream's favour, and confirm with git rev-list --count main..HEAD that your commit is gone even though the rebase exited zero. Then recover it: find the pre-rebase tip in git reflog, restore the branch to it, and report the count before and after.
  1. Prove the inversion for yourself. Build a conflict in a rebase and a conflict in a merge over the same two commits, and for each one print stage 2 and stage 3 with git show :2:<path> and git show :3:<path>. State which side --ours selects in each case, and write one sentence explaining why the answers differ.
  1. Fix the plan script. Add a dependents count built from git for-each-ref --contains, print each dependent ref name, and refuse the rebase when the count is greater than zero. Then rerun the feature/api scenario twice: once with your refusal, and once with git rebase --update-refs instead, reporting git rev-list --count feature/api..feature/api-docs after each. Explain which of the two you would put in a team's tooling.
  1. Measure the two integrations. Build one divergence of three commits over two, then integrate it twice from a clean copy: once with git rebase and once with git merge --no-ff. For each result report git rev-list --count HEAD, the parent count on the tip, and the line count of git log --first-parent --format='%s'. Say which result lets you revert the whole feature with one command, and which one you would rather read six months later.