Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Code Guard 是一个强大的代码变更分析工具,专为现代前端项目设计。它通过分析 Git 变更记录,自动检测代码修改对项目的影响范围,帮助开发团队提高代码质量和开发效率。支持ai分析代码

License

Notifications You must be signed in to change notification settings

cloudbam/code-guard-ai

Open more actions menu

Repository files navigation

Code Guard

Code Guard Logo

基于 Git 的智能代码变更分析工具

npm version License: MIT Node.js Version TypeScript

📖 简介

Code Guard 是一个强大的代码变更分析工具,专为现代前端项目设计。它通过分析 Git 变更记录,自动检测代码修改对项目的影响范围,帮助开发团队提高代码质量和开发效率。

✨ 核心特性

  • 🔍 智能变更分析 - 基于 Git diff 自动分析代码变更影响范围
  • 🧩 插件化架构 - 灵活的插件系统,支持自定义检查规则
  • 📊 多格式报告 - 支持 JSON、Excel、HTML 等多种报告格式
  • 🎯 精准影响分析 - 深度分析公共方法变更的影响范围
  • 🚀 零配置启动 - 开箱即用,同时支持高度自定义配置
  • 🧪 强制安全过滤 - 全流程强制忽略 node_modules(含多层嵌套 / 组件内私有 node_modules)
  • 🛡️ 业务目录精细排除 - 支持通过 excludesreference.excludeDirs 精准忽略如 src/api/ 等目录
  • 🌐 多框架支持 - 支持 TypeScript、JavaScript、Vue.js 等主流技术栈

🚀 快速开始

安装

# 全局安装
npm install -g code-guard

# 或者在项目中安装
npm install --save-dev code-guard

1. 零配置快速开始

# 全局安装后直接使用
code-guard

# 本地安装后使用 npx
npx code-guard

# 或添加到 package.json scripts

package.json 中添加脚本:

{
  "scripts": {
    "code-check": "code-guard", // 默认配置
  }
}

然后运行:

npm run code-check
### 配置文件

在项目根目录创建 `code-guard.config.ts``code-guard.config.js` 文件:

```typescript
import { codeGuardUserConfig } from 'code-guard'

export default codeGuardUserConfig({
  git: { main: 'main' },
  // 全局排除(正则或简单通配形式,会与内置强制 node_modules 过滤叠加)
  excludes: [
    'dist/',          // 构建产物
    '.*.log',         // 日志
    'src/api/',       // 忽略 api 目录(也可写 api/)
  ],
  reference: {
    enable: true,
    rootDir: './src',
    excludeDirs: ['api/', '.umi', 'mock/'] // 影响“公共方法检查”扫描和 diff 参与
  },
  filePathDiff: {
    enable: true,
    ignorePatterns: ['*.tmp'],
    // debug: true  // 开启后可查看过滤统计(亦可用环境变量 CODE_GUARD_DEBUG=1)
  },
  plugins: []
})

> 提示:`node_modules/` 已被内置强制过滤,无需再额外写入;若你写了不会产生冲突。

🔧 内置插件

Code Guard 提供了丰富的内置插件,覆盖代码质量检查的各个方面:

1. 版本检查插件 (Version Plugin)

检查 package.json 版本变更和依赖版本一致性。

{
  version: {
    enable: true,
    checkPackageJson: true,
    checkLockFile: true
  }
}

2. 依赖检查插件 (Package Plugin)

分析依赖项变更,检查 package.json 配置。

{
  package: {
    enable: true,
    checkDependencies: true,
    checkScripts: true,
    checkFields: ['name', 'version', 'description']
  }
}

3. 路由变更检查插件 (Routing Plugin)

监控路由文件变更,分析路由配置影响。

{
  routing: {
    enable: true,
    patterns: [
      '**/router.ts',
      '**/routes.js',
      '**/pages/**/*.vue',
      'config/routes.ts'
    ],
    alertLevel: {
      pageRouteChange: 'warning',
      routeFileDeletion: 'error'
    }
  }
}

4. 公共方法影响分析插件 (Reference Plugin)

核心功能 - 分析公共方法变更的影响范围,生成详细的引用关系报告。

{
  reference: {
    enable: true,
    fileExtensions: ['.ts', '.tsx', '.js', '.jsx', '.vue'],
    rootDir: './src',
    // excludeDirs 改进:支持写 'api/' 或 'src/api/',内部会自动归一化并在 diff 阶段二次剔除
    excludeDirs: ['api/', '.umi', 'mock/']
  }
}

功能特点:

  • 🔍 自动识别导出方法变更
  • 📈 构建完整的引用关系树
  • 📊 生成 Excel 和 JSON 格式报告
  • 🎯 支持直接引用和间接引用分析
  • 🌐 支持 TypeScript、JavaScript、Vue、js 文件

5. 变更日志检查插件 (Changelog Plugin)

检查 CHANGELOG.md 文件更新情况。

{
  changelog: {
    enable: true,
    filePath: 'CHANGELOG.md',
    requiredSections: ['Added', 'Changed', 'Fixed']
  }
}

6. 文件路径差异检查插件 (File Path Diff Plugin)

分析文件路径变更,检测文件重命名和删除。

{
  filePathDiff: {
    enable: true,
    ignorePatterns: ['*.log', '*.tmp'], // node_modules/** 已内置
    maxFileSize: 1024 * 1024,
    // debug: true // 输出过滤后的重命名/删除统计与排除模式
  }
}

### 7. 强制过滤策略说明

| 阶段 | 机制 | 行为 |
| ---- | ---- | ---- |
| Git 变更收集 | `utils/git.ts` | 任何包含 `node_modules/` 的路径直接排除 |
| 业务文件扫描 | `reference/pathResolver` | 进入目录前判断立即跳过 node_modules |
| 引用解析 | `resolveImportPath` |  `node_modules` 片段的 import 不再尝试解析内部源码 |
| 变更遍历 | `reference/index.ts` | changed 文件列表再次二次过滤 node_modules/  excludeDirs |
| 文件路径差异 | file-diff 插件 | 合并 `excludes + ignorePatterns` 后过滤 renamed / deleted |

> 结果:无论 node_modules 位于主根还是嵌套于组件包(例如 `src/lms-pc-components/node_modules/...`),都不会进入分析或报告。

### 8. 调试模式

开启任一方式:
```bash
CODE_GUARD_DEBUG=1 npx code-guard

或在配置:

filePathDiff: { debug: true }

调试输出示例:

[file-diff][debug] 排除模式:
  - src/api/.*
  - src/api/
[reference][debug] skip changed in node_modules: src/xxx/node_modules/pkg/index.js
公共方法检查:已剔除 node_modules 文件 42 个

## 📊 报告格式

### 控制台输出

🚀 开始执行代码检查插件

🤖 ✔ [版本检查] 版本检查通过 (45ms)

🤖 ⚠ [公共方法检查] 发现 2 个文件的 3 个导出项发生变更,影响 8 个直接引用 (156ms)

🤖 ✔ [路由变更检查] 路由检查通过 (23ms)

📊 执行总结: 总插件数:6 ✅ 通过:4 ⚠️ 警告:2 ❌ 错误:0 ⏱️ 总耗时:287ms


### Excel 报告

公共方法影响分析插件会生成详细的 Excel 报告,包含:

- **影响概览** - 变更文件和影响统计
- **详细分析** - 每个变更方法的引用详情
- **引用关系图** - 可视化的依赖关系

### JSON / HTML 报告

结构化的 JSON 数据,便于集成到 CI/CD 流程:

```json
{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "summary": {
    "totalFiles": 2,
    "totalBlocks": 3,
    "totalDirectReferences": 8,
    "totalIndirectReferences": 0
  },
  "references": [
    {
      "filePath": "src/utils/helper.ts",
      "exportBlocks": [
        {
          "name": "formatDate",
          "directReferences": ["src/components/DatePicker.vue"],
          "indirectReferences": []
        }
      ]
    }
  ]
}

🛠️ 高级配置

自定义插件开发

import { CodeGuardConfigPlugin, AlertLevel } from 'code-guard'

const customPlugin = (): CodeGuardConfigPlugin => ({
  name: 'custom-check',
  commander: '自定义检查',
  
  async resolved({ config, diffFiles, mainFileResolver }) {
    // 实现自定义检查逻辑
    const hasIssues = false // 你的检查逻辑
    
    return {
      level: hasIssues ? AlertLevel.warning : AlertLevel.passed,
      description: hasIssues ? '发现问题' : '检查通过',
      end: async () => {
        // 可选的后续处理逻辑
        console.log('自定义插件执行完成')
      }
    }
  }
})

export default codeGuardUserConfig({
  plugins: [customPlugin()]
})

CI/CD 集成

GitHub Actions

name: Code Guard Check
on: [push, pull_request]

jobs:
  code-guard:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run Code Guard
        run: npx code-guard

GitLab CI

code-guard:
  stage: test
  image: node:18
  script:
    - npm ci
    - npx code-guard
  artifacts:
    reports:
      junit: code-guard-report.xml
    paths:
      - "*.xlsx"
      - "*.json"

📁 项目结构

code-guard/
├── src/
│   ├── cli/                 # 命令行接口
│   ├── core/               # 核心功能
│   │   ├── config/         # 配置管理
│   │   ├── executor/       # 插件执行器
│   │   └── types/          # 类型定义
│   ├── plugins/            # 内置插件
│   │   └── built-in/       # 内置插件实现
│   └── utils/              # 工具函数
├── examples/               # 示例配置
├── docs/                   # 文档
└── test/                   # 测试文件

🔍 常见问题 (FAQ)

Q: 为什么我写了 node_modules/** 仍然看到相关日志?
A: 可能来自其他工具或旧版本缓存。请确认使用的是本地构建:node ./lib/src/cli/index.js --version

Q: 如何完全忽略某个业务子目录 (如 src/api/)?
A: 在 excludessrc/api/,同时在 reference.excludeDirsapi/,两层过滤;调试模式下应看到跳过统计。

Q: 我需要分析特定内置包(在 node_modules 下)?
A: 当前为强制排除策略,可考虑后续提供白名单机制(欢迎提 Issue)。

Q: 过滤规则是 glob 还是正则?
A: 顶层 excludes 目前使用简单字符串/正则构造测试;filePathDiff.ignorePatterns 支持简单通配(*?)。后续计划扩展完整 glob。

🗺️ Roadmap(节选)

  • 完整 glob (**、字符集、反向 ! 支持)
  • White-list 机制允许特定 node_modules 包分析
  • 引用图可视化 Web 页面
  • CI 产物(JUnit / SARIF)输出
  • plugin 执行耗时统计面板

🤝 贡献

欢迎提交 Issue / PR 改进过滤或性能。如果你在使用中发现无法过滤的路径,请附带:

  1. 真实相对路径
  2. 你的 code-guard.config.* 相关片段
  3. 运行命令与版本号

📄 许可证

MIT License

About

Code Guard 是一个强大的代码变更分析工具,专为现代前端项目设计。它通过分析 Git 变更记录,自动检测代码修改对项目的影响范围,帮助开发团队提高代码质量和开发效率。支持ai分析代码

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
Morty Proxy This is a proxified and sanitized view of the page, visit original site.