How to squash-merge stacked PRs

Assume PR A branches off master and PR B branches off PR A. We squash-merge PR A into master. PR B must now be "restacked" before merging.

Why a normal rebase doesn't work

A squash-merge collapses all of A's commits into one new commit on master with a new SHA. A's original commits are not ancestors of this new commit.

But branch B still contains A's original commits in its history. So:

Restacking

The fix is git rebase --onto, which lets us replay only B's own commits and drop A's.

git checkout <branch-B>
git fetch origin
git rebase --onto origin/master <old-A-tip> <branch-B>
git push --force-with-lease