rebase#
–onto#
The --onto option allows you to take a range of commits from one branch and “transplant” them onto another, even if they do not share a direct parent-child relationship.
Usage#
$ git rebase --onto <newbase> <upstream> <branch><newbase>: The branch or commit where you want the changes to land.<upstream>: The reference point to exclude history from. Git replays the range<upstream>..<branch>, meaning everything reachable from<branch>but not reachable from<upstream>.<branch>: The branch containing the commits you want to move (optional if currently checked out).
How it differs from standard rebase#
A standard git rebase <upstream> automatically identifies the common ancestor between <upstream> and the current branch. It then replays all commits that come after that ancestor onto the tip of <upstream>.
--onto gives you surgical control by letting you manually specify the “cut-off” point (<upstream>) independently of where the commits will land (<newbase>).
Technical Note:
git rebase <newbase> <branch>is essentially a shorthand forgit rebase --onto <newbase> <newbase> <branch>. Conceptually, both commands replay the range<newbase>..<branch>. Standard rebase is just “smarter” because it uses the common ancestor as the default cut-off if you only provide one argument.
Example: Feature on Feature#
Imagine you branched feature-b off feature-a (but from an earlier commit, not the tip), and now you want to move feature-b directly onto main, skipping the commits that belong to feature-a.
Initial state:
graph LR
A((A)) --- B((B)) --- C((C))
C --- Main[main]
B --- D((D)) --- E((E))
E --- FeatureA[feature-a]
D --- F((F)) --- G((G))
G --- FeatureB[feature-b]To move feature-b directly onto main while excluding feature-a specific commits:
$ git rebase --onto main feature-a feature-b- Git looks for commits in
feature-bbut not infeature-a(the rangefeature-a..feature-b). - In this case, it identifies
FandG. - It replays them on top of
main.
Result:
graph LR
A((A)) --- B((B)) --- C((C))
C --- Main[main]
B --- D((D)) --- E((E))
E --- FeatureA[feature-a]
C --- F'((F')) --- G'((G'))
G' --- FeatureB[feature-b]Example: Result of standard rebase#
If you were on feature-b and ran a standard git rebase main instead of using --onto, Git would first find the common ancestor between main and feature-b. In our generalized example, this is commit B. It would then move all commits reachable from feature-b but not from main (the range main..feature-b). This includes commit D, which technically belongs to feature-a’s path.
$ git rebase main feature-bResult (Polluted History):
graph LR
A((A)) --- B((B)) --- C((C))
C --- Main[main]
B --- D((D)) --- E((E))
E --- FeatureA[feature-a]
C --- D'((D')) --- F'((F')) --- G'((G'))
G' --- FeatureB[feature-b]Notice that feature-b now contains a duplicate of commit D (D'). This is often undesirable if D belongs strictly to the feature-a logical unit. --onto allows you to surgically pick only the unique work in feature-b.