How to merge a git branch properly when a file is changed on multiple branches?

We are working on a file on different branches.

After merging, the final code becomes erroneous, even though it works fine on each of the branches before merging.

I'm using the accepted answer given here as a branching/merging strategy: https://stackoverflow.com/a/5602109/4746692.

Is there a step that I'm missing?

I have file on master branch. Sample code

public class Test {
  public static void main(String[] args) {
    int a = 1;
    int b = 2;
    System.out.println(b);
  }
}

I branch out from here to newBranch.

git checkout -b newBranch

On the newBranch, I edit the code to print the value of a .

public class Test {
  public static void main(String[] args) {
    int a = 1;
    int b = 2;
    System.out.println(b);
    System.out.println(a);
  }
}

While on master, some other developer removes the statement declaring the variable a .

git checkout master
public class Test {
  public static void main(String[] args) {
    int b = 2;
    System.out.println(b);
  }
}

When I merge the newBranch back to master, the declaration of variable a will be missing, and the print statement will throw an error. Note that this merging doesn't give any merge conflict.

git checkout master
git pull origin master
git merge --no-ff newBranch

The merged code looks like

public class Test {
  public static void main(String[] args) {
    int b = 2;
    System.out.println(b);
    System.out.println(a);
  }
}

Is it a good practice to pull master into newBranch and test before merging it back to master?


"Is it a good practice to pull master into newBranch and test before merging it back to master?"

Yes. And in this case, it makes perfect sense that the code doesn't work afterwards. After all, somebody removed some code, and you added a piece of code. The changes are not in the same locations, so there is no conflict. Git is not a compiler and is not aware of the relation between the changes, so both changes are applied, and you'll have to solve this manually.


You can always use the git rerere to apply the merge results to all the givenm branches.

git rerere simply record the way you have resolved the conflict and then when the same conflicts appear on different branches it will simply apply the patch you created to resolve all the conflicts.

Read more

git rerere
Fix conflicts only once with git rerere

链接地址: http://www.djcxy.com/p/49318.html

上一篇: 总是使用git pull rebase是否安全?

下一篇: 如何在多个分支上更改文件时正确合并git分支?