繁体   English   中英

在git diff输出上操作

[英]Operate on git diff output

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

说我有git追踪的档案'foo'

foo:

line 1
line 2
line 3
line 4

我对其进行编辑(在第3行中添加“(edit)”),然后

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 git diff | scriptThatAddsBarToNewStrings将编辑foo这样

cat foo将呈现

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

那是可以想象得到的吗?

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

该脚本会将字符串添加到每条经过修改和添加的行(说:以+开头的行)。

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

#!/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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM