如何生成Git风格三向Diff文件,标记所有含可合并项的差异?
生成Git风格全差异三向Diff文件的可行方案
需求概述
需要基于三个文件(基准文件base、本地修改文件mine、远端修改文件yours)生成三向Diff文件,要求:
- 公共内容原样保留
- **所有差异(包括可自动合并的差异)**都用Git风格冲突标记(
<<<<<<<、|||||||、=======、>>>>>>>)包裹 - 输出过程无需人工干预
已验证不可行的方案
git diff:仅支持双向对比,无法处理三向文件输入git merge-file:自动合并可兼容差异,不会为这类差异添加冲突标记diff3 -m:类似git merge-file,仅标记无法自动合并的冲突,忽略可合并差异diff3:虽能显示所有差异,但输出格式不符合Git冲突标记要求diff3 -A:无法完整显示所有差异,且不标记可合并差异
可行方案:使用awk脚本转换diff3输出
无需从零编写处理逻辑,可借助现成的awk脚本将diff3的输出转换为符合要求的Git风格冲突格式。
操作步骤
- 执行
diff3命令获取完整三向差异输出:
diff3 mine.txt base.txt yours.txt > diff3_output.txt
- 创建名为
convert_diff3.awk的脚本文件,内容如下:
#!/usr/bin/awk -f BEGIN { state = "common" } /^====$/ { print "=======" next } /^@@/ { next } /^1:/ { if (state != "mine") { if (state == "base") print "=======" else if (state == "yours") print ">>>>>>>" print "<<<<<<<" state = "mine" } print substr($0, 3) next } /^2:/ { if (state != "base") { if (state == "mine") print "|||||||" else if (state == "yours") print ">>>>>>>" print "|||||||" state = "base" } print substr($0, 3) next } /^3:/ { if (state != "yours") { if (state == "mine") print "|||||||" else if (state == "base") print "=======" print "=======" state = "yours" } print substr($0, 3) next } { if (state != "common") { print ">>>>>>>" state = "common" } print $0 } END { if (state != "common") print ">>>>>>>" }
- 运行脚本处理diff3输出,得到最终符合要求的Diff文件:
awk -f convert_diff3.awk diff3_output.txt > final_diff.txt
该脚本会自动将diff3输出的各文件差异段用Git冲突标记包裹,包括可合并的差异,完全满足需求且无需人工干预。
内容的提问来源于stack exchange,提问作者mernst
相关产品推荐
相关产品推荐

