Search code examples
gitgit-merge

How does git decide when there are merge conflicts?


I have a question about how git works for a certain case. These are the steps, and assume these are the only changes done to the repo:

  1. initially I have branch master
  2. I create a new branch "feature-1" off of master
  3. I add several commits to "feature-1" branch
  4. I create a new branch "feature-2" off of "feature-1"
  5. I add several commits to "feature-2" branch
  6. I merge "feature-1" branch into master -
  7. I add several more commits to this "feature-2" branch

Now, when I want to merge "feature-2" into "master", I expect not to have any conflits, because all the commits that are merged into "master" from "feature-1" branch are already in "feature-2" branch. So "feature-2" should be no different than a branch created off of "master" after step 6

However, when I want to merge "feature-2" into "master", I get merge conflicts, git thinking all changes done in "feature-1" conflict with what's in "feature-2", whereas they come from exactly the same commits, and

commits in "feature-2" = (all commits in "feature-1") + some more commits.

What's causing git into thinking there are conflicts in this case? And maybe in general, how does git decide when there are merge confclits?


Solution

  • There are 2 things you need to now to get whow git works for conflicts:

    1. Actually git uses the commits to check if branchs are equals or not.
    2. All changes are commits in someway (merges are in it too)

    Knowing that things, let check your example again.

    lets suppose that master is like tat:
    Branch: master
    Commits: Commit-A

    And than you create feature-1 and commit one thing. It will be like that:
    Branch: feature-1
    Commits: Commit-A (From master), Commit-B

    From feature-1 you create feature-2 and commit another thing. It will be like that:
    Branch: feature-2
    Commits: Commit-A (From master), Commit-B (From feature-1), Commit-C

    Now, you merge Feature-1 into master, lets check master again:
    Branch: master
    Commits: Commit-A, Commit-B (From feature-1), Commit-D (commit created by merge)

    Can you see that the "merge commit" that exists in master do not exists in Feature-2 even Feature-2 already have the code? the merged branch branch may have the "merge information" to be merged into master, even it do not make difference in the code.