Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rebase only part of a branch

Tags:

git

I've got two branches (and master). Branch 2 is based on Branch 1 is based on master. I've submitted Branch 1 for review, it had some changes, I rebased some of those changes into history and merged the result into master.

Now I need to rebase Branch 2 on top of master to prepare it for review/merge.

The problem is that Branch 2 still contains the original commits of Branch 1, which don't exist anymore, so git gets confused. I tried rebase -i to drop the original commits of Branch 1, but the commits of Branch 2 don't base on top of master-before-branch-1.

What I need to do is take branch 2, drop some commits, and rebase just the remaining commits on top of master in a single operation. But I only know how to do these two operations in two distinct steps.

How can I rebase part of my branch onto another branch, dropping all commits that are not in common ancestry, except the ones I specify (e.g. from HEAD~2 up)?

Here's the current state:

master                     new branch 1 - - - - - - - - - - - | - - - - - - - - -     \      \   branch 1       \ _ _ _ _ _ _ _                      \                       \     branch 2                        \ _ _ _ _ _ _ _ 

What I want to end up with:

master            new branch 1     - - - - - - - | - - - - - - - - - -                                    \                                     \                                      \                                       \    branch 2                                        - - - - - - - - -  
like image 981
Puppy Avatar asked Jan 21 '16 14:01

Puppy


People also ask

What does it mean to rebase onto a branch?

From a content perspective, rebasing is changing the base of your branch from one commit to another making it appear as if you'd created your branch from a different commit. Internally, Git accomplishes this by creating new commits and applying them to the specified base.

Why you should not use rebase?

Rebasing can be dangerous! Rewriting history of shared branches is prone to team work breakage. This can be mitigated by doing the rebase/squash on a copy of the feature branch, but rebase carries the implication that competence and carefulness must be employed.


1 Answers

The actual command would be:

git rebase --onto newbranch1 branch1 branch2 

That will replay on top of new_branch1 all commits after branch1 up to branch2 HEAD.

As Joshua Goldberg puts it in the comments:

 git rebase --onto <place-to-put-it> <last-change-that-should-NOT-move> <change to move> 

As Denis Sivtsov illustrates in the comments:

If you need only replay the last commit only from branch, in this case work:

git rebase --onto newbranch1 HEAD~1 
like image 124
VonC Avatar answered Sep 28 '22 02:09

VonC