Sub topic 3
Moving a Range of Commits with `--onto`
This chapter assumes you know git switch, git commit, git log, single-branch rebasing, and pull requests. You also need Git 2.38 or newer.
Moving a range of commits with `--onto`
git rebase --onto selects a range of commits and replays it on a new base. Its general form is:
git rebase --onto <new-base> <old-base> <branch>Git replays commits reachable from branch but not from old-base. The commit named by old-base is excluded.
For a stack where feature-3 is based on feature-2, which is based on feature-1, this command moves the commits after feature-1 onto origin/main:
git fetch origin
git switch feature-3
git rebase --update-refs --onto origin/main feature-1--update-refs also moves intermediate local branches whose tips are rewritten. Without it, feature-2 can remain attached to the old commit history.
Restacking after a squash merge
A squash merge creates one new commit on main. That commit contains the changes from feature-1, but it does not preserve feature-1's commit IDs. Therefore, Git cannot treat the old branch as an ordinary ancestor of the new main.
After fetching, use the old bottom branch as the exclusion point:
git fetch origin
git switch feature-3
git rebase --update-refs --onto origin/main feature-1Git replays only the commits in feature-1..feature-3. If feature-1 was already merged by squash, do not replay its commits again.
Conflicts in the middle of a stack
A conflict can stop the rebase while Git rewrites an intermediate branch. Resolve the files, stage them, and continue:
git status
# edit conflicted files
git add path/to/resolved-file
git rebase --continueUse git rebase --abort to return to the pre-rebase state. If the conflict belongs to a change that later branches depend on, test the stack before continuing.
Undoing a bad restack with the reflog
The reflog records earlier positions of local branch references. Inspect it, then move a branch back to its previous entry:
git reflog show feature-2
git branch -f feature-2 'feature-2@{1}'Check the graph afterward with git log --oneline --decorate --graph.
Habits that keep stacks manageable
- Keep each branch focused and short.
- Rebase the stack before asking for review.
- Push rewritten branches with
--force-with-lease. - Test lower branches before testing dependent branches.
- Record the branch order in the pull request description.
Exercise
Which commits does git rebase --onto origin/main feature-1 feature-3 replay?
Show answer
It replays the commits reachable from feature-3 but not from feature-1, placing them on origin/main.