关于 code-antipatterns-analysis
code-antipatterns-analysis 是使用 ast-grep 分析代码反模式和质量问题的技能,面向代码审查与检测规则设计。它涵盖多种语言和问题类别,并建议通过并行 Agent 检查后汇总分级结果。
主要功能
- 01提供 ast-grep 反模式查询示例
- 02覆盖多语言与框架问题类别
- 03支持并行 Agent 分析策略
- 04按严重程度整理发现并提出修复建议
- 05包含 YAML 检测规则示例
适用场景
- 01设计或扩展代码扫描规则
- 02检查异步处理与错误处理问题
- 03审计安全、性能和可维护性风险
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ laurigates/ claude-plugins --skill code-antipatterns-analysis安装后在 Claude Code 中输入/code-antipatterns-analysis确认已加载。
附带文件REFERENCE.md
详细介绍
代码反模式分析
何时使用此技能
| 适用场景 | 应改用其他工具的场景 |
|---|---|
| 需要 ast-grep 反模式查询目录来编写扫描规则 | 直接运行用户可调用的扫描器 → code-antipatterns |
| 设计或扩展并行委派的反模式检测 | 查询 ast-grep 模式语法本身 → ast-grep-search |
| 专门审计被吞掉的错误 | 使用专用扫描器 → code-error-swallowing |
| 为更全面的审查整理质量问题 | 执行完整代码审查 → code-review |
使用 ast-grep 和并行 Agent 委派,对代码库中的反模式、代码异味和质量问题进行系统检测与分析的专家知识。
分析理念
此技能强调通过并行委派进行全面分析。不要按顺序扫描问题,而是同时启动多个专门 Agent 检查不同类别,然后整合结果。
分析类别
1. JavaScript/TypeScript 反模式
回调地狱与异步问题
# Nested callbacks (3+ levels)
ast-grep -p '$FUNC($$$, function($$$) { $FUNC2($$$, function($$$) { $$$ }) })' --lang js
# Missing error handling in async
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js
# Then check if try-catch is present
# Unhandled promise rejection
ast-grep -p '$PROMISE.then($$$)' --lang js
# Without .catch() - use composite rule
魔法值
# Magic numbers in comparisons
ast-grep -p 'if ($VAR > 100)' --lang js
ast-grep -p 'if ($VAR < 50)' --lang js
ast-grep -p 'if ($VAR === 42)' --lang js
# Magic strings
ast-grep -p "if ($VAR === 'admin')" --lang js
空 catch 块
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
console 语句(调试残留)
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'console.debug($$$)' --lang js
ast-grep -p 'console.warn($$$)' --lang js
使用 let/const 声明变量
ast-grep -p 'var $VAR = $$$' --lang js
2. Vue 3 反模式
修改 Props
# YAML rule for props mutation detection
id: vue-props-mutation
language: JavaScript
message: Use computed properties or emit events to update props
rule:
pattern: props.$PROP = $VALUE
# Direct prop assignment
ast-grep -p 'props.$PROP = $VALUE' --lang js
v-for 中缺少 Key
# Search in Vue templates
ast-grep -p 'v-for="$ITEM in $LIST"' --lang html
# Check if :key is present nearby
Composition API 代码库中使用 Options API
# Find Options API usage
ast-grep -p 'export default { data() { $$$ } }' --lang js
ast-grep -p 'export default { methods: { $$$ } }' --lang js
ast-grep -p 'export default { computed: { $$$ } }' --lang js
# vs Composition API
ast-grep -p 'defineComponent({ setup($$$) { $$$ } })' --lang js
响应式状态问题
# Destructuring reactive state (loses reactivity)
ast-grep -p 'const { $$$PROPS } = $REACTIVE' --lang js
# Should use toRefs
ast-grep -p 'const { $$$PROPS } = toRefs($REACTIVE)' --lang js
3. TypeScript 质量问题
过度使用 any
ast-grep -p ': any' --lang ts
ast-grep -p 'as any' --lang ts
ast-grep -p '<any>' --lang ts
非空断言
ast-grep -p '$VAR!' --lang ts
ast-grep -p '$VAR!.$PROP' --lang ts
使用类型断言而非类型守卫
ast-grep -p '$VAR as $TYPE' --lang ts
缺少返回类型
# Functions without return type annotations
ast-grep -p 'function $NAME($$$) { $$$ }' --lang ts
# Check if return type is present
4. 异步/Promise 模式
未处理的 Promise
# Promise without await or .then/.catch
ast-grep -p '$ASYNC_FUNC($$$)' --lang js
# Context: check if result is used
# Floating promises (no await)
ast-grep -p '$PROMISE_RETURNING()' --lang ts
嵌套回调(厄运金字塔)
ast-grep -p '$F1($$$, function($$$) { $F2($$$, function($$$) { $F3($$$, function($$$) { $$$ }) }) })' --lang js
Promise 构造器反模式
# Wrapping already-async code in new Promise
ast-grep -p 'new Promise(($RESOLVE, $REJECT) => { $ASYNC_FUNC($$$).then($$$) })' --lang js
5. 代码复杂度
过长函数(手动审查)
# Find function definitions, then count lines
ast-grep -p 'function $NAME($$$) { $$$ }' --lang js --json | jq '.[] | select(.range.end.line - .range.start.line > 50)'
嵌套过深
# Nested if statements (4+ levels)
ast-grep -p 'if ($A) { if ($B) { if ($C) { if ($D) { $$$ } } } }' --lang js
参数列表过长
ast-grep -p 'function $NAME($A, $B, $C, $D, $E, $$$)' --lang js
圈复杂度指标
# Multiple conditionals in single function
ast-grep -p 'if ($$$) { $$$ } else if ($$$) { $$$ } else if ($$$) { $$$ }' --lang js
6. React/Pinia Store 模式
直接修改状态(Pinia)
# Direct store state mutation outside actions
ast-grep -p '$STORE.$STATE = $VALUE' --lang js
useEffect 中缺少依赖项
ast-grep -p 'useEffect(() => { $$$ }, [])' --lang jsx
# Check if variables used inside are in dependency array
JSX 中的内联函数
ast-grep -p '<$COMPONENT onClick={() => $$$} />' --lang jsx
ast-grep -p '<$COMPONENT onChange={() => $$$} />' --lang jsx
7. 内存与性能
未清理的事件监听器
ast-grep -p 'addEventListener($EVENT, $HANDLER)' --lang js
# Check for corresponding removeEventListener
未清理的 setInterval
ast-grep -p 'setInterval($$$)' --lang js
# Check for clearInterval
计算属性/备忘录中的大型数组
ast-grep -p 'computed(() => $ARRAY.filter($$$))' --lang js
ast-grep -p 'useMemo(() => $ARRAY.filter($$$), [$$$])' --lang jsx
8. 安全问题
使用 eval
ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'new Function($$$)' --lang js
赋值给 innerHTML(XSS 风险)
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p 'dangerouslySetInnerHTML={{ __html: $$$ }}' --lang jsx
硬编码密钥
ast-grep -p "apiKey: '$$$'" --lang js
ast-grep -p "password = '$$$'" --lang js
ast-grep -p "secret: '$$$'" --lang js
SQL 字符串拼接
ast-grep -p '"SELECT * FROM " + $VAR' --lang js
ast-grep -p '`SELECT * FROM ${$VAR}`' --lang js
9. Python 反模式
裸 Except
ast-grep -p 'except: $$$' --lang py
可变默认参数
ast-grep -p 'def $FUNC($ARG=[])' --lang py
ast-grep -p 'def $FUNC($ARG={})' --lang py
使用全局变量
ast-grep -p 'global $VAR' --lang py
没有理由的 Type: ignore
# Search in comments via grep
grep -r "# type: ignore$" --include="*.py"
并行分析策略
分析代码库时,并行启动多个 Agent,以最大限度提高效率:
Agent 委派模式
1. **Language Detection Agent** (Explore)
- Detect project languages and frameworks
- Identify relevant file patterns
2. **JavaScript/TypeScript Agent** (code-analysis or Explore)
- JS anti-patterns
- TypeScript quality issues
- Async/Promise patterns
3. **Framework-Specific Agent** (code-analysis or Explore)
- Vue 3 anti-patterns (if Vue detected)
- React anti-patterns (if React detected)
- Pinia/Redux patterns (if detected)
4. **Security Agent** (security-audit)
- Security concerns
- Hardcoded values
- Injection risks
5. **Complexity Agent** (code-analysis or Explore)
- Code complexity metrics
- Long functions
- Deep nesting
6. **Python Agent** (if Python detected)
- Python anti-patterns
- Type annotation issues
整合结果
并行分析完成后:
- 按严重程度汇总发现(严重、高、中、低)
- 按类别分组(安全、性能、可维护性)
- 提供可执行的修复建议
- 根据影响确定修复优先级
YAML 规则示例
完整的反模式规则
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block suppresses errors silently
note: |
Empty catch blocks hide errors and make debugging difficult.
Either log the error, handle it specifically, or re-throw.
rule:
pattern: try { $$$ } catch ($E) { }
fix: |
try { $$$ } catch ($E) {
console.error('Error:', $E);
throw $E;
}
files:
- 'src/**/*.js'
- 'src/**/*.ts'
ignores:
- '**/*.test.js'
- '**/node_modules/**'
Vue Props 修改规则
id: no-props-mutation
language: JavaScript
severity: error
message: Never mutate props directly - use emit or local copy
rule:
all:
- pattern: props.$PROP = $VALUE
- inside:
kind: function_declaration
note: |
Props should be treated as immutable. To modify data:
1. Emit an event to parent: emit('update:propName', newValue)
2. Create a local ref: const local = ref(props.propName)
与命令集成
此技能旨在与 /code:antipatterns 命令配合使用,该命令会:
- 检测项目语言栈
- 启动并行的专门 Agent
- 将发现整合为按优先级排序的报告
- 在可能时建议自动修复
分析最佳实践
- 从语言检测开始 - 针对检测到的语言运行相应的模式
- 使用并行 Agent - 不要按顺序分析;将任务委派给专业 Agent
- 按严重程度排序 - 优先处理安全问题,其次是正确性问题,最后是风格问题
- 提供修复方案 - 不要只指出问题;还要提出解决方案
- 考虑上下文 - 某些“反模式”在特定上下文中是可以接受的
- 单独检查测试文件 - 测试代码可能适用不同的标准
严重程度
| 严重程度 | 描述 | 示例 |
|---|---|---|
| 严重 | 安全漏洞、数据丢失风险 | eval()、SQL 注入、硬编码密钥 |
| 高 | Bug、行为不正确 | Props 变更、未处理的 Promise、空 catch |
| 中 | 可维护性问题 | 魔法数字、深层嵌套、大型函数 |
| 低 | 风格/偏好 | 使用 var、console.log、内联函数 |
资源
- ast-grep 文档:https://ast-grep.github.io/
- ast-grep Playground:https://ast-grep.github.io/playground.html
- OWASP Top 10:https://owasp.org/www-project-top-ten/
- Clean Code 原则:https://clean-code-developer.com/