← ClaudeAtlas

ast-greplisted

语法感知的代码搜索、linting 和重写工具。支持基于 AST 的结构化代码搜索和批量代码转换。
aiskillstore/marketplace · ★ 329 · AI & Automation · score 77
Install: claude install-skill aiskillstore/marketplace
# AST-Grep AST-Grep (ast-grep/sg) 是一个快速且用户友好的工具,用于代码搜索、linting 和大规模代码重写。 ## 执行环境 | 路径类型 | 说明 | |---------|------| | **使用方式** | 命令行工具,需要安装 ast-grep | | **调用场景** | 语法感知的代码搜索、结构化代码分析、批量代码转换 | | **工作目录** | 项目根目录 | ## 安装 ```bash # macOS brew install ast-grep # Linux cargo install ast-grep # 验证安装 ast-grep --version ``` ## 核心功能 ### 1. 语法感知搜索 使用 AST(抽象语法树)进行代码搜索,而非简单的文本匹配。 ```bash # 搜索特定模式 ast-grep --lang python -p "def $FUNC($$$ARGS):" # 搜索函数调用 ast-grep --lang ts -p "console.log($$$MSG)" # 搜索条件语句 ast-grep --lang ts -p "if ($$COND) { $$$BODY }" ``` ### 2. 代码 Linting 基于 AST 的代码检查,比传统 linter 更精确。 ```bash # 扫描项目 ast-grep scan -r sgconfig.yml # 扫描特定目录 ast-grep scan src/ # 扫描特定文件 ast-grep scan src/main.ts ``` ### 3. 代码重写 批量转换代码模式。 ```bash # 简单替换 ast-grep run -p "oldFunction($$$ARGS)" -r "newFunction($$ARGS)" --lang ts # 复杂转换(使用 YAML 规则) ast-grep run -r rule.yml ``` ### 4. 规则测试 测试 ast-grep 规则是否正确。 ```bash # 测试规则 ast-grep test -r rule.yml # 测试特定模式 ast-grep test -p "pattern" --lang ts ``` ## 规则开发流程 ### 通用流程 1. **理解查询**:明确用户需求,必要时询问更多细节 2. **编写示例**:编写匹配查询的简单代码示例 3. **编写规则**:编写匹配示例的 ast-grep 规则 4. **测试规则**:使用 `test_match_code_rule` 验证规则 - 如果不匹配,移除部分子规则并调试 - 如果使用 `inside` 或 `has`,确保使用 `stopBy: end` 5. **搜索代码**:使用规则搜索代码库 ### 规则开发步骤 1. **分解查询**:将用户查询分解为更小的部分 2. **识别子规则**:识别可用于匹配代码的子规则 3. **组合规则**:使用关系规则或组合规则组合子规则 4. **调试规则**:如果规则不匹配示例代码,移除部分子规则并调试不匹配的部分 5. **使用工具**:使用 ast-grep mcp 工具转储 AST 或转储模式查询 6. **测试规则**:使用 ast-grep mcp 工具针对示例代码片段测试规则 ## 规则类型 ### 1. 原子规