我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?

一个非常糟糕的解决方案是grep日志:

git log -p | grep <pattern>

然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。


当前回答

Jeet的答案在PowerShell中有效。

git grep -n <regex> $(git rev-list --all)

下面显示了任何提交中包含密码的所有文件。

# Store intermediate result
$result = git grep -n "password" $(git rev-list --all)

# Display unique file names
$result | select -unique { $_ -replace "(^.*?:)|(:.*)", "" }

其他回答

我接受了Jeet的答案,并将其改编为Windows(多亏了这个答案):

FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt

注意,对于我来说,出于某种原因,删除这个正则表达式的实际提交并没有出现在命令的输出中,而是出现在它之前的一次提交。

灵感来自答案https://stackoverflow.com/a/2929502/6041515,我发现gitgrep似乎在每次提交时都会搜索完整的代码库,而不仅仅是差异,结果往往重复且冗长。下面的脚本将只搜索每个git提交的差异:

for commit in $(git rev-list --all); do 
    # search only lines starting with + or -
    if  git show "$commit" | grep "^[+|-].*search-string"; then 
        git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
    fi  
done

示例输出,底部的gitcommit是第一次引入我正在搜索的更改的gitcommit:

csshx$ for commit in $(git rev-list --all); do 
>     if  git show "$commit" | grep "^[+|-].*As csshX is a command line tool"; then 
>         git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
>     fi  
> done

+As csshX is a command line tool, no special installation is needed. It may
987eb89 2009-03-04 Gavin Brock Added code from initial release

所以,您是否正在尝试翻看旧版本的代码,以查看最后存在的内容?

如果我这样做的话,我可能会使用git平分。使用平分线,您可以指定已知的好版本、已知的坏版本,以及一个简单的脚本,该脚本可以检查版本是好还是坏(在本例中,一个grep可以查看您正在查找的代码是否存在)。运行此命令将发现代码何时被删除。

场景:您使用IDE对代码进行了大清理。问题:IDE清理的比它应该清理的多,现在代码无法编译(缺少资源等)

解决方案:

git grep --cached "text_to_find"

它将找到更改“text_to_find”的文件。

现在可以撤消此更改并编译代码。

如果您想浏览代码更改(查看整个历史中给定单词的实际更改),请选择补丁模式-我发现了一个非常有用的组合:

git log -p
# Hit '/' for search mode.
# Type in the word you are searching.
# If the first search is not relevant, hit 'n' for next (like in Vim ;) )