mcpField
S
structural-search

structural-search

github.com/0xdarkmatter开发7855 次安装2 周前更新
代码仓库

关于 structural-search

这项技能介绍如何用 ast-grep 按语法树结构搜索代码,适合需要查找语义模式或准备重构的开发者,减少正则表达式带来的误匹配。

主要功能

  1. 01基于 AST 的代码搜索
  2. 02按模式匹配代码
  3. 03预览或应用改写
  4. 04输出 JSON、上下文和计数
  5. 05运行 YAML 规则

适用场景

  1. 01查找函数或方法的用法
  2. 02定位 Hook 和 API 调用
  3. 03准备大规模重构
  4. 04检测反模式和安全问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/0xdarkmatter/claude-mods --skill structural-search

安装后在 Claude Code 中输入/structural-search确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
rule-template.yaml
references/
advanced-usage.md
go-rust-patterns.md
js-ts-patterns.md
python-patterns.md
security-patterns.md
scripts/
.gitkeep

详细介绍

结构化搜索

根据代码的抽象语法树(AST)结构搜索代码。查找正则表达式无法可靠匹配的语义模式。

工具

工具命令用途
ast-grepsg -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