by hylarucoder
编写自定义 lint 规则和代码转换复杂且容易出错。此技能提供可直接使用的 ast-grep YAML 模式,用于创建精确的基于 AST 的代码搜索和重写规则。
1. 打开 Claude 聊天界面
2. 点击下方 "📋 复制" 按钮
3. 粘贴到 Claude 聊天框中并发送
4. 输入 "使用 ast-grep-rule-crafter 技能" 开始使用
=== ast-grep-rule-crafter 技能 === 作者: hylarucoder 描述: 编写自定义 lint 规则和代码转换复杂且容易出错。此技能提供可直接使用的 ast-grep YAML 模式,用于创建精确的基于 AST 的代码搜索和重写规则。 使用方法: 1. 调用技能: "使用 ast-grep-rule-crafter 技能" 2. 提供相关信息: 根据技能要求提供必要参数 3. 查看结果: 技能会返回处理结果 示例: "使用 ast-grep-rule-crafter 技能,帮我分析一下这段代码"
这种方法适用于所有 Claude 用户,不需要安装额外工具。
coding
safe
ast-grep uses tree-sitter to parse code into AST, enabling precise pattern matching. Rules are defined in YAML for linting, searching, and rewriting code.
id: no-console-log
language: JavaScript
rule:
pattern: console.log($$$ARGS)
fix: logger.log($$$ARGS)
message: Replace console.log with logger
项目级扫描需要 sgconfig.yml 配置文件:
# sgconfig.yml (项目根目录)
ruleDirs:
- rules # 规则目录,递归加载所有 .yml 文件
典型项目结构:
my-project/
├── sgconfig.yml
├── rules/
│ ├── no-console.yml
│ └── custom/
│ └── team-rules.yml
└── src/
运行项目扫描:
ast-grep scan # 自动查找 sgconfig.yml
ast-grep scan --config path/to/sgconfig.yml # 指定配置
注意:
ast-grep scan命令必须有sgconfig.yml,而ast-grep run -p可单独使用。
只检查不修复,用于 CI/编辑器提示:
# rules/no-console-log.yml
id: no-console-log
language: JavaScript
severity: warning
message: Avoid console.log in production code
rule:
pattern: console.log($$$ARGS)
验证:
ast-grep scan -r rules/no-console-log.yml src/
需要自动修复时添加 fix:
id: no-console-log
language: JavaScript
severity: warning
message: Replace console.log with logger
rule:
pattern: console.log($$$ARGS)
fix: logger.log($$$ARGS)
应用修复:
ast-grep scan -r rules/no-console-log.yml --update-all src/
- [ ] 1. 用 CLI 探索 pattern: ast-grep -p 'pattern' src/
- [ ] 2. 创建规则文件 (.yml)
- [ ] 3. 验证: ast-grep scan -r rule.yml src/
- [ ] 4. 如有误报 → 添加 constraints → 重新验证
调试 AST 结构:
ast-grep -p 'console.log($ARG)' --debug-query ast
| Element | Syntax | Example |
|---|---|---|
| Single node | $VAR | console.log($MSG) |
| Multiple nodes | $$$ARGS | fn($$$ARGS) |
| Same content | Use same name | $A == $A |
| Non-capturing | $_VAR | $_FN($_FN) |
| Type | Purpose | Example |
|---|---|---|
pattern | Match code structure | pattern: if ($COND) {} |
kind | Match AST node type | kind: function_declaration |
all | Match ALL conditions | all: [pattern: X, kind: Y] |
any | Match ANY condition | any: [pattern: var $A, pattern: let $A] |
not | Exclude matches | not: {pattern: safe_call()} |
has | Must have child | has: {kind: return_statement} |
inside | Must be in ancestor | inside: {kind: class_body} |
Complete syntax guide: See references/rule-syntax.md
Language-specific patterns: See references/common-patterns.md
Bash, C, Cpp, CSharp, Css, Elixir, Go, Haskell, Hcl, Html, Java, JavaScript, Json, Kotlin, Lua, Nix, Php, Python, Ruby, Rust, Scala, Solidity, Swift, Tsx, TypeScript, Yaml
View Count
0
Download Count
0
Favorite Count
0
Quality Score
70