【问题标题】:Operate on git diff output操作 git diff 输出
【发布时间】:2014-07-18 00:25:19
【问题描述】:

如果我想围绕它编写脚本并编辑实际的新/更新代码行,是否可以对 git diff 输出进行操作?

假设我有 git 跟踪的文件 'foo'

富:

line 1
line 2
line 3
line 4

我编辑它(在第 3 行添加“(编辑)”)和

git diff foo

给我

workspace@workspace:~/gitRepo/$ git diff foo
diff --git a/foo b/foo
index 9c2a709..30fb870 100644
--- a/foo
+++ b/foo
@@ -1,4 +1,4 @@
line 1
line 2
-line 3
+line 3 (edit)
line 4

而且我希望能够运行 git diff | scriptThatAddsBarToNewStrings,它会编辑 foo 这样

cat foo 会渲染

line 1
line 2
line 3 (edit)bar
line 4

这是可以想象的事情吗?

【问题讨论】:

    标签: git diff git-diff


    【解决方案1】:

    此脚本将在每个修改和添加的行中附加一个字符串(即:以+ 开头的行)。

    如果您需要任何修改,请告诉我。

    #!/bin/sh
    # Change this string to whatever you want appended to a modified line
    appending="bar"
    
    
    write_file() {
        echo -ne "$content" > "$file"
    }
    
    skip_start=true
    content=""
    while read line; do
        if $skip_start; then
            # Check for the "starting line"
            [[ "$line" == @@* ]] && skip_start=false
    
            # Look for the file name
            if [[ "$line" == +++* ]]; then
                file=$(echo "$line" | sed -e 's/^+++ b\/\(.*\)$/\1/')
            fi
    
            continue
        fi
    
        # Check if the diff for the current file ended
        if [[ "$line" == diff\ --git* ]]; then
            write_file
    
            # Reset variables
            skip_start=true
            content=""
    
            continue
        fi
    
        # Process the diff
        first_char=${line:0:1}
        if [[ "#$first_char#" == '# #' || "$first_char" == '-' ]]; then
            continue
        elif [[ "$first_char" == '+' ]]; then
            line="${line:1}$appending"
        fi
    
        # Prevent a newline at the beginning
        if [[ -n "$content" ]]; then
            content+="\n"
        fi
        content+="$line"
    done
    
    write_file
    

    【讨论】:

    • 对不起,我完全是个菜鸟。将脚本命名为“附加”并运行 git diff | sh append 给了我 workspace@workspace:~/Desktop/foo$ git diff | sh append append: 15: append: [[: not found append: 18: append: [[: not found append: 15: append: [[: not found append: 18: append: [[: not found append: 15: append: [[: not found append: 18: append: [[: not found append: 15: append: [[: not found append: 18: append: [[: not found append: 15: append: [[: not found append: 18: append: [[: not found append: 15: append: [[: not found append: 18: append: [[: not found 任何想法?
    • @user2347638 您在哪个系统上使用该脚本?以及在什么环境下? [[ 是特定于 bash 的命令。
    • 我正在运行 Ubuntu 并使用 GNOME shell。我应该在mac上试试吗?顺便说一句,感谢您的帮助-非常感谢
    • 在 Mac 上完美运行——我将在 Mac 与 Ubuntu 上进行一些研究。非常感谢!
    • 实际上,我必须删除第 7 行的 -ne 选项,否则它会在第 1 行 -ne line 1 上添加“-ne”。除此之外,它就像一个魅力!
    【解决方案2】:

    是的,它可以。您可以将任何 git 命令的输出通过管道传输到任何 shell 命令(grep、sort 等)并根据需要进行处理。没有什么能阻止您将此输出作为输入传递给您的 shell 脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-15
      • 2014-05-24
      • 2011-11-10
      • 1970-01-01
      • 2012-01-22
      • 2011-02-01
      相关资源
      最近更新 更多