ast-grep-search
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseast-grep Structural Code Search & Refactoring
ast-grep 结构化代码搜索与重构
Structural code search and refactoring using — matches code by its AST (abstract syntax tree) rather than text patterns.
ast-grep使用 实现结构化代码搜索与重构——它基于 AST(抽象语法树)而非文本模式匹配代码。
ast-grepWhen to Use ast-grep vs Grep/ripgrep
何时选择 ast-grep 还是 Grep/ripgrep
| Use ast-grep when... | Use grep/rg when... |
|---|---|
| Pattern depends on code structure | Simple text or regex match |
| Need to match any number of arguments | Searching logs, docs, config |
| Refactoring across many files | One-off literal string search |
| Finding anti-patterns (empty catch, etc.) | Language doesn't matter |
| Replacing while preserving variables | Quick filename/line check |
Decision rule: If your search pattern contains wildcards for "any expression," "any arguments," or "any function name," use ast-grep.
| 适合使用 ast-grep 的场景 | 适合使用 grep/rg 的场景 |
|---|---|
| 匹配模式依赖代码结构 | 简单的文本或正则匹配 |
| 需要匹配任意数量的参数 | 搜索日志、文档、配置文件 |
| 跨多文件执行重构 | 一次性字面量字符串搜索 |
| 查找代码反模式(如空 catch 块等) | 不限制搜索内容的语言类型 |
| 替换内容同时保留变量 | 快速检查文件名/行号 |
决策规则:如果你的搜索模式包含「任意表达式」、「任意参数」或「任意函数名」这类通配需求,请使用 ast-grep。
Pattern Syntax
模式语法
| Pattern | Matches | Example |
|---|---|---|
| Single AST node | |
| Zero or more nodes | |
| Single node (no capture) | |
| Same node repeated | Finds |
| 模式 | 匹配规则 | 示例 |
|---|---|---|
| 单个 AST 节点 | |
| 零个或多个节点 | |
| 单个节点(不捕获) | |
| 重复出现的相同节点 | 可匹配 |
Essential Commands
核心命令
Search for Patterns
搜索模式
bash
undefinedbash
undefinedFind structural patterns
查找结构化模式
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'def $FUNC($$$): $$$' --lang py
ast-grep -p 'fn $NAME($$$) -> $RET { $$$ }' --lang rs
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'def $FUNC($$$): $$$' --lang py
ast-grep -p 'fn $NAME($$$) -> $RET { $$$ }' --lang rs
Search in specific directory
在指定目录下搜索
ast-grep -p 'import $PKG' --lang js src/
ast-grep -p 'import $PKG' --lang js src/
JSON output for parsing
输出JSON格式结果用于后续解析
ast-grep -p 'pattern' --lang js --json=compact
undefinedast-grep -p 'pattern' --lang js --json=compact
undefinedSearch and Replace
搜索并替换
bash
undefinedbash
undefinedPreview changes (default - shows matches)
预览变更(默认行为,仅展示匹配结果)
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js
Apply changes to all files
对所有文件应用变更
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js -U
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js -U
Interactive review
交互式审核变更
ast-grep -p 'oldAPI($$$ARGS)' -r 'newAPI($$$ARGS)' --lang py -i
ast-grep -p 'oldAPI($$$ARGS)' -r 'newAPI($$$ARGS)' --lang py -i
Convert function syntax
转换函数语法
ast-grep -p 'function($$$ARGS) { return $EXPR }'
-r '($$$ARGS) => $EXPR' --lang js -U
-r '($$$ARGS) => $EXPR' --lang js -U
ast-grep -p 'function($$$ARGS) { return $EXPR }'
-r '($$$ARGS) => $EXPR' --lang js -U
-r '($$$ARGS) => $EXPR' --lang js -U
Update import paths
更新导入路径
ast-grep -p "import $NAME from '@old/$PATH'"
-r "import $NAME from '@new/$PATH'" --lang ts -U
-r "import $NAME from '@new/$PATH'" --lang ts -U
undefinedast-grep -p "import $NAME from '@old/$PATH'"
-r "import $NAME from '@new/$PATH'" --lang ts -U
-r "import $NAME from '@new/$PATH'" --lang ts -U
undefinedLanguage Codes
语言代码对照表
| Code | Language | Code | Language |
|---|---|---|---|
| JavaScript | | Python |
| TypeScript | | Rust |
| JSX | | Go |
| TSX | | Java |
| C++ | | Ruby |
| C | | PHP |
| 代码 | 编程语言 | 代码 | 编程语言 |
|---|---|---|---|
| JavaScript | | Python |
| TypeScript | | Rust |
| JSX | | Go |
| TSX | | Java |
| C++ | | Ruby |
| C | | PHP |
Common Patterns by Language
各语言常用模式
JavaScript/TypeScript
JavaScript/TypeScript
bash
undefinedbash
undefinedFind React hooks
查找 React hooks
ast-grep -p 'const [$STATE, $SETTER] = useState($INIT)' --lang jsx
ast-grep -p 'const [$STATE, $SETTER] = useState($INIT)' --lang jsx
Find async functions
查找 async 函数
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js
Find type assertions
查找类型断言
ast-grep -p '$EXPR as $TYPE' --lang ts
ast-grep -p '$EXPR as $TYPE' --lang ts
Find empty catch blocks
查找空 catch 块
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
Find eval usage (security)
查找 eval 用法(安全风险)
ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'eval($$$)' --lang js
Find innerHTML (XSS risk)
查找 innerHTML 用法(XSS 风险)
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
Find specific imports
查找指定导入
ast-grep -p "import { $$$IMPORTS } from '$PKG'" --lang js
undefinedast-grep -p "import { $$$IMPORTS } from '$PKG'" --lang js
undefinedPython
Python
bash
undefinedbash
undefinedFind class definitions
查找类定义
ast-grep -p 'class $NAME($$$BASES): $$$' --lang py
ast-grep -p 'class $NAME($$$BASES): $$$' --lang py
Find decorated functions
查找带装饰器的函数
ast-grep -p '@$DECORATOR\ndef $FUNC($$$): $$$' --lang py
ast-grep -p '@$DECORATOR\ndef $FUNC($$$): $$$' --lang py
Find dangerous shell calls
查找危险的 shell 调用
ast-grep -p 'os.system($$$)' --lang py
ast-grep -p 'os.system($$$)' --lang py
Find SQL concatenation (injection risk)
查找 SQL 拼接(注入风险)
ast-grep -p '"SELECT * FROM " + $VAR' --lang py
undefinedast-grep -p '"SELECT * FROM " + $VAR' --lang py
undefinedRust
Rust
bash
undefinedbash
undefinedFind unsafe blocks
查找 unsafe 块
ast-grep -p 'unsafe { $$$ }' --lang rs
ast-grep -p 'unsafe { $$$ }' --lang rs
Find impl blocks
查找 impl 块
ast-grep -p 'impl $TRAIT for $TYPE { $$$ }' --lang rs
ast-grep -p 'impl $TRAIT for $TYPE { $$$ }' --lang rs
Find public functions
查找公共函数
ast-grep -p 'pub fn $NAME($$$) { $$$ }' --lang rs
undefinedast-grep -p 'pub fn $NAME($$$) { $$$ }' --lang rs
undefinedGo
Go
bash
undefinedbash
undefinedFind goroutines
查找 goroutine
ast-grep -p 'go $FUNC($$$)' --lang go
ast-grep -p 'go $FUNC($$$)' --lang go
Find defer statements
查找 defer 语句
ast-grep -p 'defer $FUNC($$$)' --lang go
ast-grep -p 'defer $FUNC($$$)' --lang go
Find error handling
查找错误处理逻辑
ast-grep -p 'if err != nil { $$$ }' --lang go
undefinedast-grep -p 'if err != nil { $$$ }' --lang go
undefinedCommon Refactoring Recipes
常用重构方案
bash
undefinedbash
undefinedReplace deprecated API calls
替换废弃的 API 调用
ast-grep -p 'oldAPI.$METHOD($$$)' -r 'newAPI.$METHOD($$$)' --lang js -U
ast-grep -p 'oldAPI.$METHOD($$$)' -r 'newAPI.$METHOD($$$)' --lang js -U
Rename a function across files
跨文件重命名函数
ast-grep -p 'oldName($$$ARGS)' -r 'newName($$$ARGS)' --lang py -U
ast-grep -p 'oldName($$$ARGS)' -r 'newName($$$ARGS)' --lang py -U
Remove console.log statements
移除 console.log 语句
ast-grep -p 'console.log($$$)' -r '' --lang js -U
ast-grep -p 'console.log($$$)' -r '' --lang js -U
Convert require to import
将 require 转换为 import
ast-grep -p 'const $NAME = require($PKG)'
-r 'import $NAME from $PKG' --lang js -i
-r 'import $NAME from $PKG' --lang js -i
ast-grep -p 'const $NAME = require($PKG)'
-r 'import $NAME from $PKG' --lang js -i
-r 'import $NAME from $PKG' --lang js -i
Add error handling wrapper
添加错误处理包装
ast-grep -p 'await $EXPR'
-r 'await $EXPR.catch(handleError)' --lang ts -i
-r 'await $EXPR.catch(handleError)' --lang ts -i
undefinedast-grep -p 'await $EXPR'
-r 'await $EXPR.catch(handleError)' --lang ts -i
-r 'await $EXPR.catch(handleError)' --lang ts -i
undefinedCommand-Line Flags
命令行参数
| Flag | Purpose |
|---|---|
| Search pattern |
| Replacement pattern |
| Target language |
| Review changes one by one |
| Apply all changes |
| JSON output ( |
| Lines after match |
| Lines before match |
| Lines around match |
| Debug pattern parsing |
| 参数 | 用途 |
|---|---|
| 搜索模式 |
| 替换模式 |
| 目标语言 |
| 逐次审核变更 |
| 应用所有变更 |
| JSON 格式输出(可选 |
| 展示匹配结果后N行 |
| 展示匹配结果前N行 |
| 展示匹配结果前后N行 |
| 调试模式解析查询 |
YAML Rules (Scan Mode)
YAML 规则(扫描模式)
For reusable rules, use with YAML configuration:
ast-grep scanbash
undefined如果需要复用规则,可以搭配 YAML 配置使用 命令:
ast-grep scanbash
undefinedScan with config
使用配置文件扫描
ast-grep scan -c sgconfig.yml
ast-grep scan -c sgconfig.yml
Run specific rule
运行指定规则
ast-grep scan -r rule-name
ast-grep scan -r rule-name
Initialize a rules project
初始化规则项目
ast-grep new project my-linter
ast-grep new rule no-console-log
Minimal rule file:
```yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block hides errors
rule:
pattern: try { $$$ } catch ($E) { }
fix: |
try { $$$ } catch ($E) { console.error($E) }For comprehensive YAML rule syntax, constraints, transformations, and testing, see REFERENCE.md.
ast-grep new project my-linter
ast-grep new rule no-console-log
最小规则文件示例:
```yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block hides errors
rule:
pattern: try { $$$ } catch ($E) { }
fix: |
try { $$$ } catch ($E) { console.error($E) }完整的 YAML 规则语法、约束、转换和测试方法请参考 REFERENCE.md。
Agentic Optimizations
智能优化场景
| Context | Command |
|---|---|
| Quick structural search | |
| Count matches | |
| File list only | |
| Batch refactor | |
| Scan with rules | |
| Debug pattern | |
| 场景 | 命令 |
|---|---|
| 快速结构化搜索 | |
| 统计匹配数量 | |
| 仅输出匹配的文件列表 | |
| 批量重构 | |
| 使用规则扫描 | |
| 调试模式解析规则 | |
Quick Reference
快速参考
bash
undefinedbash
undefined1. Search for pattern
1. 搜索模式
ast-grep -p 'pattern' --lang js src/
ast-grep -p 'pattern' --lang js src/
2. Preview rewrite
2. 预览替换效果
ast-grep -p 'old' -r 'new' --lang js
ast-grep -p 'old' -r 'new' --lang js
3. Apply rewrite
3. 应用替换
ast-grep -p 'old' -r 'new' --lang js -U
ast-grep -p 'old' -r 'new' --lang js -U
4. Scan with rules
4. 使用规则扫描
ast-grep scan -c sgconfig.yml
ast-grep scan -c sgconfig.yml
5. Debug pattern
5. 调试模式解析规则
ast-grep -p 'pattern' --debug-query --lang js
undefinedast-grep -p 'pattern' --debug-query --lang js
undefined