🚀 快速安装

复制以下命令并运行,立即安装此 Skill:

npx @anthropic-ai/skills install supercent-io/skills-template/pattern-detection

💡 提示:需要 Node.js 和 NPM

何时使用此技能

  • 代码审查:主动检测有问题的代码模式
  • 安全审查:扫描漏洞模式
  • 重构:识别重复代码
  • 监控:对异常情况进行告警

操作指南

步骤 1:检测代码坏味道模式

检测过长函数

# 查找超过 50 行的函数
grep -n "function\|def\|func " **/*.{js,ts,py,go} | \
  while read line; do
    file=$(echo $line | cut -d: -f1)
    linenum=$(echo $line | cut -d: -f2)
    # 函数长度计算逻辑
  done

重复代码模式

# 搜索相似的代码块
grep -rn "if.*==.*null" --include="*.ts" .
grep -rn "try\s*{" --include="*.java" . | wc -l

魔法数字

# 搜索硬编码的数字
grep -rn "[^a-zA-Z][0-9]{2,}[^a-zA-Z]" --include="*.{js,ts}" .

步骤 2:安全漏洞模式

SQL 注入风险

# 通过字符串拼接构建 SQL 查询
grep -rn "query.*+.*\$\|execute.*%s\|query.*f\"" --include="*.py" .
grep -rn "SELECT.*\+.*\|\|" --include="*.{js,ts}" .

硬编码密钥

# 密码、API 密钥模式
grep -riE "(password|secret|api_key|apikey)\s*=\s*['\"][^'\"]+['\"]" --include="*.{js,ts,py,java}" .

# AWS 密钥模式
grep -rE "AKIA[0-9A-Z]{16}" .

危险函数使用

# eval, exec 使用
grep -rn "eval\(.*\)\|exec\(.*\)" --include="*.{py,js}" .

# innerHTML 使用
grep -rn "innerHTML\s*=" --include="*.{js,ts}" .

步骤 3:代码结构模式

导入分析

# 可能未使用的导入
grep -rn "^import\|^from.*import" --include="*.py" . | \
  awk -F: '{print $3}' | sort | uniq -c | sort -rn

TODO/FIXME 模式

# 查找未完成的代码
grep -rn "TODO\|FIXME\|HACK\|XXX" --include="*.{js,ts,py}" .

错误处理模式

# 空的 catch 块
grep -rn "catch.*{[\s]*}" --include="*.{js,ts,java}" .

# 被忽略的错误
grep -rn "except:\s*pass" --include="*.py" .

步骤 4:数据异常模式

正则表达式模式

import re

patterns = {
    'email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
    'phone': r'\d{3}[-.\s]?\d{4}[-.\s]?\d{4}',
    'ip_address': r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
    'credit_card': r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}',
    'ssn': r'\d{3}-\d{2}-\d{4}',
}

def detect_sensitive_data(text):
    found = {}
    for name, pattern in patterns.items():
        matches = re.findall(pattern, text)
        if matches:
            found[name] = len(matches)
    return found

统计异常检测

import numpy as np
from scipy import stats

def detect_anomalies_zscore(data, threshold=3):
    """基于 Z 分数的异常值检测"""
    z_scores = np.abs(stats.zscore(data))
    return np.where(z_scores > threshold)[0]

def detect_anomalies_iqr(data, k=1.5):
    """基于 IQR 的异常值检测"""
    q1, q3 = np.percentile(data, [25, 75])
    iqr = q3 - q1
    lower = q1 - k * iqr
    upper = q3 + k * iqr
    return np.where((data < lower) | (data > upper))[0]

步骤 5:趋势分析

import pandas as pd

def analyze_trend(df, date_col, value_col):
    """时间序列趋势分析"""
    df[date_col] = pd.to_datetime(df[date_col])
    df = df.sort_values(date_col)

    # 移动平均线
    df['ma_7'] = df[value_col].rolling(window=7).mean()
    df['ma_30'] = df[value_col].rolling(window=30).mean()

    # 增长率
    df['growth'] = df[value_col].pct_change() * 100

    # 趋势方向
    recent_trend = df['ma_7'].iloc[-1] > df['ma_30'].iloc[-1]

    return {
        'trend_direction': '上升' if recent_trend else '下降',
        'avg_growth': df['growth'].mean(),
        'volatility': df[value_col].std()
    }

输出格式

模式检测报告

# 模式检测报告

## 摘要
- 扫描文件数:XXX
- 检测到的模式数:XX
- 高风险:X
- 中风险:X
- 低风险:X

## 检测到的模式

### 安全漏洞(高风险)
| 文件 | 行号 | 模式 | 描述 |
|------|------|------|------|
| file.js | 42 | 硬编码密钥 | 硬编码的 API 密钥 |

### 代码坏味道(中风险)
| 文件 | 行号 | 模式 | 描述 |
|------|------|------|------|
| util.py | 100 | 过长函数 | 函数长度:150 行 |

## 建议操作
1. [操作 1]
2. [操作 2]

最佳实践

  1. 渐进式分析:从简单模式开始
  2. 减少误报:使用精确的正则表达式
  3. 检查上下文:理解匹配结果周围的上下文
  4. 优先级排序:按严重程度排序

约束条件

强制性规则 (必须遵守)

  1. 只读操作
  2. 执行结果验证
  3. 说明可能存在误报

禁止事项 (绝不能做)

  1. 不要自动修改代码
  2. 不要记录敏感信息

参考链接

使用示例

示例 1:基础用法

示例 2:高级用法

📄 原始文档

完整文档(英文):

https://skills.sh/supercent-io/skills-template/pattern-detection

💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。