Grep 工具
Grep 工具用于在文件内容中搜索模式。
概述
Grep 工具允许 AI 助手在文件系统中搜索特定内容。它支持:
- 正则表达式匹配
- 递归目录搜索
- 行号显示
- 多文件搜索
定义位置
packages/opencode/src/tool/grep.tspackages/opencode/src/tool/grep.txt
参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
pattern | string | 是 | 搜索模式(正则表达式) |
path | string | 是 | 搜索路径(支持 glob 模式) |
TypeScript 类型定义
export type GrepInput = {
pattern: string // 正则表达式
path: string // 文件路径或 glob 模式
}
export type GrepOutput = {
title: string
output: string // 匹配结果(文件:行号 内容)
metadata: {
count: number // 匹配数量
}
}
工作流程
1. 正则编译
const regex = new RegExp(params.pattern, "g")
2. 文件搜索
const files = await glob(params.path)
3. 内容匹配
for (const file of files) {
const content = await fs.readFile(file, "utf-8")
const lines = content.split("\n")
lines.forEach((line, index) => {
if (regex.test(line)) {
results.push(`${file}:${index + 1}:${line.trim()}`)
}
})
}
典型使用场景
场景 1:搜索函数定义
await GrepTool.execute(
{
pattern: "function.*\\(",
path: "src/**/*.ts",
},
ctx,
)
场景 2:搜索导入语句
await GrepTool.execute(
{
pattern: "import.*from",
path: "**/*.js",
},
ctx,
)
场景 3:搜索 TODO 注释
await GrepTool.execute(
{
pattern: "TODO",
path: "src/**/*.{ts,tsx}",
},
ctx,
)
场景 4:搜索特定变量
await GrepTool.execute(
{
pattern: "const.*API.*=",
path: "**/*.{ts,js}",
},
ctx,
)
错误处理
无效正则
Error: Invalid regular expression
解决:
- 检查正则语法
- 使用有效的正则模式
限制和注意事项
正则限制
- 必须使用有效的正则表达式
- 区分大小写(除非使用
i标志)
搜索限制
- 大型目录可能需要较长时间
- 考虑使用更具体的路径模式
权限要求
| 权限类型 | 说明 |
|---|---|
read | 搜索文件的读取权限 |
最佳实践
1. 使用转义
// ✅ 好:转义特殊字符
await GrepTool.execute(
{
pattern: "import\\s+from",
path: "**/*.ts",
},
ctx,
)
2. 组合使用
场景: 先搜索,再读取
Grep (搜索函数) → Read (读取所在文件)
3. 具体化搜索
// ✅ 好:具体模式
await GrepTool.execute(
{
pattern: "export async function testRoute",
path: "**/*test.ts",
},
ctx,
)
// ❌ 差:太宽泛
await GrepTool.execute(
{
pattern: "function",
path: "**/*.ts",
},
ctx,
)
相关文档
- Tool System - Tool 系统实现机制
- Read - 读取文件
- Glob - 查找文件
变更历史
| 版本 | 变更内容 | 日期 |
|---|---|---|
| v1 | 初始 Grep 工具 | - |