Home > other >  How to avoid merge conflicts when merging several branches?
How to avoid merge conflicts when merging several branches?

Time:12-11

For our project, we have a main branch. We each also work on our own feature branches. On a couple of occasions, I have made a feature branch, say feature1, off of main, finished up, pushed it to GitHub, and created a pull request. Before the pull request is approved, I have already branched off of feature1 into feature2 and I'm working on something new. Then, I push it up to GitHub and make a pull request, again. When my first pull request, feature1, gets approved, I then get merge conflicts in feature2.

  1. Why does this happen? I haven't changed anything in feature1, just added on top of it.
  2. Is there a proper way to solve this issue? I tried rebasing but that has been a very long and tedious process with fixing issues at each commit.
  3. I was thinking that maybe instead of making a pull request from feature2 into main, it should be into feature1. Would that fix it?
  4. Is there a better practice to do what we are trying to accomplish?

CodePudding user response:

Do you use "squash merges" or "rebase and fast-forward" when merging your Oil Requests?

If so, either:

  • Stop using that and use a "true merge" / "merge commit"; or
  • Never base a new branch on an unmerged Pull Request

The reason is that whenever you squash or rebase a branch, you are throwing away the commits that were originally on that branch, and creating new ones with no recorded relationship to the originals. If you've based later work on those original commits, git thinks those commits are still unmerged, and when you try to merge the later work, it tries to apply changes that have already been made, pretty much guaranteeing some confusing conflicts.

You can recreate the second branch by rebasing it onto the squashed / rebased commits on main, but the more often you "chain" branches together (starting from a previous feature rather than main) the more work you make for yourself keeping them in sync.

If you use a true merge, git knows how the branches relate, and not to apply the same changes twice.

  • Related