Sub topic 3
Removing Commits and Restacking Branches with `git rebase --onto`
Assume you know how to commit, switch branches, inspect logs, and use plain git rebase. A branch is a movable pointer to a commit. Rebasing changes that pointer and creates replacement commits.
Removing Commits from the Middle
The command form is:
git rebase --onto <new-base> <upstream> <branch>Git replays commits reachable from branch but not from upstream, placing them after new-base. This lets you exclude a middle range.
Suppose topicA contains E-F-G-H-I-J. To remove F and G, replay only H, I, and J after E:
git switch topicA
git rebase --onto topicA~5 topicA~3 topicAHere, topicA~5 names E, and topicA~3 names G. The range G..topicA contains H, I, and J, so the result is E-H'-I'-J'.
Restacking After a Squash Merge
A squash merge creates one new commit in main. Git does not recognize that commit as equivalent to the original commits on feature-a. If feature-b was based on feature-a, rebase it using feature-a as the upstream:
git fetch origin
git switch feature-b
git rebase --onto origin/main feature-a feature-bGit skips the original feature-a commits and replays only feature-b's commits onto origin/main.
Recovery and Publishing
A completed rebase can be undone with ORIG_HEAD:
git reset --hard ORIG_HEADIf another command overwrote ORIG_HEAD, find the old branch tip in the reflog:
git reflog
git reset --hard feature-b@{1}Rebasing changes commit IDs. If the branch is already remote, publish it with:
git push --force-with-lease origin feature-b--force-with-lease refuses to overwrite remote commits you have not fetched. Avoid rewriting a shared branch unless everyone agrees.
Updating a Branch Stack
With Git 2.38 or later, --update-refs moves other local branches that point into the rewritten range:
git rebase --update-refs --onto main old-base feature-bThis is useful when several dependent branches form a stack.
Exercise
Which command removes F and G from E-F-G-H-I-J while keeping H, I, and J?
Show answer
git rebase --onto topicA~5 topicA~3 topicA