多次应用gitdiff/patch

Apply git diff/patch multiple times

使用 git 流程我创建了一个新分支,newFunction,离开 develop 分支。 我将 newFunction 添加到示例 class:

class ExampleClass
{

    public function exampleFunction(){
        return "example";
    }

    public function newFunction(){
        return "new";
    }

}

假设我将它合并到 develop,几个月后我回来,我的 class 看起来像这样。

class ExampleClass
{

    public function exampleFunction(){
        return "example";
    }

    public function anotherFunction(){
        return "another";
    }

    public function yetAnotherFunction(){
        return "yetAnother";
    }

    public function newFunction(){
        return "new";
    }

}

是否可以在developnewFunction之间的那个时间点应用diff?可能使用 git patch 或某种黑魔法。 所以我 运行 一个神奇的 git something 命令,我最终得到了这样的东西:

class ExampleClass
{

    public function exampleFunction(){
        return "example";
    }

    public function anotherFunction(){
        return "another";
    }

    public function yetAnotherFunction(){
        return "yetAnother";
    }

    public function newFunction(){
        return "new";
    }

    public function newFunction(){
        return "new";
    }
}

如果我再做一次,我会得到这个:

class ExampleClass
{

    public function exampleFunction(){
        return "example";
    }

    public function anotherFunction(){
        return "another";
    }

    public function yetAnotherFunction(){
        return "yetAnother";
    }

    public function newFunction(){
        return "new";
    }

    public function newFunction(){
        return "new";
    }

    public function newFunction(){
        return "new";
    }   
}

等 我知道它当前生成的代码不正确,因为函数中的名称相同。 例如,我会用它在遗留系统中生成样板代码。

回答

我认为您正在寻找的命令是 git apply。假设 newFunction 分支上的最后一次提交只为 newFunction 添加了四行,您可以使用以下命令在 develop 分支上应用相同的更改:

git checkout develop
git diff newFunction^ newFunction | git apply --3way
# "newFunction^" means the second last commit on newFunction branch

Git apply 将在此处尝试将在 newFunction 分支上的最后一次提交中所做的相同更改应用到 develop 分支。

当使用测试存储库进行测试时,为每次提交添加一个函数,上述 git 应用没有完全应用。但是当使用三向模式时,它会让结果保持打开状态以供手动解析,例如git status 将为文件显示 both modifiedgit ls-files -u 将显示类似

的内容
100644 21ecaba537582661c82c9dd2dff920a88a4b69a1 1   file.php
100644 56728941868d309cc06a49a8c49afc72cb0285b7 2   file.php
100644 0bbcab178802667c0228e424ce84f4c13a2b4c94 3   file.php

关于处理合并冲突的额外提示

默认的 git 行为是为我发现很难处理的合并冲突部分插入一些文本标记。我更喜欢使用 KDiff3 以图形方式合并,并使用 ls-files 的输出,我们可以获取所有相关版本并创建具有我们 运行 kdiff3 上的相应内容的文件。例如

$ git cat-file blob 21ecaba537582661c82c9dd2dff920a88a4b69a1 > file1.php
$ git cat-file blob 56728941868d309cc06a49a8c49afc72cb0285b7 > file2.php
$ git cat-file blob 0bbcab178802667c0228e424ce84f4c13a2b4c94 > file3.php
$ kdiff3 -o file_merged.php file1.php file2.php file3.php
$ mv file_merged.php file.php
$ git add file.php
$ git commit -m "Manually resolved git apply result"

有两个手动diff比对不难解决:

我个人创建了一个脚本,其核心执行上述命令来解决 git 冲突,虽然有点复杂,但我一直在使用它,我喜欢 kdiff3。