@ttjl/ai-code-review 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example ADDED
@@ -0,0 +1,3 @@
1
+ # 阿里云百炼 API 配置
2
+ # 获取 API Key: https://bailian.console.aliyun.com/
3
+ DASHSCOPE_API_KEY=sk-48566cc7ac734ae1a1560f411ca3564d
package/Readme.md ADDED
@@ -0,0 +1,262 @@
1
+ # AI 驱动的代码审查工具
2
+
3
+ 基于 Git Hooks 和阿里云百炼 qwen-max 的自动化代码审查系统,用于在代码提交前验证代码质量、规范和潜在的安全问题。
4
+
5
+ ## ✨ 特性
6
+
7
+ - 🔍 **智能代码审查**: 使用阿里云百炼 qwen-max 进行深度代码分析
8
+ - 🚀 **自动化集成**: 通过 Git Hooks 在提交前自动触发
9
+ - 📝 **多文件类型支持**: 支持 JavaScript、TypeScript、Vue、CSS 等
10
+ - ⚙️ **灵活配置**: 支持自定义审查规则和输出格式
11
+ - 📊 **详细报告**: 生成控制台彩色输出和 JSON 格式报告
12
+ - 🎯 **问题分类**: 代码质量、安全、性能、最佳实践等多维度审查
13
+
14
+ ## 核心技术栈
15
+
16
+ - **Git Hooks 管理**: Lefthook
17
+ - **运行环境**: Node.js >= 18.0.0
18
+ - **AI SDK**: 阿里云百炼 SDK (@alicloud/ai-2024-06-01)
19
+ - **AI 模型**: qwen-max-latest
20
+
21
+ ## 📦 安装
22
+
23
+ ### 全局安装
24
+
25
+ ```bash
26
+ npm install -g @your-scope/ai-code-review
27
+ ```
28
+
29
+ ### 项目本地安装
30
+
31
+ ```bash
32
+ npm install -D @your-scope/ai-code-review
33
+ ```
34
+
35
+ ## 🚀 快速开始
36
+
37
+ ### 1. 配置 API Key
38
+
39
+ 有两种方式配置阿里云百炼 API Key:
40
+
41
+ #### 方式一: 在配置文件中配置(推荐)
42
+
43
+ 在 `.ai-reviewrc.json` 中直接配置:
44
+
45
+ ```json
46
+ {
47
+ "ai": {
48
+ "apiKey": "sk-your-api-key-here",
49
+ "model": "qwen-max-latest"
50
+ }
51
+ }
52
+ ```
53
+
54
+ #### 方式二: 使用环境变量
55
+
56
+ 创建 `.env` 文件:
57
+
58
+ ```bash
59
+ cp .env.example .env
60
+ ```
61
+
62
+ 编辑 `.env` 文件,添加你的阿里云百炼 API Key:
63
+
64
+ ```env
65
+ DASHSCOPE_API_KEY=your_dashscope_api_key_here
66
+ ```
67
+
68
+ **优先级**: 配置文件中的 API Key 优先级高于环境变量。
69
+
70
+ 获取 API Key: https://bailian.console.aliyun.com/
71
+
72
+ ### 2. 初始化配置
73
+
74
+ ```bash
75
+ ai-review init
76
+ ```
77
+
78
+ 这将创建 `.ai-reviewrc.json` 配置文件。
79
+
80
+ ### 3. 检查环境
81
+
82
+ ```bash
83
+ ai-review check
84
+ ```
85
+
86
+ ### 4. 手动触发审查
87
+
88
+ ```bash
89
+ ai-review review
90
+ ```
91
+
92
+ ## ⚙️ 配置
93
+
94
+ `.ai-reviewrc.json` 配置文件示例:
95
+
96
+ ```json
97
+ {
98
+ "review": {
99
+ "enabled": true,
100
+ "onFail": "block",
101
+ "maxFiles": 20
102
+ },
103
+ "files": {
104
+ "include": ["**/*.js", "**/*.ts", "**/*.tsx", "**/*.vue"],
105
+ "exclude": ["node_modules/**", "dist/**"]
106
+ },
107
+ "ai": {
108
+ "apiKey": "sk-your-api-key-here",
109
+ "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
110
+ "model": "qwen-max-latest",
111
+ "temperature": 0.3
112
+ },
113
+ "rules": {
114
+ "codeQuality": true,
115
+ "security": true,
116
+ "bestPractices": true
117
+ }
118
+ }
119
+ ```
120
+
121
+ **配置说明**:
122
+ - `ai.apiKey`: 阿里云百炼 API Key(可选,不配置则使用环境变量)
123
+ - `ai.baseUrl`: API 地址(可选,默认为阿里云百炼兼容模式地址)
124
+ - `ai.model`: 使用的模型名称(默认: qwen-max-latest)
125
+ - `ai.temperature`: 温度参数,控制输出随机性(0-1)
126
+ - `ai.maxTokens`: 最大 token 数
127
+
128
+ ## 📖 使用方法
129
+
130
+ ### 命令行工具
131
+
132
+ ```bash
133
+ # 执行代码审查
134
+ ai-review review
135
+
136
+ # 初始化配置文件
137
+ ai-review init
138
+
139
+ # 显示当前配置
140
+ ai-review config
141
+
142
+ # 检查环境配置
143
+ ai-review check
144
+ ```
145
+
146
+ ### Git Hooks 集成
147
+
148
+ 当你暂存文件并执行 `git commit` 时,代码审查会自动运行:
149
+
150
+ ```bash
151
+ git add .
152
+ git commit # 自动触发 AI 代码审查
153
+ ```
154
+
155
+ 如果发现问题,提交将被阻止(取决于 `review.onFail` 配置)。
156
+
157
+ ## 📊 审查报告
158
+
159
+ ### 控制台输出
160
+
161
+ ```
162
+ ============================================================
163
+ 代码审查总结
164
+ ============================================================
165
+
166
+ 📁 审查文件: 5
167
+ ❌ 错误: 2
168
+ ⚠️ 警告: 3
169
+ ℹ️ 提示: 1
170
+
171
+ ============================================================
172
+ ```
173
+
174
+ ### JSON 报告
175
+
176
+ 审查报告会保存在 `reports/` 目录下:
177
+
178
+ ```json
179
+ {
180
+ "timestamp": "2026-01-02T00:00:00.000Z",
181
+ "summary": {
182
+ "totalFiles": 5,
183
+ "totalIssues": 6,
184
+ "bySeverity": {
185
+ "error": 2,
186
+ "warning": 3,
187
+ "info": 1
188
+ }
189
+ },
190
+ "files": [...],
191
+ "issues": [...]
192
+ }
193
+ ```
194
+
195
+ ## 🛠️ 开发
196
+
197
+ ### 安装依赖
198
+
199
+ ```bash
200
+ npm install
201
+ ```
202
+
203
+ ### 运行测试
204
+
205
+ ```bash
206
+ npm test
207
+ ```
208
+
209
+ ### 代码检查
210
+
211
+ ```bash
212
+ npm run lint
213
+ ```
214
+
215
+ ### 格式化代码
216
+
217
+ ```bash
218
+ npm run format
219
+ ```
220
+
221
+ ## 📝 项目结构
222
+
223
+ ```
224
+ ai-code-review/
225
+ ├── src/
226
+ │ ├── core/ # 核心逻辑
227
+ │ │ ├── ai-client.js # AI 客户端
228
+ │ │ ├── config-loader.js # 配置加载器
229
+ │ │ ├── file-collector.js # 文件收集器
230
+ │ │ └── reviewer.js # 审查器
231
+ │ ├── formatters/ # 输出格式化
232
+ │ │ ├── console-formatter.js
233
+ │ │ └── json-formatter.js
234
+ │ ├── utils/ # 工具函数
235
+ │ │ ├── git.js
236
+ │ │ └── error-handler.js
237
+ │ └── cli/ # 命令行工具
238
+ │ └── index.js
239
+ ├── bin/ # 可执行命令
240
+ ├── config/ # 默认配置
241
+ ├── templates/ # 配置模板
242
+ ├── lefthook.yml # Git Hooks 配置
243
+ └── package.json
244
+ ```
245
+
246
+ ## ⚠️ 注意事项
247
+
248
+ ### API 配额
249
+
250
+ 阿里云百炼 API 有调用频率限制。如果遇到配额问题,可以考虑:
251
+
252
+ 1. 减少单次审查的文件数量 (`maxFiles`)
253
+ 2. 增加 API 调用间隔
254
+ 3. 查看 [阿里云百炼定价页面](https://bailian.console.aliyun.com/)了解详情
255
+
256
+ ## 🤝 贡献
257
+
258
+ 欢迎提交 Issue 和 Pull Request!
259
+
260
+ ## 📄 许可证
261
+
262
+ MIT License
package/bin/ai-review ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../src/cli/index');
@@ -0,0 +1,67 @@
1
+ module.exports = {
2
+ review: {
3
+ enabled: true,
4
+ onFail: 'block',
5
+ maxFileSize: 1024,
6
+ maxFiles: 20,
7
+ maxLineLength: 500
8
+ },
9
+ files: {
10
+ include: [
11
+ '**/*.js',
12
+ '**/*.jsx',
13
+ '**/*.ts',
14
+ '**/*.tsx',
15
+ '**/*.vue',
16
+ '**/*.css',
17
+ '**/*.scss',
18
+ '**/*.less'
19
+ ],
20
+ exclude: [
21
+ 'node_modules/**',
22
+ 'dist/**',
23
+ 'build/**',
24
+ '*.min.js',
25
+ '*.config.js',
26
+ 'coverage/**'
27
+ ]
28
+ },
29
+ ai: {
30
+ // API Key 可以在这里配置,也可以通过 DASHSCOPE_API_KEY 环境变量设置
31
+ // apiKey: 'your-dashscope-api-key-here',
32
+ baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
33
+ model: 'qwen-max-latest',
34
+ temperature: 0.3,
35
+ maxTokens: 4096,
36
+ timeout: 30000,
37
+ retry: {
38
+ times: 3,
39
+ delay: 1000
40
+ }
41
+ },
42
+ rules: {
43
+ codeQuality: true,
44
+ security: true,
45
+ bestPractices: true,
46
+ naming: true,
47
+ complexity: true,
48
+ performance: true
49
+ },
50
+ output: {
51
+ console: {
52
+ enabled: true,
53
+ format: 'pretty',
54
+ color: true
55
+ },
56
+ file: {
57
+ enabled: true,
58
+ path: './reports',
59
+ format: 'json',
60
+ filename: 'review-report-{timestamp}.json'
61
+ }
62
+ },
63
+ git: {
64
+ stagedOnly: true,
65
+ diffBase: 'HEAD'
66
+ }
67
+ };
package/lefthook.yml ADDED
@@ -0,0 +1,13 @@
1
+ pre-commit:
2
+ parallel: false
3
+ commands:
4
+ ai-code-review:
5
+ run: npx ai-review review
6
+ glob: "*.{js,jsx,ts,tsx,vue,css,scss,less}"
7
+ exclude:
8
+ - node_modules/**
9
+ - dist/**
10
+ - build/**
11
+ - "*.min.js"
12
+ - "*.config.js"
13
+ stage_fixed: true
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@ttjl/ai-code-review",
3
+ "version": "1.0.0",
4
+ "description": "AI 驱动的代码审查工具 - 基于 Git Hooks 和阿里百炼 qwen3-max 自动审查前端代码",
5
+ "main": "src/cli/index.js",
6
+ "bin": {
7
+ "ai-review": "./bin/ai-review"
8
+ },
9
+ "scripts": {
10
+ "lint": "eslint src/**/*.js",
11
+ "format": "prettier --write src/**/*.js",
12
+ "prepare": "lefthook install",
13
+ "review": "node src/cli/index.js review"
14
+ },
15
+ "keywords": [
16
+ "git",
17
+ "hook",
18
+ "code-review",
19
+ "ai",
20
+ "qwen",
21
+ "pre-commit",
22
+ "automated-review",
23
+ "code-quality",
24
+ "frontend"
25
+ ],
26
+ "author": "",
27
+ "license": "MIT",
28
+ "dependencies": {
29
+ "axios": "^1.6.0",
30
+ "chalk": "^4.1.2",
31
+ "commander": "^12.1.0",
32
+ "log-symbols": "^5.1.0",
33
+ "minimatch": "^8.0.4",
34
+ "async-retry": "^1.3.3",
35
+ "dotenv": "^16.4.5",
36
+ "ora": "^5.4.1"
37
+ },
38
+ "devDependencies": {
39
+ "lefthook": "^1.7.0",
40
+ "prettier": "^3.3.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=18.0.0"
44
+ },
45
+ "files": [
46
+ "src",
47
+ "bin",
48
+ "config",
49
+ "templates",
50
+ "lefthook.yml",
51
+ "README.md",
52
+ ".env.example"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ }
57
+ }
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { program } = require('commander');
4
+ const path = require('path');
5
+ const fs = require('fs').promises;
6
+ require('dotenv').config();
7
+
8
+ const ConfigLoader = require('../core/config-loader');
9
+ const CodeReviewer = require('../core/reviewer');
10
+
11
+ program
12
+ .name('ai-review')
13
+ .description('AI 驱动的代码审查工具 - 基于 Gemini 2.5')
14
+ .version('1.0.0');
15
+
16
+ program
17
+ .command('review')
18
+ .description('执行代码审查')
19
+ .option('-c, --config <path>', '配置文件路径')
20
+ .option('-m, --mode <mode>', '运行模式 (manual|pre-commit)', 'manual')
21
+ .option('--fail-on-error', '有错误时退出码为 1')
22
+ .action(async (options) => {
23
+ try {
24
+ // 加载配置
25
+ const config = await ConfigLoader.load(options.config);
26
+ ConfigLoader.validate(config);
27
+
28
+ // 执行审查
29
+ const reviewer = new CodeReviewer(config);
30
+ const result = await reviewer.review();
31
+
32
+ // 根据结果决定退出码
33
+ if (options.failOnError && !result.success) {
34
+ process.exit(1);
35
+ }
36
+
37
+ if (!result.success) {
38
+ process.exit(1);
39
+ }
40
+
41
+ process.exit(0);
42
+ } catch (error) {
43
+ console.error('❌ 审查失败:', error.message);
44
+ if (process.env.DEBUG) {
45
+ console.error(error.stack);
46
+ }
47
+ process.exit(1);
48
+ }
49
+ });
50
+
51
+ program
52
+ .command('init')
53
+ .description('初始化配置文件')
54
+ .action(async () => {
55
+ try {
56
+ const templatePath = path.join(
57
+ __dirname,
58
+ '../../templates/.ai-reviewrc.json'
59
+ );
60
+ const targetPath = path.join(process.cwd(), '.ai-reviewrc.json');
61
+
62
+ // 检查是否已存在配置文件
63
+ try {
64
+ await fs.access(targetPath);
65
+ console.log('⚠️ 配置文件已存在: .ai-reviewrc.json');
66
+ console.log('💡 如需重新生成,请先删除现有配置文件');
67
+ return;
68
+ } catch {
69
+ // 文件不存在,继续创建
70
+ }
71
+
72
+ await fs.copyFile(templatePath, targetPath);
73
+ console.log('✅ 配置文件已创建: .ai-reviewrc.json');
74
+ console.log('\n💡 提示:');
75
+ console.log(' 1. 请根据项目需求修改配置');
76
+ console.log(' 2. 确保 .env 文件包含 GEMINI_API_KEY');
77
+ console.log(' 3. 运行 `ai-review review` 测试配置');
78
+ } catch (error) {
79
+ console.error('❌ 创建配置文件失败:', error.message);
80
+ process.exit(1);
81
+ }
82
+ });
83
+
84
+ program
85
+ .command('config')
86
+ .description('显示当前配置')
87
+ .option('-c, --config <path>', '配置文件路径')
88
+ .action(async (options) => {
89
+ try {
90
+ const config = await ConfigLoader.load(options.config);
91
+ console.log(JSON.stringify(config, null, 2));
92
+ } catch (error) {
93
+ console.error('❌ 加载配置失败:', error.message);
94
+ process.exit(1);
95
+ }
96
+ });
97
+
98
+ program
99
+ .command('check')
100
+ .description('检查环境配置')
101
+ .action(async () => {
102
+ console.log('🔍 检查环境配置...\n');
103
+
104
+ const checks = [];
105
+
106
+ // 检查 Node 版本
107
+ const nodeVersion = process.version;
108
+ const minNodeVersion = '18.0.0';
109
+ const isNodeValid = nodeVersion >= 'v' + minNodeVersion;
110
+ checks.push({
111
+ name: 'Node.js 版本',
112
+ status: isNodeValid ? '✅' : '❌',
113
+ value: nodeVersion,
114
+ message: isNodeValid
115
+ ? `满足要求 (>= ${minNodeVersion})`
116
+ : `需要 >= ${minNodeVersion}`
117
+ });
118
+
119
+ // 检查 Git 仓库
120
+ const { execSync } = require('child_process');
121
+ let isGitRepo = false;
122
+ try {
123
+ execSync('git rev-parse --is-inside-work-tree', {
124
+ encoding: 'utf-8',
125
+ stdio: 'pipe'
126
+ });
127
+ isGitRepo = true;
128
+ } catch {}
129
+ checks.push({
130
+ name: 'Git 仓库',
131
+ status: isGitRepo ? '✅' : '⚠️ ',
132
+ value: isGitRepo ? '是' : '否',
133
+ message: isGitRepo ? '可以正常使用' : '某些功能可能不可用'
134
+ });
135
+
136
+ // 检查环境变量
137
+ const hasApiKey = !!process.env.GEMINI_API_KEY;
138
+ checks.push({
139
+ name: 'GEMINI_API_KEY',
140
+ status: hasApiKey ? '✅' : '❌',
141
+ value: hasApiKey
142
+ ? process.env.GEMINI_API_KEY.substring(0, 10) + '...'
143
+ : '未设置',
144
+ message: hasApiKey ? 'API Key 已配置' : '请在 .env 文件中设置'
145
+ });
146
+
147
+ // 检查配置文件
148
+ const configFiles = [
149
+ '.ai-reviewrc.json',
150
+ '.ai-reviewrc.js',
151
+ 'ai-review.config.js'
152
+ ];
153
+ let configFile = null;
154
+ for (const file of configFiles) {
155
+ try {
156
+ await fs.access(path.join(process.cwd(), file));
157
+ configFile = file;
158
+ break;
159
+ } catch {}
160
+ }
161
+ checks.push({
162
+ name: '配置文件',
163
+ status: configFile ? '✅' : '⚠️ ',
164
+ value: configFile || '未找到',
165
+ message: configFile
166
+ ? '使用自定义配置'
167
+ : '将使用默认配置(运行 ai-review init 创建)'
168
+ });
169
+
170
+ // 显示检查结果
171
+ checks.forEach(check => {
172
+ console.log(`${check.status} ${check.name}`);
173
+ console.log(` ${check.value}`);
174
+ console.log(` ${check.message}\n`);
175
+ });
176
+
177
+ // 总结
178
+ const hasErrors = checks.some(c => c.status === '❌');
179
+ if (hasErrors) {
180
+ console.log('❌ 环境检查失败,请修复上述问题');
181
+ process.exit(1);
182
+ } else {
183
+ console.log('✅ 环境检查通过!');
184
+ }
185
+ });
186
+
187
+ // 解析命令行参数
188
+ program.parse(process.argv);
189
+
190
+ // 如果没有参数,显示帮助
191
+ if (!process.argv.slice(2).length) {
192
+ program.outputHelp();
193
+ }