首页 > 解决方案 > 如何在 gitconfig 中正确地为这个 git 行计数命令起别名?

问题描述

我在 Stack Overflow 上找到了这个命令来计算每个用户对 repo 的 LOC 贡献:

git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = ""; next } END { for (a in ins) { printf "%10d %10d %10d %s\n", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn

但是,当我尝试在我的 .gitconfig 中将此别名作为命令时,会出现各种错误。我不知道如何正确地转义它,以便当我调用“git count-lines”时它在我的 bash 中正常运行。我根据 StackOverflow 上描述 git 别名的其他问题进行了多次尝试,但我不断遇到不同的问题。

到目前为止,我已经在我的 gitconfig 中尝试了很多东西。这个给我的错误最少:

[alias]
    count-lines = "!f() { git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = \"\"; next } END { for (a in ins) { printf \"%10d %10d %10d %s\n\", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn; }; f"

这是上面给出的错误:

awk: cmd. line:1: /./ && ... printf "%10d %10d %10d %s
awk: cmd. line:1:                   ^ unterminated string  
awk: cmd. line:1: /./ && ... printf "%10d %10d %10d %s 
awk: cmd. line:1:                   ^ syntax error

(据我了解,我在 Windows 7 计算机上,所以我需要在整个命令周围使用引号)

标签: windowsbashgitconfigalias

解决方案


好的,经过一个半小时的调试和摆弄,我终于找到了问题所在:我需要在 printf 语句中的换行符中转义反斜杠。

broken: count-lines = "!f() { git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = \"\"; next } END { for (a in ins) { printf \"%10d %10d %10d %s\n\", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn; }; f"
fixed:  count-lines = "!f() { git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = \"\"; next } END { for (a in ins) { printf \"%10d %10d %10d %s\\n\", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn; }; f"

编辑:根据要求添加最终脚本(以下是我~/.gitconfig文件的全部内容):

[user]
    name = Sam Smith
    email = sam.smith@gmail.com
[alias]
    count-lines = "!f() { git log --no-merges --pretty=format:%an --numstat | awk '/./ && !author { author = $0; next } author { ins[author] += $1; del[author] += $2 } /^$/ { author = \"\"; next } END { for (a in ins) { printf \"%10d %10d %10d %s\\n\", ins[a] - del[a], ins[a], del[a], a } }' | sort -rn; }; f"

推荐阅读