Avoiding conflicts in git when merging a squashed commit from main into feature branch
Asked Answered
C

1

7

Consider the following practice:

  • A developer branches from main and creates as many commits as needed in a feature branch
  • Once the feature is completed, all commits are squashed and merged into the main branch (for instance, think of a GitHub's "Squash and merge" button)

And now this is a use case that interests me:

  1. Create and work on a feature1 branch
  2. Create a feature2 branch starting from the last commit of the feature1 branch (see the C commit in the image below)
  3. Squash and merge feature1 into main (see the commit G)
  4. Merge this newly created commit G into the feature2 branch
  5. Continue working on the feature2 branch

In other words, the merge of G into the feature2 branch in step 4 looks like this:

user@host:~/repo (main)$ git checkout feature2
user@host:~/repo (feature2)$ git merge main     # merge G into feature2

merge conflicts after squash and merge

Often, this merge (see the commit H) results in a number of merge conflicts.

How to completely eliminate these conflicts?

The easiest solution I can think of is the following (see the image below):

user@host:~/repo (main)$ git checkout feature1
user@host:~/repo (feature1)$ git merge main         # merge G into feature1; essentially, an empty commit
user@host:~/repo (feature1)$ git checkout feature2
user@host:~/repo (feature2)$ git merge feature1     # merge G' into feature2

overcoming merge conflicts after squash and merge

To put it another way, instead of merging G into feature2 directly, we first merge G into feature1 and then merge feature1 into feature2.

Is there a simpler approach?

Chafee answered 2/7, 2021 at 18:27 Comment(0)
W
4

I would rebase feature2 onto main just after that feature1 has been squashed and merged.

Something like:

git checkout feature2
git rebase --onto main C feature2

This will rebase commits from C (exclusive) to feature2 (inclusive) on top of main.

So instead of merging main into feature2(red), feature2 moves to be on top of main(green). enter image description here

However I'm not sure it qualifies as simpler. And one drawback is that you will get commits of main in the resulting branch (but that's what you want ultimately I guess).

Personal opinion: do not use squash in the first place if the branch is used by other people as reference.

Walcoff answered 2/7, 2021 at 18:59 Comment(2)
I could easily imagine the feature1 branch being deleted after it is merged to main, so we may no longer have easy access to it. This argues for rebasing being a good option.Jesus
Yeah, good simple option. One potential drawback: if feature2 has been already pushed upstream, we would need to --force after this rebase.Chafee

© 2022 - 2024 — McMap. All rights reserved.