git - 如何使用 bash 在每次提交的 git log 输出上运行命令

标签 git bash shell xargs git-log

在我们的项目中,我们使用 git 提交消息将某些元数据添加到我们的提交中。最明显的是 JIRA id,但还有更多。 我想做的是处理提交消息以提取此数据并对其执行某些操作,但我在如何针对每条消息而不是每行运行脚本时遇到问题。 例如,这是我正在尝试做的:

# Extract JIRA issue ids for last 5 commits
git log --format=format:%B --no-merges -n5 | while read line ; do echo $line | grep -oP "(?<=JIRA: )[^ ]+"; done

#Output 
456
128
756

这在这种情况下确实有效,但问题是这里使用 while 是每行运行而不是每条日志输出消息,因此 grep 运行了太多次。当我尝试做类似的事情时,这就成了一个问题:

 # Extract JIRA issue id and Gerrit change id from last 5 commits
 git log --format=format:%B --no-merges -n5 | while read line ; do echo $line | grep -oP "(?<=Change-Id: )[^ ]+|(?<=JIRA: )[^ ]+"; done

#Output
Ida3e220cdfa80ace5164109916fb5015d7aaaaaa
Ic4eed79f8acf5bf56f848bf543168e4ac9aaaaaa
456
I51dc621df6f54539f05053f6e036cc97a7aaaaaa
128
Ic04fa3de9b5e453358292bc7b965139707aaaaaa
756
I453a99155dacdc693ee28f248e92a6ccc8aaaaaa

如您所见,grep 中的每个匹配项都打印在单独的留置权上,但我希望以以下格式获得输出:

更改 ID JIRA

Ida3e220cdfa80ace5164109916fb5015d7aaaaaa
Ida3e220cdfa80ace5164109916fb5015d7aaaaaa 128 ic04fa3de9b5e453358292bc7b965139707aaaaaa 756

请注意,某些提交没有 Jira Id,这应该由空字符串或“”反射(reflect)出来,就像第一次提交时显示的那样。

我也试过用

# Extract JIRA ids using bash function and xargs
git log --format=format:%B --no-merges -n5 | xargs -L1 gitLogExtractJIRA

但这给了我“xargs: gitLogExtractJIRA: No such file or directory” 错误

我也研究过使用 https://git-scm.com/docs/git-for-each-ref,尤其是 --shell 子命令,但认为它不适用于这种情况,因为我正在迭代日志消息而不是引用。我在这方面可能是错的,因为我没有太多地使用 for-each-ref。

所以我的问题是如何为每条 git log 输出消息而不是每行运行 bash 函数(或内联命令组)?

最佳答案

这不是对输出中的每条消息运行命令的一般问题的答案,但对于手头的特定问题,git log 可以使用 git 提取所需的元信息-解释预告片。它可以提取遵循格式“key:value”的行,并将它们添加到日志消息中

如果你的提交信息是这样的:

Commit message subject

This is an example commit message.
Change-Id: I123123y51241
Jira: J-123

然后你可以使用类似的东西:

$ git log --format="%(trailers:key=Change-Id,separator=%x2C,valueonly) %(trailers:key=Jira,separator=%x2C,valueonly)" -n1
> I123123y51241 J-123

请参阅 https://git-scm.com/docs/git-log 中关于预告片 的部分了解更多信息。

关于git - 如何使用 bash 在每次提交的 git log 输出上运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346038/

相关文章:

ios - 用多个私有(private) cocoapods 组织一个大型项目

linux - 如何使用 sed 或 awk 命令根据另外两个变量的值设置一个变量

linux - 在 Ubuntu : I can not change files and get "file can not be found" even though the file exists?

bash - Shell脚本命令(例如 “make”)中的错误检测

linux - 从文件中删除字段保持定界符不变

python - 使用 Git 部署到我的服务器

git - 是否有自动增加 Maven 版本的好方法

linux - 如何查看标签的年龄?

shell - spawn后如何在expect shell脚本中获取子进程pid

Git cvsimport 缺少对分支的增量更改