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

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

我们正在不同分支上处理一个文件。

合并后,最终代码变得错误,即使在合并前它在每个分支上都运行良好。

我将此处给出的公认答案用作 branching/merging 策略:。

有没有我遗漏的步骤?

我在 master 分支上有文件。 示例代码

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

我从这里分支到 newBranch。

git checkout -b newBranch

在 newBranch 上,我编辑代码以打印 a 的值。

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

在 master 上,其他一些开发人员删除了声明变量 a.

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

当我将newBranch合并回master时,变量a的声明会丢失,打印语句会报错。请注意,此合并不会产生任何合并冲突。

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

合并后的代码看起来像

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

将 master 拉入 newBranch 并在将其合并回 master 之前进行测试是一个好习惯吗?

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

是的。在这种情况下,代码之后不起作用是完全合理的。毕竟,有人删除了一些代码,而你添加了一段代码。更改不在同一位置,因此不存在冲突。 Git 不是编译器,不知道更改之间的关系,因此应用了两个更改,您必须手动解决此问题。

您始终可以使用 git rerere 将合并结果应用于所有给定的分支。

git rerere 只需记录您解决冲突的方式,然后当相同的冲突出现在不同的分支上时,它会简单地应用您创建的补丁来解决所有冲突。

阅读更多

git rerere
Fix conflicts only once with git rerere