You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Git补丁中的C/C++代码自动添加宏包裹变更代码?

自动为Git补丁添加C/C++条件宏的实现方案

目前Git没有内置工具直接实现该需求,你可以通过自定义脚本处理补丁内容,自动将变更代码用MODIFIED宏包裹,具体实现如下:

核心思路

  • 替换行:将原删除行(-开头)和新增行(+开头)转换为#ifdef MODIFIED包裹新增代码、#else保留原代码的结构
  • 单独新增行:用#ifdef MODIFIED包裹新增内容
  • 单独删除行:用#ifndef MODIFIED保留原删除内容

Python实现脚本

#!/usr/bin/env python3
import sys

def process_patch(patch_content):
    lines = patch_content.splitlines()
    output = []
    i = 0
    line_count = len(lines)
    while i < line_count:
        current_line = lines[i]
        # 保留diff头部信息
        if current_line.startswith(('diff --git', 'index', '---', '+++', '@@')):
            output.append(current_line)
            i += 1
            continue
        
        # 处理替换行:-旧行 +新行的配对
        if i + 1 < line_count and current_line.startswith('-') and lines[i+1].startswith('+'):
            old_content = current_line[1:]
            new_content = lines[i+1][1:]
            output.extend([
                "+#ifdef MODIFIED",
                f"+{new_content}",
                "+#else",
                f" {old_content}",
                "+#endif"
            ])
            i += 2
        # 处理单独新增行
        elif current_line.startswith('+'):
            content = current_line[1:]
            output.extend([
                "+#ifdef MODIFIED",
                f"+{content}",
                "+#endif"
            ])
            i += 1
        # 处理单独删除行
        elif current_line.startswith('-'):
            content = current_line[1:]
            output.extend([
                "+#ifndef MODIFIED",
                f" {content}",
                "+#endif"
            ])
            i += 1
        # 保留上下文行
        else:
            output.append(current_line)
            i += 1
    return '\n'.join(output)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法: ./patch_macro.py <补丁文件路径>")
        sys.exit(1)
    with open(sys.argv[1], 'r') as f:
        patch_text = f.read()
    print(process_patch(patch_text))

使用步骤

  1. 将上述代码保存为patch_macro.py
  2. 赋予脚本执行权限:
    chmod +x patch_macro.py
    
  3. 处理目标补丁文件:
    ./patch_macro.py original.patch > modified.patch
    

效果验证

针对你提供的示例补丁,处理后将生成如下内容(以第一种格式为例):

diff --git a/test.c b/test.c
index a35d23a..668d2e0 100644
--- a/test.c
+++ b/test.c
@@ -1,6 +1,10 @@
 #include <stdio.h>

 int main() {
+#ifdef MODIFIED
+    printf("New line");
+#else
     printf("Old line");
+#endif
     return 0;
 }

注意事项

  • 脚本默认处理单行变更,如需支持多行连续变更,可扩展逻辑识别连续的-/+行块
  • 可自行修改脚本中的MODIFIED宏名称为自定义标识
  • 若补丁包含复杂格式(如二进制文件、非C/C++代码),需添加过滤逻辑仅处理目标文件

内容的提问来源于stack exchange,提问作者Satyajit Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 23:50:02