Video in progress

Senior 🌿 Git

When you send a big change as several dependent PRs (stacked PRs), how do you work with Git?

Each PR is based on the branch of the previous one: feat-1 ← feat-2 ← feat-3. If a lower PR changes, the ones above must be rebased, and git rebase --update-refs does that in one command. Merging goes from the bottom up.

📖 Answer

An example: first the new PaymentGateway interface, then the Stripe implementation, then the controller.

git switch -c pay/1-interface main
# ... commit
git switch -c pay/2-stripe
# ... commit
git switch -c pay/3-api
# ... commit

The base branches in the PRs: pay/1 → main, pay/2 → pay/1, pay/3 → pay/2. In each one, the reviewer sees only their own part.

If you make a fix on pay/1 after review, all the branches above go stale. In Git 2.38+:

git switch pay/3-api
git rebase -i --update-refs main
git push --force-with-lease origin pay/1-interface pay/2-stripe pay/3-api

--update-refs also updates the pay/1 and pay/2 pointers along the way. If you set git config --global rebase.updateRefs true, you do not have to type it every time.

A trap: when pay/1 is squash-merged, pay/2's history still has the old commits. You have to move it with git rebase --onto main pay/1-old pay/2-stripe, otherwise the code that is already merged shows up again in the PR diff.

I try to keep the stack depth to 3-4 at most. Beyond that it becomes unmanageable.