gitgit-mergebranching-and-merginggit-merge-conflictgit-squash

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


Consider the following practice:

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?


Solution

  • 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.