How to rebase after squashing commits in the original branch?

Viewed 9287

I have

A--B--C master
       \
        D branch0

Then I squash B and C into B'. How do I rebase branch0 such that it looks like this:

A--B' master
    \
     D branch0
3 Answers

I've run into a similar problem when using squash-merge on PRs when you have branches off of branches.

My common example is if I have one feature branch (feature-a). I push some commits to that branch. Then I create another feature branch off of that (feaure-b-off-a). Then I squash-merge feature-a into main, I'll see duplicate commits in the PR of feature-b-off-a into main.

To fix this, we can use a rebase --onto like the accepted answer, here. But the manual work of that is finding C (I refer to common-ancestor below). Rewritten another way:

git rebase --onto main common-ancestor feature-b-off-a

  • Take all the commits between common-ancestor and feature-b-off-a and rebase them onto main

Fortunately, git has a way of finding the common ancestor between two branches:

git merge-base feature-b-off-a feature-a


TL;DR:

# This will print out the 'common-ancestor' commit between the commits/branches causing the problem
git merge-base feature-b-off-a feature-a
# Take all the commits between common-ancestor and feature-b-off-a and rebase them onto main
git rebase --onto main <common-ancestor> feature-b-off-a
# Then you'll need to force push since it's a rebase
git push -f origin feature-b-off-a

Your PR into main should now only show the new commits.


Bonus git-alias

Note: This assumes your flow is squash-merging both into main

git config --global alias.rebase-onto '!f() { git rebase --onto main $(git merge-base "$1" "$2") "$1"; }; f'

Which you'd call with:

git rebase-onto feature-b-off-a feature-a
# Then you'll need to force push since it's a rebase
git push -f origin feature-b-off-a
Related