我在我的代码库中使用git notes。有时候我需要查找包含特定字符串的注释提交。到目前为止,我一直使用以下命令:
git log --show-notes=* --grep="PATTERN" --format=format:%H
这里的问题是无论是否仅在提交信息中,它都会打印带有PATTERN的每个提交SHA。有更好的方法吗?
笔记存储在一个已提交的树对象中,这个树对象“隐藏”在一个注释引用下(默认情况下是refs/notes/commits
)。这意味着您可以像处理内容一样处理它们。
$ git grep Testing refs/notes/commits
refs/notes/commits:fad066950ba73c309e80451d0d0f706e45adf5a8:This is a test - Testing
$ git show fad0669
commit fad066950ba73c309e80451d0d0f706e45adf5a8
Author: Mark Adelsberger <adelsbergerm@xxx>
Date: Thu Sep 6 07:51:15 2018 -0500
1
Notes:
This is a test - Testing
diff --git a/file1 b/file1
index e69de29..038d718 100644
--- a/file1
+++ b/file1
@@ -0,0 +1 @@
+testing
在格式字符串中有一个注释的占位符,%N
。我不知道如何将注释打印在一行中,因此我使用循环逐个测试所有可达提交的注释。
尝试一下
git log --format=%H | while read commit;do
git log -1 $commit --format=%N | if grep -q "PATTERN";then echo $commit;fi;
done
您可以将 echo $commit
更改为 git log -1 --show-notes $commit
。
你可以搜索每个注释,只有在搜索匹配时才输出相应的提交。
#!/usr/bin/env bash
git notes list | while read -r note_and_commit_raw;
do
note_and_commit=($note_and_commit_raw)
git cat-file -p "${note_and_commit[0]}" | grep --quiet 'search string' &&
git --no-pager log -1 --format=format:%H ${note_and_commit[1]}
done
注意事项:
git log -1
(仅输出该提交)因为似乎您不想要这些提交的祖先
git log
的原因--notes
而不是--show-notes
,因为后者已被弃用git --no-pager
可能是不必要的我每天都使用Git Notes来编写自己的手动笔记。换句话说,没有编写我的笔记的程序,因此我不会得到大量需要搜索的内容。
显然,我只有467个refs/notes/commits
中的注释。如果我提供一个与任何提交都不匹配的搜索字符串,则该命令需要1.220秒才能完成(可能已经在磁盘缓存中等等)。因此,如果您有很多注释,则可能无法真正扩展。
通过使用Mark在他的答案中指出的内容,可以实现更有效率的程序。