Sub topic 1
Moving a Branch to a New Base with `git rebase --onto`
Prerequisites
This chapter assumes you know how to commit, create branches, switch branches, and read a commit graph. A branch is a movable pointer to one commit. A commit points to its parent commit, so Git can follow the history behind each branch.
Branches as Pointers into a Commit Graph
Suppose topic was created from main and has two new commits:
The names main and topic do not contain commits. They point to commits. Moving a branch changes which commit its name points to.
What a Plain Rebase Replays
A plain rebase moves commits from the current branch onto another branch. In this example, Git finds commits reachable from topic but not from main, then copies those commits onto the tip of main.
git switch topic
git rebase mainThe copied commits receive new commit IDs because their parent changes. The original commits remain temporarily available through the reflog.
This operation is a special case of --onto:
git rebase --onto main main topicThe first main is the new base. The second main is the upstream boundary. topic is the branch to move.
How the Upstream Argument Selects Commits
The upstream argument defines where the replay range begins. Git replays commits in upstream..branch: commits reachable from the branch but not reachable from upstream.
For example, if topic was based on next, this command moves only topic's own commits onto main:
git rebase --onto main next topicGit leaves the commits shared with next out of the replay.
Reading and Writing `git rebase --onto`
Read the three arguments as:
| Argument | Meaning |
|---|---|
| `main` | New base where copied commits are placed |
| `next` | Upstream boundary that excludes earlier commits |
| `topic` | Branch whose commits are replayed |
The general form is:
git rebase --onto <new-base> <upstream> <branch>If you omit <branch>, Git uses the current branch. Check the range first, then inspect the graph after the operation with git log --oneline --graph --decorate.
Exercise
Which commits does git rebase --onto main next topic replay?
Show answer
Commits reachable from topic but not from next, placing copies of them on main.