簡體   English   中英

如何在存儲庫中搜索特定字符串的所有Git和Mercurial提交?

[英]How to search through all Git and Mercurial commits in the repository for a certain string?

我有一個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

或者,如果要搜索特定字符串的更改,可以使用pickaxe搜索選項“-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 <regexp>以查找何時移動包含<regexp>的行,-S無法執行。 -S只會告訴你包含字符串的行總數何時發生變化(即添加/刪除字符串)。

最后,您可以使用gitk來顯示懸空提交:

gitk --all $(git log -g --pretty=format:%h)

然后使用其搜索功能查找放錯位置的文件。 所有這些工作假設丟失的提交沒有“過期”並且被垃圾收集,如果它懸掛30天並且您使explog到期或運行使它們到期的命令,則可能發生這種情況。

在Mercurial中,您使用hg log --keyword在提交消息中搜索關鍵字,使用hg log --user搜索特定用戶。 有關限制hg help log的其他方法,請參閱hg help log日志。

除了richq答案用的git log -g --grep=<regexp>git grep -e <regexp> $(git log -g --pretty=format:%h)看看下面的博客文章作者:Junio C Hamano,現任git維護者


摘要

git grepgit log --grep都是面向行的 ,因為它們尋找與指定模式匹配的行。

您可以使用git log --grep=<foo> --grep=<bar> (或git log --author=<foo> --grep=<bar> ,內部轉換為兩個--grep )來查找提交匹配任何一種模式(隱含語義)。

因為是面向行的,有用語義是使用git log --all-match --grep=<foo> --grep=<bar>找到提交 同時具有線路匹配第一和線路匹配第二某處。

git grep可以組合多個模式(所有這些都必須使用-e <regexp>用形式) --or (這是默認值), --and--not() 對於grep --all-match意味着該文件必須具有與每個備選項匹配的行。

基於rq的答案,我發現這條線做了我想要的:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

這將報告提交ID,文件名,並顯示匹配的行,如下所示:

91ba969:testFile:this is a test

...有沒有人同意這是一個很好的選擇,可以包含在標准的git grep命令中?

任何以引用作為參數的命令都將接受git rev-list手冊頁中記錄的--all選項,如下所示:

   --all
       Pretend as if all the refs in $GIT_DIR/refs/ are listed on the
       command line as <commit>.

因此,例如git log -Sstring --all將顯示所有提交string提交,並且可以從分支或標記訪問(我假設您的懸掛提交至少以標記命名)。

使用Mercurial,你可以做到

$ hg grep "search for this" [file...]

還有其他選項可以縮小搜索范圍。

不知道git,但是在Mercurial中我只是將hg日志的輸出傳遞給某些sed / perl /無論什么腳本來搜索你正在尋找的任何東西。 如果您願意,可以使用模板或樣式自定義hg日志的輸出,以便於搜索。

這將包括repo中的所有命名分支。 Mercurial沒有類似懸掛blob的東西。

如果您是vim用戶,可以安裝tig(apt-get install tig),並使用/,相同的命令在vim上搜索

https://blogs.atlassian.com/2013/05/git-tig/

要添加一個尚未提及的解決方案,我不得不說使用gitg的圖形搜索框對我來說是最簡單的解決方案。 它將選擇第一個匹配項,您可以使用Ctrl-G找到下一個匹配項。

在git中的一個命令,我認為找到一個字符串要容易得多:

git log --pretty=oneline --grep "string to search"

適用於Git 2.0.4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM