我有一个 Git 存储库,其中只有很少的分支和悬空提交。我想在存储库中搜索特定字符串的所有此类提交。
我知道如何获取历史记录中所有提交的日志,但这些不包括分支或悬挂的 blob,只包括 HEAD 的历史记录。我想把它们全部找到,找到一个丢失的特定提交。
我也想知道如何在 Mercurial 中执行此操作,因为我正在考虑进行切换。
您可以使用
git log -g
查看悬空提交。
-g, --walk-reflogs
Instead of walking the commit ancestry chain, walk reflog entries from
the most recent one to older ones.
因此,您可以这样做来查找悬空的提交消息中的特定字符串:
git log -g --grep=search_for_this
或者,如果您想搜索特定字符串的更改,您可以使用镐搜索选项“-S”:
git log -g -Ssearch_for_this
# this also works but may be slower, it only shows text-added results
git grep search_for_this $(git log -g --pretty=format:%h)
Git 1.7.4 将添加 -G 选项,允许您通过 -G
最后,您可以使用 gitk 来可视化悬空提交:
gitk --all $(git log -g --pretty=format:%h)
然后使用其搜索功能来查找丢失的文件。所有这些工作都假设丢失的提交尚未“过期”并且已被垃圾收集,如果它悬空 30 天并且您使引用日志过期或运行使它们过期的命令,则可能会发生这种情况。
在 Mercurial 中,您可以使用
hg log --keyword
搜索提交消息中的关键字,并使用 hg log --user
搜索特定用户。有关限制日志的其他方法,请参阅 hg help log
。
除了使用 git log -g --grep=<regexp>
或
git grep -e <regexp> $(git log -g --pretty=format:%h)
的 richq 答案之外:请查看现任 git 维护者 Junio C Hamano 的以下博客文章
git grep和git log --grep都是面向行的,因为它们查找与指定模式匹配的行。
您可以使用git log --grep=<foo> --grep=<bar>
(或内部翻译为两个
git log --author=<foo> --grep=<bar>
的
--grep
)来查找与模式中的either 匹配的提交(隐式 OR 语义)。 因为是面向行的,所以有用的
AND 语义是使用 git log --all-match --grep=<foo> --grep=<bar>
来查找commit ,它在某处具有 both 行匹配第一行和行匹配第二行。 使用
git grep
,您可以将多种模式(所有模式都必须使用
-e <regexp>
形式)与
--or
(默认)、
--and
、
--not
、
(
和
)
组合起来。对于 grep
--all-match
意味着file 必须具有与每个替代项匹配的行。
git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")
它将报告提交 ID、文件名,并显示匹配的行,如下所示:
91ba969:testFile:this is a test
...有人同意这将是包含在标准 git grep 命令中的一个不错的选择吗?
--all
手册页中记录的
git rev-list
选项,如下所示:
--all
Pretend as if all the refs in $GIT_DIR/refs/ are listed on the
command line as <commit>.
因此,例如
git log -Sstring --all
将显示所有提到
string
的提交,并且可以从分支或标签访问这些提交(我假设您的悬空提交至少用标签命名)。
$ hg grep "search for this" [file...]
还有其他选项可以缩小搜索修订的范围。
这将包括存储库中所有命名的分支。 Mercurial 没有类似悬挂斑点之类的东西。
git log --pretty=oneline --grep "string to search"
适用于 Git 2.0.4
git log | Select-String "what you want to find”