ast-grep
ast-grep 是一款快速且支持多语言的工具,用于大规模代码结构搜索、代码检查及重写。
GenAIScript 提供了一个封装器,围绕 ast-grep
来在脚本的抽象语法树(AST)中搜索模式,并转换AST!这是一种非常高效的方式来创建修改源代码的脚本,因为能够精确地定位代码的特定部分。
- 加载
ast-grep
模块
const sg = await host.astGrep()
- 查找所有TypeScript
console.log
语句。此示例使用'pattern'语法。
// matches is an array of AST (immutable) nodesconst { matches } = await sg.search("ts", "src/*.ts", "console.log($META)")
- 查找所有没有注释的TypeScript函数。这个例子使用了规则语法。
const { matches } = await sg.search("ts", "src/fib.ts", { rule: { kind: "function_declaration", not: { precedes: { kind: "comment", stopBy: "neighbor", }, }, },})
或者如果您从ast-grep playground使用YAML复制规则,
const { matches } = await sg.search( "ts", "src/fib.ts", YAML`rule: kind: function_declaration not: precedes: kind: comment stopBy: neighbor`)
支持的语言
这个版本的 ast-grep
支持以下内置语言:
- Html
- JavaScript
- Tsx
- Css
- TypeScript
以下语言需要安装额外的软件包:
- C,
@ast-grep/lang-c
npm install -D @ast-grep/lang-c
- SQL,
@ast-grep/lang-sql
- Angular,
@ast-grep/lang-angular
搜索与替换
一个常见的用例是搜索一个模式并将其替换为另一个模式。转换阶段可以利用
inline prompts 来执行LLM转换。
这可以通过 replace
方法实现。
const { matches, replace, commitEdits } = await sg.search("ts", "...")
replace
方法创建一个编辑操作,用新文本替换节点的内容。
该编辑操作在内部存储,但在调用commitEdits
之前不会应用。
replace(matches[0], "console.log('replaced')")
当然,当您使用内联提示来生成替换文本时,事情会变得更加有趣。
const updated = await prompt`... ${matches[0].text()} ...`replace( matches[0].node, `console.log ('${updated.text}')`)
接下来,您可以提交编辑以创建一组内存中的文件。这些更改尚未应用到文件系统中。
const newFiles = await commitEdits()
如果您希望将更改应用到文件系统,可以使用writeFiles
函数。
await workspace.writeFiles(newFiles)
学习ast-grep
掌握ast-grep
的查询语言需要一定的学习曲线。
- 官方文档是一个不错的起点。
- 在线游乐场允许您无需安装即可试用该工具。
- 帮助您理解如何操作节点的JavaScript API
- 将llms.txt下载到您的Copilot上下文中以获得最佳效果。