关于 structural-search
这项技能介绍如何用 ast-grep 按语法树结构搜索代码,适合需要查找语义模式或准备重构的开发者,减少正则表达式带来的误匹配。
主要功能
- 01基于 AST 的代码搜索
- 02按模式匹配代码
- 03预览或应用改写
- 04输出 JSON、上下文和计数
- 05运行 YAML 规则
适用场景
- 01查找函数或方法的用法
- 02定位 Hook 和 API 调用
- 03准备大规模重构
- 04检测反模式和安全问题
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill structural-search安装后在 Claude Code 中输入/structural-search确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/rule-template.yamlreferences/advanced-usage.mdgo-rust-patterns.mdjs-ts-patterns.mdpython-patterns.mdsecurity-patterns.mdscripts/.gitkeep详细介绍
结构化搜索
根据代码的抽象语法树(AST)结构搜索代码。查找正则表达式无法可靠匹配的语义模式。
工具
| 工具 | 命令 | 用途 |
|---|---|---|
| ast-grep | sg -p 'pattern' | 感知 AST 的代码搜索 |
模式语法
| 模式 | 匹配内容 | 示例 |
|---|---|---|
$NAME | 命名标识符 | function $NAME() {} |
$_ | 任意单个节点 | console.log($_) |
$$$ | 零个或多个节点 | function $_($$$) {} |
10 个必备模式
# 1. Find console.log calls
sg -p 'console.log($_)'
# 2. Find React hooks
sg -p 'const [$_, $_] = useState($_)'
sg -p 'useEffect($_, [$$$])'
# 3. Find function definitions
sg -p 'function $NAME($$$) { $$$ }'
sg -p 'def $NAME($$$): $$$' --lang python
# 4. Find imports
sg -p 'import $_ from "$_"'
sg -p 'from $_ import $_' --lang python
# 5. Find async patterns
sg -p 'await $_'
sg -p 'async function $NAME($$$) { $$$ }'
# 6. Find error handling
sg -p 'try { $$$ } catch ($_) { $$$ }'
sg -p 'if err != nil { $$$ }' --lang go
# 7. Find potential issues
sg -p '$_ == $_' # == instead of ===
sg -p 'eval($_)' # Security risk
sg -p '$_.innerHTML = $_' # XSS vector
# 8. Preview refactoring
sg -p 'console.log($_)' -r 'logger.info($_)'
# 9. Apply refactoring
sg -p 'var $NAME = $_' -r 'const $NAME = $_' --rewrite
# 10. Search specific language
sg -p 'pattern' --lang typescript
快速参考
| 任务 | 命令 |
|---|---|
| 查找模式 | sg -p 'pattern' |
| 指定语言 | sg -p 'pattern' --lang python |
| 替换(预览) | sg -p 'old' -r 'new' |
| 替换(应用) | sg -p 'old' -r 'new' --rewrite |
| 显示上下文 | sg -p 'pattern' -A 3 |
| JSON 输出 | sg -p 'pattern' --json |
| 仅显示文件列表 | sg -p 'pattern' -l |
| 统计匹配数量 | sg -p 'pattern' --count |
| 运行 YAML 规则 | sg scan |
适用场景
- 查找函数或方法的所有用法
- 定位特定代码模式(Hook、API 调用)
- 为大规模重构做准备
- 正则表达式可能产生误匹配时
- 检测反模式和安全问题
- 创建自定义 lint 规则
更多资源
如需查看完整模式,请加载:
./references/js-ts-patterns.md- JavaScript/TypeScript 模式./references/python-patterns.md- Python 模式./references/go-rust-patterns.md- Go 和 Rust 模式./references/security-patterns.md- 安全漏洞检测./references/advanced-usage.md- YAML 规则和工具集成./assets/rule-template.yaml- 自定义规则的入门模板
评论
支持 Markdown