Home > database >  How to remove original branch's commits from my new branch after the original branch has been m
How to remove original branch's commits from my new branch after the original branch has been m

Time:05-25

Let's say I have one MR up - merging branch1 into main

  • I checkout a new branch from branch1 and call it branch2.
  • branch2 relies on branch1s changes but is big enough for its own branch.
  • The MR for branch1 gets squash merged into main.
  • I rebase branch2 onto main and notice my rebase is trying to include all the commits from branch1

Do I simply skip these commits? Am I looking for something other than rebasing? I'm sorry if this has been asked - I've tried to find the answer but am not sure the best way to search for it.

CodePudding user response:

I rebase branch2 onto main and notice my rebase is trying to include all the commits from branch1

Then you did the rebase wrong. Unfortunately you didn't show the command you used, but you probably said git rebase main. That was wrong! The correct syntax would be:

git rebase --onto main branch1 branch2

That does exactly what you want: it snips the branch2-only commits off the end and shoves them onto the end of main.

To understand why what you did is wrong, you need to realize that Git doesn't think of branches the way you do. Let's say you had this:

A -- B -- C -- D (main)
 \
  W -- X (branch1) -- Y -- Z (branch2)

You probably think branch2 is just Y and Z. But to Git, branch2 is just a name for Z alone. So it has to decide where to snip at the start of the rebase, and in the absence of other info, it will decide to snip starting at W. The syntax I showed you tells it to snip starting at Y.


That, however, does not tell you what to do now to get rid of the commits W and X that have come along for the ride in your incorrect rebase result:

A -- B -- C -- D (main) -- W -- X -- Y -- Z (branch2)
                          [WRONG!]

The answer is git rebase -i main. This is an interactive rebase and you can just delete W and X from the list it gives you.

  •  Tags:  
  • git
  • Related