【问题标题】:run git merge algorithm on two individual files在两个单独的文件上运行 git 合并算法
【发布时间】:2012-02-03 02:29:03
【问题描述】:

我想在 git repo 中的两个任意文件上利用 git-merge 算法。这是我的工作目录:

folder/
    file1
    file2

file1 和 file2 相似,但我想看看 git 如何将它们合并,就好像它们是同一文件的不同版本一样。换句话说,我想要这样的东西:

git merge-files file1 file2 > merge_of_file1_file2

有没有办法做到这一点?

【问题讨论】:

    标签: git


    【解决方案1】:

    这没有任何意义,因为您没有提供共同的祖先。但是,如果你有一个,你可以使用:

    git merge-file <current-version> <common-ancestor> <other-version>
    

    这会将结果放在当前版本文件中;如果您想在其他地方使用它们,请使用:

    git merge-file -p <current> <common> <other> > <dest>
    

    它需要共同的祖先提供一些东西来考虑相对的变化。您可以通过从存储库的历史记录中提供一个空文件或其中一个旧版本的副本来破解它,但结果的质量将取决于您选择一个共同祖先的程度,因为它合并了两个差异,在那个和每个新版本之间。只有当两者非常相似(许多运行至少三个相同的行)时,一个空文件才能正常工作。

    没有它,你真正能做的就是看看差异:

    git diff --no-index file1 file2
    

    【讨论】:

    • 使用其中一个文件的副本作为共同祖先怎么样?
    • @CarlG,假设 file2 比 file1 多一行。如果您选择 file1 作为祖先,则此行被解释为添加,因此合并将是文件 2。如果您选择 file2 作为锚点,则该行被解释为删除并且您得到 file1 作为结果。
    • @CarlG 换一种说法,如果你从A开始,一侧改为B,另一侧保持为A,那么合并后的结果显然是B。
    • common-ancestor 应该是一个空文件吗?
    • 如果其中一个文件是祖先文件可能会很好用?
    【解决方案2】:

    对于你想要做的事情:

    touch file3  #empty
    git merge-file file1 file3 file2
    

    这将以file3(空文件)为基础进行file1和file2的三向合并。

    请注意,这将写入 file1。如果不需要,您当然可以执行以下操作:

    touch file3
    cp file1 merge_of_file1_file2
    git merge-file merge_of_file1_file2 file3 file2
    

    【讨论】:

    • 我验证了它的工作原理(通过 Git Bash)。这是我编写的 bash 函数,用于将其封装到单个命令中:``` function merge() { touch merge_result git merge-file $1 merge_result $2 rm 合并结果 } ```
    • 这显示整个文件已更改而不是更改的行
    【解决方案3】:

    只是为了补充 manojlds 的答案,这是一个不错的完整功能,您可以将其添加到您的 .bashrc 中。它的好处是可以在“合并冲突”块中正确识别两个文件的名称。

    merge() {
      local ext
      [ $# -ne 2 ] && echo "Error: Need exactly two args." && return 1
      [[ ! -r $1 || ! -r $2 ]] && echo "Error: One of the files is not readable." && return 1
      if [[ ${1##*/} =~ '.' || ${2##*/} =~ '.' ]]; then
        [ ${1##*.} != ${2##*.} ] && echo "Error: Files must have same extension." && return 1
         ext=.${1##*.}
      fi
      touch tmp$ext # use empty file as the 'root' of the merge
      cp $1 backup$ext
      git merge-file $1 tmp$ext $2 # will write to file 1
      mv $1 merge$ext
      mv backup$ext $1
      rm tmp$ext
      echo "Files merged into \"merge$ext\"."
    }
    

    【讨论】:

      【解决方案4】:

      您也可以为此使用 KDiff3。

      • 选择文件一
      • 选择文件二

      然后合并:)

      http://kdiff3.sourceforge.net/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-07
        • 2015-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        相关资源
        最近更新 更多