How to drop all commits between two commits without interactive rebase

Viewed 135

I have a branch B based off branch master, I want to rebase B onto branch A instead.

My problem is branch A is based off an earlier commit in master than B, so when I try and rebase B onto A it's bringing all the commit history of master since A was split from it.

Normally I would solve this problem with an interactive rebase and manually drop the unwanted commits, however in this case there are too many commits to handle in this way. What I want is a command that will allow me to drop all commits in branch B between it's last common ancestor with A and the tip of master.

IE. A command that drops commits 2-5 in the diagram below from branch B

* 099b4f7 (HEAD -> master) commit_6
| * a4b6a50 (B) some other commit
|/  
* 80cfbbc commit_5
* 49c40c9 commit_4
* 2923714 commit_3
* f78ee3c commit_2
| * f6d3601 (A) some commit
|/  
* df753e1 commit_1
2 Answers

This is exactly the sort of situation the --onto option to rebase is for:

git switch B
git rebase --onto A master

This will write B's commits onto A starting from the child of the latest common commit between B and master.

# start from branch_B
git checkout branch_B

# back it up
git branch backup_B

# make it point to branch_A
git reset --hard branch_A

# bring all commits from branch_B not already on master
git cherry-pick master..backup_B

It will bring on branch_A every commit from branch_B that are not reachable from master, so it won't bring your commits 2, 3 and 4.

Related