有没有办法 git grep stdin?

问题描述 投票:0回答:1

我想将

git grep
与从标准输入获取的输入一起使用。有一个选项
--no-index
但根据 documentation 它只允许 grep 当前目录中的文件:

--无索引

搜索当前目录中不受Git管理的文件。

我想使用

git grep
,因为它有一个选项
--function-context
,而普通的grep没有它。有没有办法用
git grep
做到这一点?

git grep stdin
1个回答
0
投票

要使用 stdin 实现与

git grep --function-context
类似的功能,您需要采用解决方法,因为
git grep
本身不支持 stdin 的输入。
相反,您可以创建一个临时文件,将标准输入内容写入其中,然后在此文件上使用
git grep
--no-index
选项。这将模拟
git grep
在标准输入上的操作。

一个

git-grep-stdin.sh
脚本可以是:

#!/bin/bash

# Create a temporary file
temp_file=$(mktemp)

# Make sure the temporary file is deleted on exit
trap "rm -f $temp_file" EXIT

# Read from stdin and write to the temporary file
cat > "$temp_file"

# Use git grep with --no-index and --function-context on the temporary file
git grep --no-index --function-context "$@" "$temp_file"

搭配使用:

chmod 755 git-grep-stdin.sh
echo "your stdin content here" | ./git-grep-stdin.sh your_search_term

注意:Git 2.45(2024 年第 2 季度),第 14 批

--no-index
选项上更清晰:

参见commit 6e9ef29commit 4a9357a(2024 年 3 月 25 日),作者:Dragan Simic (

dragan-simic
)
(由 Junio C Hamano --
gitster
--
合并于 commit e4193dc,2024 年 4 月 3 日)

grep docs
:进一步描述
--no-index
并稍微改进格式

签署人:Dragan Simic

改进

--no-index
的描述,让用户更清楚这个选项实际上在幕后做什么,以及它的目的是什么。
描述
--no-index
--cached
--untracked
选项之间的依赖关系,不能一起使用。

更详细地说,

--cached
--untracked
都让 git-grep(1) 处于通常状态,在这种状态下,它将目录视为本地 git 存储库,这与
--no-index
使 git-grep(1) 对待不同该目录不是 git 存储库。

换句话说,我们应该告诉用户我们的软件可以做什么,而不是告诉用户要做什么。

git grep
现在包含在其 手册页中:

--no-index

搜索当前目录下不受Git管理的文件, 或者忽略当前目录是由 Git 管理的。这 与运行常规

grep(1)
实用程序及其 指定了
-r
选项,但还有一些额外的好处,例如 使用 pathspec 模式来限制路径;请参阅“pathspec”条目 在链接git:gitglossary [7]中了解更多信息。

此选项不能与

--cached
--untracked
一起使用。 另请参阅下面“配置”中的
grep.fallbackToNoIndex

© www.soinside.com 2019 - 2024. All rights reserved.