Skip to content

analyze - 代码分析命令

analyze 命令是 Claude Code 的智能代码分析工具,提供深度的代码质量分析、安全检查、性能评估和架构洞察。

命令概述

analyze 命令通过多维度分析帮助开发者:

  • 发现潜在的代码问题
  • 识别安全漏洞
  • 评估代码质量指标
  • 分析系统架构
  • 检测性能瓶颈

基本用法

完整项目分析

bash
# 分析整个项目
claude analyze

# 分析指定目录
claude analyze ./src

# 分析特定文件
claude analyze ./src/components/UserProfile.jsx

按类型分析

bash
# 代码质量分析
claude analyze --type quality

# 安全性分析
claude analyze --type security

# 性能分析
claude analyze --type performance

# 架构分析
claude analyze --type architecture

分析深度控制

bash
# 快速分析 (基础检查)
claude analyze --depth quick

# 标准分析 (推荐)
claude analyze --depth standard

# 深度分析 (全面检查)
claude analyze --depth deep

配置选项

基础选项

选项类型默认值描述
--typestringall分析类型
--depthstringstandard分析深度
--outputstringconsole输出格式
--configstring-配置文件路径

输出选项

选项类型默认值描述
--formatstringtable输出格式: table, json, html
--reportstring-生成报告文件
--verbosebooleanfalse详细输出
--quietbooleanfalse安静模式

过滤选项

选项类型默认值描述
--severitystringmedium最低严重性: low, medium, high
--includestring-包含的文件模式
--excludestring-排除的文件模式

分析类型详解

1. 代码质量分析 (Quality)

代码复杂度分析

bash
# 圈复杂度分析
claude analyze --type quality --focus complexity

# 认知复杂度分析  
claude analyze --type quality --focus cognitive

示例输出:

bash
代码复杂度分析报告
==================

 总体指标:
 平均圈复杂度: 4.2 (良好)
 平均认知复杂度: 6.8 (中等)
 最大函数复杂度: 15 (需要重构)

 高复杂度函数 (>10):
┌─────────────────────────────────────┬──────────┬──────────┐
 文件 函数 复杂度
├─────────────────────────────────────┼──────────┼──────────┤
 src/utils/dataProcessor.js:45 process 15
 src/components/UserForm.jsx:120 validate 12
 src/services/apiService.js:78 request 11
└─────────────────────────────────────┴──────────┴──────────┘

 重构建议:
 dataProcessor.process(): 建议拆分成多个小函数
 UserForm.validate(): 考虑使用策略模式
 apiService.request(): 提取错误处理逻辑

代码重复检测

bash
# 重复代码检测
claude analyze --type quality --focus duplication

示例输出:

bash
代码重复分析报告
================

 重复代码统计:
 重复代码块: 8
 重复行数: 156 (占总代码 3.2%)
 最大重复块: 23

 重复代码详情:
┌─────────────────────────────────────┬──────────┬─────────┐
 位置 行数 相似度
├─────────────────────────────────────┼──────────┼─────────┤
 src/components/UserList.jsx:34 23 95%
 src/components/ProductList.jsx:45 23 95%
├─────────────────────────────────────┼──────────┼─────────┤
 src/utils/validation.js:12 15 88%
 src/utils/formHelpers.js:28 15 88%
└─────────────────────────────────────┴──────────┴─────────┘

 重构建议:
 提取公共组件 ListComponent
 创建通用验证函数库
 使用高阶组件减少重复逻辑

2. 安全性分析 (Security)

安全漏洞扫描

bash
# 全面安全扫描
claude analyze --type security

# 特定漏洞类型
claude analyze --type security --focus xss,sql-injection,csrf

示例输出:

bash
安全分析报告
============

 安全评分: B+ (82/100)

  发现的安全问题:
┌──────────┬─────────────────────────────────────┬──────────┬─────────┐
 严重性 问题 位置 CWE
├──────────┼─────────────────────────────────────┼──────────┼─────────┤
 HIGH SQL注入风险 user.js:45│ CWE-89
 MEDIUM XSS攻击风险 post.jsx:78│ CWE-79
 MEDIUM 硬编码敏感信息 config.js:12│ CWE-798│
 LOW 弱密码策略 auth.js:23│ CWE-521
└──────────┴─────────────────────────────────────┴──────────┴─────────┘

 详细问题:

1. SQL注入风险 (HIGH)
   位置: src/models/user.js:45
   代码: query = `SELECT * FROM users WHERE id = $\{userId}`
   
    风险: 直接拼接用户输入到SQL查询中
    修复: 使用参数化查询
   
   修复代码:
   ```javascript
   // 修复前
   const query = `SELECT * FROM users WHERE id = $\{userId}`;
   
   // 修复后  
   const query = 'SELECT * FROM users WHERE id = ?';
   const result = await db.query(query, [userId]);
  1. XSS攻击风险 (MEDIUM) 位置: src/components/post.jsx:78

    jsx
    // 代码示例
    <div dangerouslySetInnerHTML={{__html: userContent}} />

    风险: 直接渲染用户HTML内容 修复: 使用HTML净化库

    修复代码:

    jsx
    import DOMPurify from 'dompurify';
    
    // 修复后
    <div dangerouslySetInnerHTML={{
      __html: DOMPurify.sanitize(userContent)
    }} />

依赖安全检查

bash
# 检查第三方依赖漏洞
claude analyze --type security --focus dependencies

示例输出:

text
依赖安全分析
============

 依赖统计:
• 总依赖数: 234
• 存在漏洞: 12 个
• 高危漏洞: 3 个

 高危漏洞:
- lodash v4.17.10 - CVE-2019-10744 - 建议升级到 >=4.17.12
- express v4.16.0 - CVE-2022-24999 - 建议升级到 >=4.18.2  
- react-scripts v3.4.0 - Multiple - 建议升级到 >=5.0.1

快速修复命令:

bash
npm audit fix --force
yarn audit --fix

3. 性能分析 (Performance)

性能瓶颈分析

bash
# 性能分析
claude analyze --type performance

# 重点分析渲染性能
claude analyze --type performance --focus rendering

示例输出:

bash
性能分析报告
============

 性能评分: C+ (65/100)

 性能问题:
┌──────────────────────────────────────┬──────────┬─────────────┐
 问题 严重性 影响
├──────────────────────────────────────┼──────────┼─────────────┤
 组件不必要重渲染 HIGH UI响应慢
 大数组操作阻塞主线程 HIGH 页面卡顿
 未优化的数据库查询 MEDIUM 响应延迟
 过大的JavaScript包 MEDIUM 加载慢
└──────────────────────────────────────┴──────────┴─────────────┘

 详细分析:

1. React组件重渲染问题
   文件: src/components/ProductList.jsx
   
    问题: ProductList 组件每次都重新渲染所有商品
    优化: 使用 React.memo useMemo
   
   ```jsx
   // 优化前
   const ProductList = (\{ products, onSelect }) => \{
     return products.map(product => (
       <ProductCard 
         key={product.id}
         product={product}
         onClick={() => onSelect(product)}
       />
     ));
   \};
   
   // 优化后
   const ProductList = React.memo((\{ products, onSelect }) => \{
     const memoizedProducts = useMemo(() => 
       products.map(product => (\{
         ...product,
         onClick: () => onSelect(product)
       \})), [products, onSelect]
     );
     
     return memoizedProducts.map(product => (
       <MemoizedProductCard key={product.id} {...product} />
     ));
   \});
  1. 数据库查询性能 文件: src/services/productService.js

    问题: N+1 查询问题,每个产品单独查询类别 优化: 使用JOIN查询或数据预加载

    javascript
    // 优化前
    const getProductsWithCategories = async () => \{
      const products = await Product.findAll();
      for (let product of products) \{
        product.category = await Category.findById(product.categoryId);
      \}
      return products;
    \};
    
    // 优化后
    const getProductsWithCategories = async () => \{
      return await Product.findAll(\{
        include: [Category]
      \});
    \};

4. 架构分析 (Architecture)

依赖关系分析

bash
# 架构分析
claude analyze --type architecture

# 模块依赖分析
claude analyze --type architecture --focus dependencies

示例输出:

架构分析报告
============

 架构健康度: B (78/100)

 模块统计:
• 总模块数: 156
• 平均依赖数: 8.2
• 循环依赖: 3 个
• 紧耦合模块: 12 个

 循环依赖检测:
┌─────────────────────────────────────────────────────────────┐
│ 循环依赖链                                                  │
├─────────────────────────────────────────────────────────────┤
│ UserService → OrderService → PaymentService → UserService  │
│ ComponentA → ComponentB → ComponentC → ComponentA          │
│ utils/api → utils/auth → utils/storage → utils/api        │
└─────────────────────────────────────────────────────────────┘

 模块耦合度分析:
┌────────────────────────┬──────────┬──────────┬─────────┐
│ 模块                   │ 入度     │ 出度     │ 耦合度  │
├────────────────────────┼──────────┼──────────┼─────────┤
│ src/utils/helpers.js   │ 23       │ 2        │ HIGH    │
│ src/services/api.js    │ 18       │ 5        │ HIGH    │
│ src/store/index.js     │ 15       │ 8        │ MEDIUM  │
└────────────────────────┴──────────┴──────────┴─────────┘

 架构建议:
• 解除 UserService 和 OrderService 的循环依赖
• 重构 utils/helpers.js,拆分成专门的工具模块
• 引入依赖注入减少模块间的直接依赖

技术债务分析

bash
# 技术债务分析
claude analyze --type architecture --focus tech-debt

示例输出:

技术债务分析
============

 技术债务评估: $47,000 (预估修复成本)

 债务趋势:  增长中 (+12% vs 上月)

 债务分类:
┌─────────────────┬──────────┬──────────────┬─────────────┐
│ 类型            │ 问题数   │ 预估工时     │ 优先级      │  
├─────────────────┼──────────┼──────────────┼─────────────┤
│ 代码质量        │ 23       │ 45h          │ HIGH        │
│ 过期依赖        │ 18       │ 20h          │ MEDIUM      │
│ 测试覆盖        │ 12       │ 60h          │ HIGH        │  
│ 文档缺失        │ 15       │ 25h          │ LOW         │
│ 性能问题        │ 8        │ 35h          │ MEDIUM      │
└─────────────────┴──────────┴──────────────┴─────────────┘

 修复建议 (按ROI排序):
1. 修复关键性能问题 (投资回报率: 8.5x)
2. 增加单元测试覆盖率 (投资回报率: 6.2x)  
3. 重构复杂函数 (投资回报率: 4.8x)
4. 升级过期依赖 (投资回报率: 3.1x)

报告生成

HTML 报告

bash
# 生成完整HTML报告
claude analyze --report analysis-report.html

# 生成特定类型报告
claude analyze --type security --format html --report security-report.html

JSON 数据导出

bash
# 导出JSON格式数据
claude analyze --format json --output analysis-data.json

# 用于CI/CD集成
claude analyze --format json --quiet > analysis-results.json

报告示例预览

HTML 报告结构

html
<!DOCTYPE html>
<html>
<head>
    <title>Claude Code 分析报告</title>
    <style>
        /* 现代化样式 */
    </style>
</head>
<body>
    <div class="report-container">
        <header class="report-header">
            <h1>代码分析报告</h1>
            <div class="report-meta">
                <span>生成时间: 2024-01-20 14:30:00</span>
                <span>项目: MyProject</span>
                <span>版本: v1.2.0</span>
            </div>
        </header>
        
        <section class="summary">
            <h2>总体概览</h2>
            <div class="metrics-grid">
                <div class="metric-card">
                    <h3>代码质量</h3>
                    <div class="score">B+</div>
                    <div class="progress">82%</div>
                </div>
                <!-- 更多指标卡片 -->
            </div>
        </section>
        
        <section class="details">
            <!-- 详细分析内容 -->
        </section>
    </div>
</body>
</html>

自定义配置

配置文件

javascript
// claude.analyze.config.js
export default \{
  // 分析规则配置
  rules: \{
    // 代码质量规则
    quality: \{
      complexity: \{
        cyclomatic: { max: 10, warn: 6 },
        cognitive: { max: 15, warn: 10 }
      \},
      duplication: \{
        threshold: 5,
        minLines: 10
      \}
    \},
    
    // 安全规则
    security: \{
      vulnerabilities: ['high', 'medium'],
      dependencies: \{
        allowKnownVulns: false,
        maxAge: '1 year'
      \}
    \},
    
    // 性能规则
    performance: \{
      bundleSize: { max: '2MB', warn: '1MB' },
      renderTime: { max: 100, warn: 50 }
    \}
  },
  
  // 文件过滤
  include: ['src/**/*.{js,jsx,ts,tsx}'],
  exclude: [
    'node_modules/**',
    'dist/**',
    '**/*.test.{js,ts}',
    '**/*.spec.{js,ts}'
  ],
  
  // 输出配置
  output: \{
    format: 'html',
    template: 'modern',
    charts: true,
    trends: true
  \},
  
  // 集成配置
  integrations: \{
    sonarqube: \{
      enabled: true,
      url: 'http://sonar.example.com',
      token: process.env.SONAR_TOKEN
    \},
    github: \{
      enabled: true,
      annotations: true
    \}
  \}
\};

自定义分析器

javascript
// analyzers/custom-analyzer.js
export default class CustomAnalyzer \{
  constructor(options) \{
    this.options = options;
  \}
  
  async analyze(files) \{
    const results = [];
    
    for (const file of files) \{
      const issues = await this.analyzeFile(file);
      results.push(...issues);
    \}
    
    return results;
  \}
  
  async analyzeFile(file) \{
    // 自定义分析逻辑
    const issues = [];
    
    // 检查特定模式
    if (file.content.includes('console.log')) \{
      issues.push(\{
        type: 'quality',
        severity: 'low',
        message: '生产代码中包含console.log',
        line: this.findLine(file.content, 'console.log'),
        file: file.path
      \});
    \}
    
    return issues;
  \}
\}

CI/CD 集成

GitHub Actions

yaml
# .github/workflows/code-analysis.yml
name: Code Analysis

on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run code analysis
        run: |
          npx claude analyze --format json --output analysis.json
          npx claude analyze --type security --format sarif --output security.sarif
          
      - name: Upload analysis results
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: security.sarif
          
      - name: Comment PR
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const analysis = JSON.parse(fs.readFileSync('analysis.json'));
            
            const comment = `## 代码分析报告
            
            - 质量评分: $\{analysis.quality.score}
            - 安全问题: $\{analysis.security.issues.length}
            - 性能问题: $\{analysis.performance.issues.length}
            
            详细报告请查看Actions日志。`;
            
            github.rest.issues.createComment(\{
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            \});

质量门禁

javascript
// scripts/quality-gate.js
const fs = require('fs');

// 读取分析结果
const analysis = JSON.parse(fs.readFileSync('analysis.json'));

// 定义质量标准
const qualityGate = \{
  minQualityScore: 70,
  maxHighSeverityIssues: 0,
  maxMediumSeverityIssues: 5,
  maxTechDebt: 50000 // 美元
\};

// 检查质量门禁
let passed = true;
const failures = [];

if (analysis.quality.score < qualityGate.minQualityScore) \{
  passed = false;
  failures.push(`质量评分 $\{analysis.quality.score} 低于要求的 $\{qualityGate.minQualityScore}`);
\}

const highIssues = analysis.issues.filter(i => i.severity === 'high').length;
if (highIssues > qualityGate.maxHighSeverityIssues) \{
  passed = false;
  failures.push(`高严重性问题 $\{highIssues} 个,超过限制 $\{qualityGate.maxHighSeverityIssues}`);
\}

// 输出结果
if (passed) {
  console.log(' 质量门禁通过');
  process.exit(0);
\} else \{
  console.error(' 质量门禁失败:');
  failures.forEach(f => console.error(`  - $\{f}`));
  process.exit(1);
\}

相关命令

最佳实践

1. 定期分析

  • 在开发过程中定期运行分析
  • 集成到CI/CD流水线中
  • 设置质量门禁标准

2. 渐进式改进

  • 优先修复高严重性问题
  • 制定技术债务还款计划
  • 跟踪质量趋势变化

3. 团队协作

  • 分享分析报告给团队
  • 制定编码规范和质量标准
  • 定期回顾和改进分析配置

analyze 命令 - 洞察代码的智慧之眼

Claude Code 使用指南