job51-gitlab-cr-node-skill-prompt-optimize 1.3.7 → 1.3.9

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/index.js CHANGED
@@ -1,535 +1,628 @@
1
- #!/usr/bin/env node
2
-
3
- const { spawn } = require('child_process');
4
- const path = require('path');
5
- const fs = require('fs');
6
- const { GitLabAPIClient, debugLog, extractReportContent } = require('./utils');
7
-
8
- class GitLabCodeReviewer {
9
- constructor(gitlabToken, gitlabUrl = null) {
10
- debugLog(`GitLab客户端初始化: ${gitlabUrl}`);
11
- this.gitlabClient = new GitLabAPIClient(gitlabToken, gitlabUrl);
12
- }
13
-
14
- /**
15
- * 获取合并请求的diff信息
16
- * @param {number} projectId GitLab项目ID
17
- * @param {number} mergeRequestIid 合并请求IID
18
- * @returns {Promise<Array>} diff块数组
19
- */
20
- async getMergeRequestDiffs(projectId, mergeRequestIid) {
21
- debugLog(`开始获取项目 ${projectId} 合并请求 ${mergeRequestIid} 的diff信息`);
22
- try {
23
- let allDiffs = [];
24
- let page = 1;
25
- const perPage = 20;
26
-
27
- do {
28
- const url = `/projects/${projectId}/merge_requests/${mergeRequestIid}/diffs?per_page=${perPage}&page=${page}`;
29
- const data = await this.gitlabClient.callGitLabAPI(url);
30
-
31
- if (data && data.length > 0) {
32
- allDiffs = allDiffs.concat(data);
33
- debugLog(`成功获取到第${page}页,${data.length}个diff块`);
34
- page++;
35
- } else {
36
- break; // 没有更多数据
37
- }
38
- } while (true);
39
-
40
- debugLog(`总共获取到 ${allDiffs.length} 个diff块`);
41
- return allDiffs;
42
- } catch (error) {
43
- console.error('获取diff信息失败:', error.message);
44
- throw error;
45
- }
46
- }
47
-
48
-
49
-
50
- /**
51
- * 使用Claude对单个diff块进行代码审核
52
- * @param {Object} diff 单个diff对象
53
- * @returns {Promise<string>} 审核结果
54
- */
55
- async reviewDiffWithClaude(diff) {
56
- debugLog(`开始审核文件: ${diff.new_path || diff.old_path}, diff长度: ${diff.diff.length}`);
57
-
58
- // 读取模板文件内容 - 支持多种路径查找
59
- let templateContent = '';
60
- const possibleTemplatePaths = [
61
- path.resolve(__dirname, '../mr-review-template.md'), // 从项目根目录查找
62
- path.resolve(__dirname, './mr-review-template.md'), // 从当前目录查找
63
- path.resolve(process.cwd(), 'mr-review-template.md'), // 从当前工作目录查找
64
- ];
65
-
66
- for (const templatePath of possibleTemplatePaths) {
67
- try {
68
- templateContent = fs.readFileSync(templatePath, 'utf8');
69
- // 将模板中的{{CODE_CHANGES}}替换为实际的diff内容
70
- templateContent = templateContent.replace('{{CODE_CHANGES}}', diff.diff);
71
- // 将行信息添加到模版中
72
- templateContent = templateContent.replace('{{LINE_INFO}}', diff.line_msg);
73
- break;
74
- } catch (error) {
75
- continue; // 尝试下一个路径
76
- }
77
- }
78
-
79
- // 如果没有找到模板文件,使用默认的prompt
80
- if (!templateContent) {
81
- console.warn('未找到模板文件,使用默认模板');
82
- templateContent =
83
- `你是一个代码审核员,请从以下角度进行审核,并输出中文报告:
84
- 0. 请先输出行号
85
- 1. 代码质量问题
86
- 2. 安全漏洞
87
- 3. 性能问题
88
- 4. 最佳实践
89
- 5. 代码风格
90
- 请对以下代码变更进行审核:
91
- ${diff.diff}
92
- `;
93
- }
94
-
95
- const prompt = templateContent;
96
-
97
- // 最多重试3次,直到结果包含"AI代码审查结果"或达到最大重试次数
98
- let attempts = 0;
99
- const maxAttempts = 5;
100
-
101
- while (attempts < maxAttempts) {
102
- attempts++;
103
- try {
104
- debugLog(`调用本地AI命令审核文件 (尝试 ${attempts}/${maxAttempts})`);
105
-
106
- // 直接将prompt内容传递给Claude命令
107
- const claudeResult = await runClaudeCommand(prompt);
108
-
109
- debugLog(`本地AI命令审核完成文件`);
110
-
111
- // 检查结果是否包含"AI代码审查结果",如果包含则返回结果
112
- if (claudeResult && claudeResult.includes('AI代码审查结果')) {
113
- debugLog(`AI审核成功,包含"AI代码审查结果" (尝试 ${attempts})`);
114
-
115
- // 提取REPORT标签内容并返回
116
- return extractReportContent(claudeResult);
117
- } else {
118
- debugLog(`AI审核结果不包含"AI代码审查结果" (尝试 ${attempts}),将重试...`);
119
- if (attempts >= maxAttempts) {
120
- debugLog(`已达到最大重试次数 ${maxAttempts},返回最后一次结果,${claudeResult}`);
121
-
122
- // 提取REPORT标签内容并返回
123
- return extractReportContent(claudeResult);
124
- }
125
- }
126
- } catch (error) {
127
- console.error(`AI审核失败 (尝试 ${attempts}/${maxAttempts}):`, error.message);
128
- if (attempts >= maxAttempts) {
129
- return `审核失败: ${error.message}`;
130
- }
131
- // 等待一段时间后重试
132
- await new Promise(resolve => setTimeout(resolve, 1000 * attempts)); // 递增等待时间
133
- }
134
- }
135
- }
136
-
137
- /**
138
- * 对合并请求的所有diff进行审核(逐个处理并立即发布评论)
139
- * @param {number} projectId GitLab项目ID
140
- * @param {number} mergeRequestIid 合并请求IID
141
- * @returns {Promise<Array>} 审核结果数组
142
- */
143
- async reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency = 3) {
144
- debugLog(`开始审核项目 ${projectId} 的合并请求 ${mergeRequestIid}`);
145
-
146
- // 获取diff信息
147
- const diffs = await this.getMergeRequestDiffs(projectId, mergeRequestIid);
148
- debugLog(`获取到 ${diffs.length} 个diff块`);
149
-
150
- // 对每个diff进一步按变更块拆分并审核
151
- debugLog('开始处理所有diff块的变更块拆分');
152
-
153
- // 创建处理单个块的函数
154
- const processBlock = async (diffObject, blockIndex) => {
155
- // 审核当前块
156
- const review_result = await this.reviewDiffWithClaude(diffObject);
157
- const blockObj = { ...diffObject, review_result };
158
-
159
- // 检查审查结果中是否包含严重问题,只有包含严重问题才发布评论
160
- if (blockObj.review_result && blockObj.review_result.includes('🔴 严重问题')) {
161
- // 立即发布评论
162
- await this.postSingleCommentToGitLab(projectId, mergeRequestIid, {
163
- diff_info: blockObj,
164
- block_index: blockObj.block_index,
165
- review_result: blockObj.review_result,
166
- });
167
- } else {
168
- debugLog(`该块不包含严重问题,跳过评论发布: ${blockObj.new_path || blockObj.old_path}#${blockObj.block_index}`);
169
- }
170
-
171
- return {
172
- diff_info: blockObj,
173
- block_index: blockObj.block_index,
174
- review_result: blockObj.review_result,
175
- };
176
- };
177
-
178
- // 收集所有需要处理的块
179
- const allBlocks = [];
180
- for (const diff of diffs) {
181
- const diffObjects = this.getDiffBlocks(diff);
182
- for (let i = 0; i < diffObjects.length; i++) {
183
- // 更新块索引
184
- diffObjects[i].block_index = i;
185
- allBlocks.push({ diffObject: diffObjects[i], blockIndex: i });
186
- }
187
- }
188
-
189
- // 使用线程池控制并发数量
190
- const results = await this.processWithThreadPool(allBlocks, processBlock, maxConcurrency);
191
-
192
- debugLog(`总共处理了 ${results.length} 个diff block块`);
193
-
194
- debugLog('所有diff块审核并发布评论完成');
195
-
196
- return results;
197
- }
198
-
199
- /**
200
- * 使用线程池控制并发执行
201
- * @param {Array} tasks 任务数组
202
- * @param {Function} processor 任务处理器
203
- * @param {number} maxConcurrency 最大并发数
204
- * @returns {Promise<Array>} 处理结果数组
205
- */
206
- async processWithThreadPool(tasks, processor, maxConcurrency = 3) {
207
- debugLog(`开始使用线程池处理 ${tasks.length} 个任务,最大并发数: ${maxConcurrency}`);
208
-
209
- const results = [];
210
- const executing = [];
211
-
212
- for (let i = 0; i < tasks.length; i++) {
213
- const task = tasks[i];
214
-
215
- // 创建一个异步任务
216
- const promise = processor(task.diffObject, task.blockIndex)
217
- .then(result => {
218
- results.push(result);
219
- // 从执行队列中移除已完成的任务
220
- const index = executing.indexOf(promise);
221
- if (index !== -1) {
222
- executing.splice(index, 1);
223
- }
224
- debugLog(`----------任务完成: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
225
- return result;
226
- });
227
-
228
- executing.push(promise);
229
-
230
- debugLog(`----------开始处理任务: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
231
-
232
- // 如果达到最大并发数,等待至少一个任务完成
233
- if (executing.length >= maxConcurrency) {
234
- await Promise.race(executing);
235
- }
236
- }
237
-
238
- // 等待所有剩余任务完成
239
- await Promise.all(executing);
240
-
241
- debugLog(`线程池处理完成,共处理 ${results.length} 个任务`);
242
-
243
- return results;
244
- }
245
-
246
- /**
247
- * 按照变更块分割数组并提取行号信息
248
- * @param {Object} diffObj 包含diff内容和文件信息的对象
249
- * @returns {Array} 包含diff块内容和行号信息的对象数组
250
- */
251
- getDiffBlocks(diffObj) {
252
- const regex = /(?=@@\s-\d+(?:,\d+)?\s\+\d+(?:,\d+)?\s@@)/g;
253
- const diffBlocks = diffObj.diff.split(regex);
254
- // 过滤掉空块并提取行号信息
255
- return diffBlocks
256
- .filter(block => block.trim() !== '')
257
- .map(block => {
258
- // 解析diff头信息 @@ -old_start,old_count +new_start,new_count @@
259
- const headerRegex = /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
260
- const headerMatch = block.match(headerRegex);
261
-
262
- // 取block第一行是否是加号或者减号开头还是没有开头,block需要用.split(/\r?\n/)
263
- const firstLine = block.split(/\r?\n/)[1];
264
- // 取出第一行的第一个字符
265
- const firstLineFirstChar = firstLine.charAt(0);
266
-
267
- let old_start = 0;
268
- let old_count = 0;
269
- let new_start = 0;
270
- let new_count = 0;
271
-
272
- if (headerMatch) {
273
- old_start = parseInt(headerMatch[1], 10);
274
- old_count = headerMatch[2] ? parseInt(headerMatch[2], 10) : 1;
275
- new_start = parseInt(headerMatch[3], 10);
276
- new_count = headerMatch[4] ? parseInt(headerMatch[4], 10) : 1;
277
- }
278
-
279
- return {
280
- diff: block,
281
- new_path: diffObj.new_path,
282
- old_path: diffObj.old_path,
283
- a_mode: diffObj.a_mode,
284
- b_mode: diffObj.b_mode,
285
- new_file: diffObj.new_file,
286
- renamed_file: diffObj.renamed_file,
287
- deleted_file: diffObj.deleted_file,
288
- generated_file: diffObj.generated_file,
289
- block_index: null, // 会在后续分配
290
- line_info: {
291
- old_start,
292
- old_count,
293
- new_start,
294
- new_count,
295
- firstLineFirstChar
296
- },
297
- line_msg:headerMatch
298
- };
299
- });
300
- }
301
-
302
- /**
303
- * 获取合并请求的最新版本信息
304
- * @param {number} projectId GitLab项目ID
305
- * @param {number} mergeRequestIid 合并请求IID
306
- * @returns {Promise<Object>} 版本信息
307
- */
308
- async getMergeRequestVersions(projectId, mergeRequestIid) {
309
- try {
310
- const data = await this.gitlabClient.callGitLabAPI(
311
- `/projects/${projectId}/merge_requests/${mergeRequestIid}/versions`
312
- );
313
- // 返回最新版本信息
314
- return data[0] || null;
315
- } catch (error) {
316
- console.error('获取MR版本信息失败:', error.message);
317
- throw error;
318
- }
319
- }
320
-
321
- /**
322
- * 发布单个评论到GitLab MR
323
- * @param {number} projectId GitLab项目ID
324
- * @param {number} mergeRequestIid 合并请求IID
325
- * @param {Object} result 单个审核结果
326
- */
327
- async postSingleCommentToGitLab(projectId, mergeRequestIid, result) {
328
- try {
329
- const { diff_info, review_result, block_index } = result;
330
- const file_path = diff_info.new_path || diff_info.old_path;
331
- const file_path_with_line = `${file_path}#L${block_index}`;
332
-
333
- // 获取MR版本信息
334
- const versionInfo = await this.getMergeRequestVersions(projectId, mergeRequestIid);
335
- if (!versionInfo) {
336
- console.error('无法获取MR版本信息');
337
- return;
338
- }
339
-
340
- const baseSha = versionInfo.base_commit_sha;
341
- const headSha = versionInfo.head_commit_sha;
342
- const startSha = versionInfo.start_commit_sha;
343
-
344
- debugLog(`获取到版本信息 - base: ${baseSha}, head: ${headSha}, start: ${startSha}`);
345
-
346
- // 直接使用diff_info中的line_info
347
- const lineInfo = diff_info.line_info;
348
-
349
- if (!lineInfo) {
350
- // 如果没有行号信息,创建一般讨论
351
- await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
352
- debugLog(`评论已发布到文件 ${file_path_with_line} (无法解析行号)`);
353
- return;
354
- }
355
-
356
- // 如果lineInfo里的firstLineFirstChar为+,则targetLine为new_path的new_start行;为-,则targetLine为old_path的old_start行;否则new和old都要赋值
357
- const targetLine = lineInfo.firstLineFirstChar === '+'
358
- ? { new_line: lineInfo.new_start, new_path: diff_info.new_path }
359
- : lineInfo.firstLineFirstChar === '-'
360
- ? { old_line: lineInfo.old_start, old_path: diff_info.old_path }
361
- : { new_line: lineInfo.new_start, new_path: diff_info.new_path, old_line: lineInfo.old_start, old_path: diff_info.old_path };
362
-
363
- if (targetLine) {
364
- // 创建diff评论
365
- const payload = {
366
- body: review_result,
367
- position: {
368
- position_type: 'text',
369
- base_sha: baseSha,
370
- head_sha: headSha,
371
- start_sha: startSha,
372
- ...targetLine
373
- }
374
- };
375
-
376
- try {
377
- await this.createDiffDiscussion(projectId, mergeRequestIid, payload);
378
- debugLog(`评论已发布到文件 ${file_path_with_line} 的相关变更区域`);
379
- } catch (error) {
380
- console.error(`发布评论到文件 ${file_path_with_line} 的变更区域失败,改用一般讨论:`, error.message);
381
- await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
382
- debugLog(`评论已发布到文件 ${file_path_with_line} (作为一般讨论)`);
383
- }
384
- } else {
385
- // 如果没有找到任何行号,创建一般讨论
386
- await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
387
- debugLog(`评论已发布到文件 ${file_path_with_line} (无特定行号)`);
388
- }
389
- } catch (error) {
390
- console.error('发布单个评论到GitLab失败:', error.message);
391
- throw error;
392
- }
393
- }
394
-
395
- /**
396
- * 发布评论到GitLab MR
397
- * @param {number} projectId GitLab项目ID
398
- * @param {number} mergeRequestIid 合并请求IID
399
- * @param {Array} reviewResults 审核结果数组
400
- */
401
- async postCommentsToGitLab(projectId, mergeRequestIid, reviewResults) {
402
- // 保持原有的批量发布方法,以防需要兼容旧的调用
403
- for (const result of reviewResults) {
404
- await this.postSingleCommentToGitLab(projectId, mergeRequestIid, result);
405
- }
406
- }
407
-
408
- /**
409
- * 创建一般讨论
410
- * @param {number} projectId GitLab项目ID
411
- * @param {number} mergeRequestIid 合并请求IID
412
- * @param {string} file_path 文件路径
413
- * @param {string} review_result 审核结果
414
- */
415
- async createGeneralDiscussion(projectId, mergeRequestIid, file_path, review_result) {
416
- const discussionData = {
417
- body: `**代码审核评论 - 文件: ${file_path}**\n\n${review_result}`
418
- };
419
-
420
- await this.gitlabClient.callGitLabAPI(
421
- `/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
422
- { method: 'POST', data: discussionData }
423
- );
424
- }
425
-
426
- /**
427
- * 创建diff讨论
428
- * @param {number} projectId GitLab项目ID
429
- * @param {number} mergeRequestIid 合并请求IID
430
- * @param {Object} payload 讨论数据
431
- */
432
- async createDiffDiscussion(projectId, mergeRequestIid, payload) {
433
- await this.gitlabClient.callGitLabAPI(
434
- `/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
435
- { method: 'POST', data: payload }
436
- );
437
- }
438
- }
439
-
440
- // 主函数
441
- async function main() {
442
- debugLog('开始加载环境变量');
443
- // 从环境变量获取配置
444
- const gitlabUrl = process.env.CI_API_V4_URL;
445
- const gitlabToken = process.env.GITLAB_ACCESS_TOKEN;
446
- const projectId = process.env.CI_PROJECT_ID;
447
- const mergeRequestIid = process.env.CI_MERGE_REQUEST_IID;
448
- // 获取最大并发数配置,默认为3
449
- const maxConcurrency = parseInt(process.env.GITLAB_CR_CONCURRENCY || 3);
450
-
451
- debugLog(`环境变量加载完成:`);
452
- debugLog(` GITLAB_API_V4_URL: ${gitlabUrl}`);
453
- debugLog(` GITLAB_TOKEN存在: ${!!gitlabToken}`);
454
- debugLog(` GITLAB_PROJECT_ID: ${projectId}`);
455
- debugLog(` GITLAB_MERGE_REQUEST_IID: ${mergeRequestIid}`);
456
- debugLog(` 设置最大并发数: ${maxConcurrency}`);
457
-
458
- if (!gitlabToken || !projectId || !mergeRequestIid) {
459
- console.error('缺少必要的环境变量配置');
460
- console.error('请设置: CI_API_V4_URL, GITLAB_ACCESS_TOKEN, CI_PROJECT_ID, CI_MERGE_REQUEST_IID');
461
- process.exit(1);
462
- }
463
-
464
- const reviewer = new GitLabCodeReviewer(gitlabToken, gitlabUrl);
465
-
466
- try {
467
- // 审核合并请求 - 现在会在每个块审核后立即发布评论
468
- debugLog('开始审核合并请求并发布评论...');
469
- await reviewer.reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency);
470
- debugLog('所有评论已成功发布到GitLab MR');
471
- console.log('代码审核完成!');
472
- } catch (error) {
473
- console.error('审核过程出错:', error);
474
- process.exit(1);
475
- }
476
- }
477
-
478
- // 辅助函数:执行本地Claude命令
479
- function runClaudeCommand(promptContent) {
480
- return new Promise((resolve, reject) => {
481
- // 创建当前目录下的临时文件
482
- const tmpFileName = `./temp-prompt-${Date.now()}.md`;
483
- debugLog('临时文件路径:', tmpFileName);
484
-
485
- // 将prompt内容写入临时文件
486
- fs.writeFileSync(tmpFileName, promptContent);
487
-
488
- debugLog("AI review命令开始时间")
489
- // 使用spawn替代exec,更安全地处理命令执行并实现环境隔离
490
- const claudeProcess = spawn('claude', ['-p', tmpFileName], {
491
- shell: true, // ✅ 启用 shell,支持别名和完整 PATH
492
- env: process.env,
493
- stdio: ['ignore', 'pipe', 'pipe']
494
- });
495
-
496
- let stdout = '';
497
- let stderr = '';
498
-
499
- claudeProcess.stdout.on('data', (data) => {
500
- stdout += data.toString();
501
- });
502
-
503
- claudeProcess.stderr.on('data', (data) => {
504
- stderr += data.toString();
505
- });
506
-
507
- claudeProcess.on('close', (code) => {
508
- debugLog("AI review命令结束时间")
509
- // 清理临时文件
510
- try {
511
- fs.unlinkSync(tmpFileName);
512
- } catch (cleanupError) {
513
- console.error('清理临时文件失败:', cleanupError.message);
514
- }
515
- resolve(stdout.trim());
516
- });
517
-
518
- claudeProcess.on('error', (error) => {
519
- // 出错时也要清理临时文件
520
- try {
521
- fs.unlinkSync(tmpFileName);
522
- } catch (cleanupError) {
523
- console.error('清理临时文件失败:', cleanupError.message);
524
- }
525
- reject(new Error(`AI命令执行出错: ${error.message}, 错误输出: ${stderr || '无错误输出'}`));
526
- });
527
- });
528
- }
529
-
530
- // 如果直接运行此文件,则执行主函数
531
- if (require.main === module) {
532
- main();
533
- }
534
-
535
- module.exports = GitLabCodeReviewer;
1
+ #!/usr/bin/env node
2
+
3
+ const { spawn } = require('child_process');
4
+ const path = require('path');
5
+ const fs = require('fs');
6
+ const { GitLabAPIClient, debugLog, extractReportContent } = require('./utils');
7
+
8
+ class GitLabCodeReviewer {
9
+ constructor(gitlabToken, gitlabUrl = null) {
10
+ debugLog(`GitLab客户端初始化: ${gitlabUrl}`);
11
+ this.gitlabClient = new GitLabAPIClient(gitlabToken, gitlabUrl);
12
+ }
13
+
14
+ /**
15
+ * 获取合并请求的diff信息
16
+ * @param {number} projectId GitLab项目ID
17
+ * @param {number} mergeRequestIid 合并请求IID
18
+ * @returns {Promise<Array>} diff块数组
19
+ */
20
+ async getMergeRequestDiffs(projectId, mergeRequestIid) {
21
+ debugLog(`开始获取项目 ${projectId} 合并请求 ${mergeRequestIid} 的diff信息`);
22
+ try {
23
+ let allDiffs = [];
24
+ let page = 1;
25
+ const perPage = 20;
26
+
27
+ do {
28
+ const url = `/projects/${projectId}/merge_requests/${mergeRequestIid}/diffs?per_page=${perPage}&page=${page}`;
29
+ const data = await this.gitlabClient.callGitLabAPI(url);
30
+
31
+ if (data && data.length > 0) {
32
+ allDiffs = allDiffs.concat(data);
33
+ debugLog(`成功获取到第${page}页,${data.length}个diff块`);
34
+ page++;
35
+ } else {
36
+ break; // 没有更多数据
37
+ }
38
+ } while (true);
39
+
40
+ debugLog(`总共获取到 ${allDiffs.length} 个diff块`);
41
+ return allDiffs;
42
+ } catch (error) {
43
+ console.error('获取diff信息失败:', error.message);
44
+ throw error;
45
+ }
46
+ }
47
+
48
+
49
+
50
+ /**
51
+ * 使用Claude对单个diff块进行代码审核
52
+ * @param {Object} diff 单个diff对象
53
+ * @returns {Promise<string>} 审核结果
54
+ */
55
+ async reviewDiffWithClaude(diff) {
56
+ debugLog(`开始审核文件: ${diff.new_path || diff.old_path}, diff长度: ${diff.diff.length}`);
57
+
58
+ const prompt = `使用技能进行代码审查,变更内容:${diff.diff}`;
59
+
60
+ debugLog(`开始调用本地AI命令审核文件, prompt:${prompt}`)
61
+ // 最多重试3次,直到结果包含"🤖 AI 代码审查结果"或达到最大重试次数
62
+ let attempts = 0;
63
+ const maxAttempts = 5;
64
+
65
+ while (attempts < maxAttempts) {
66
+ attempts++;
67
+ try {
68
+ debugLog(`调用本地AI命令审核文件 (尝试 ${attempts}/${maxAttempts})`);
69
+
70
+ // 直接将prompt内容传递给Claude命令
71
+ const claudeResult = await runClaudeCommand(prompt);
72
+
73
+ debugLog(`本地AI命令审核完成,AI审核结果: ${claudeResult}`);
74
+
75
+ // 检查结果是否包含"🤖 AI 代码审查结果",如果包含则返回结果
76
+ if (claudeResult && claudeResult.includes('🤖 AI 代码审查结果')) {
77
+ debugLog(`AI审核成功,包含"🤖 AI 代码审查结果" (尝试 ${attempts})`);
78
+
79
+
80
+ // 提取REPORT标签内容并返回
81
+ return extractReportContent(claudeResult);
82
+ } else {
83
+ debugLog(`AI审核结果不包含"🤖 AI 代码审查结果" (尝试 ${attempts}),将重试...`);
84
+ if (attempts >= maxAttempts) {
85
+ debugLog(`已达到最大重试次数 ${maxAttempts},返回最后一次结果,${claudeResult}`);
86
+
87
+ // 提取REPORT标签内容并返回
88
+ return extractReportContent(claudeResult);
89
+ }
90
+ }
91
+ } catch (error) {
92
+ console.error(`AI审核失败 (尝试 ${attempts}/${maxAttempts}):`, error.message);
93
+ if (attempts >= maxAttempts) {
94
+ return `审核失败: ${error.message}`;
95
+ }
96
+ // 等待一段时间后重试
97
+ await new Promise(resolve => setTimeout(resolve, 1000 * attempts)); // 递增等待时间
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 对合并请求的所有diff进行审核(逐个处理并立即发布评论)
104
+ * @param {number} projectId GitLab项目ID
105
+ * @param {number} mergeRequestIid 合并请求IID
106
+ * @returns {Promise<Array>} 审核结果数组
107
+ */
108
+ async reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency = 3) {
109
+ debugLog(`开始审核项目 ${projectId} 的合并请求 ${mergeRequestIid}`);
110
+
111
+ // 获取diff信息
112
+ const diffs = await this.getMergeRequestDiffs(projectId, mergeRequestIid);
113
+ debugLog(`获取到 ${diffs.length} 个diff块`);
114
+
115
+ // 对每个diff进一步按变更块拆分并审核
116
+ debugLog('开始处理所有diff块的变更块拆分');
117
+
118
+ // 创建处理单个块的函数
119
+ const processBlock = async (diffObject, blockIndex) => {
120
+ // 创建临时文件存储diff内容,文件地址选择当前文件夹下,避免权限问题
121
+ const fileName = `temp-diff-block-${Date.now()}-${blockIndex}.diff`;
122
+ const tmpFileName = path.join(process.cwd(), fileName);
123
+
124
+ try {
125
+ // 构造包含元数据的 diff 内容
126
+ const diffContentWithMetadata = `=== File Information ===
127
+ New Path: ${diffObject.new_path || 'N/A'}
128
+ Old Path: ${diffObject.old_path || 'N/A'}
129
+ Block Index: ${blockIndex}
130
+ === Diff Content ===
131
+ ${diffObject.diff}`;
132
+
133
+ // 将diff内容写入临时文件
134
+ fs.writeFileSync(tmpFileName, diffContentWithMetadata);
135
+
136
+ // 审核当前块(传入临时的文件而不是直接的diff内容)
137
+ const review_result = await this.reviewDiffWithClaudeUsingFile(tmpFileName);
138
+ const blockObj = { ...diffObject, review_result, temp_file_path: tmpFileName };
139
+
140
+ // 检查审查结果中是否包含严重问题,只有包含严重问题才发布评论
141
+ if (blockObj.review_result && blockObj.review_result.includes('🔴 严重问题')) {
142
+ // 立即发布评论
143
+ console.log(`🤖 AI 代码审查结果: ${blockObj.review_result}`);
144
+ await this.postSingleCommentToGitLab(projectId, mergeRequestIid, {
145
+ diff_info: blockObj,
146
+ block_index: blockObj.block_index,
147
+ review_result: blockObj.review_result,
148
+ });
149
+ } else {
150
+ debugLog(`该块不包含严重问题,跳过评论发布: ${blockObj.new_path || blockObj.old_path}#${blockObj.block_index}`);
151
+ }
152
+
153
+ return {
154
+ diff_info: blockObj,
155
+ block_index: blockObj.block_index,
156
+ review_result: blockObj.review_result,
157
+ temp_file_path: tmpFileName,
158
+ };
159
+ } catch (error) {
160
+ throw error;
161
+ } finally {
162
+ try {
163
+ if (fs.existsSync(tmpFileName)) {
164
+ fs.unlinkSync(tmpFileName);
165
+ }
166
+ } catch (cleanupError) {
167
+ console.error('清理临时文件失败:', cleanupError.message);
168
+ }
169
+ }
170
+ };
171
+
172
+ // 收集所有需要处理的块
173
+ const allBlocks = [];
174
+ for (const diff of diffs) {
175
+ const diffObjects = this.getDiffBlocks(diff);
176
+ for (let i = 0; i < diffObjects.length; i++) {
177
+ // 更新块索引
178
+ diffObjects[i].block_index = i;
179
+ allBlocks.push({ diffObject: diffObjects[i], blockIndex: i });
180
+ }
181
+ }
182
+
183
+ // 使用线程池控制并发数量
184
+ const results = await this.processWithThreadPool(allBlocks, processBlock, maxConcurrency);
185
+
186
+ debugLog(`总共处理了 ${results.length} 个diff block块`);
187
+
188
+ debugLog('所有diff块审核并发布评论完成');
189
+
190
+ return results;
191
+ }
192
+
193
+ /**
194
+ * 使用Claude对单个diff文件进行代码审核
195
+ * @param {string} filePath 临时文件路径
196
+ * @returns {Promise<string>} 审核结果
197
+ */
198
+ async reviewDiffWithClaudeUsingFile(filePath) {
199
+ debugLog(`开始审核文件: ${filePath}`);
200
+
201
+ const prompt = `请调用 simple-code-review 技能审核代码变更。
202
+ 文件路径:${filePath}
203
+
204
+ 输出要求:
205
+ 1. 严格按照 .claude/skills/simple-code-review/SKILL.md 中定义的模板格式输出
206
+ 2. **每个模块不是必须的**:没有对应问题时,完全省略该模块(不输出标题)
207
+ 3. 必须以 <REPORT> 开始,以 </REPORT> 结束
208
+ 4. 不要输出任何额外的解释、问候或总结文本`;
209
+ //打印
210
+ debugLog(`Claude命令: ${prompt}`);
211
+ // 最多重试5次,直到结果包含"🤖 AI 代码审查结果"或达到最大重试次数
212
+ let attempts = 0;
213
+ const maxAttempts = 5;
214
+
215
+ while (attempts < maxAttempts) {
216
+ attempts++;
217
+ try {
218
+ debugLog(`调用本地AI命令审核文件 (尝试 ${attempts}/${maxAttempts})`);
219
+
220
+ // 直接将prompt内容(包含文件路径)传递给Claude命令
221
+ const claudeResult = await runClaudeCommand(prompt);
222
+ //若结果为空,则记录日志
223
+ if (!claudeResult) {
224
+ debugLog(`本地AI命令审核结果为空`);
225
+ }
226
+ debugLog(`本地AI命令审核完成,审核结果为:${claudeResult}`);
227
+ // 检查结果是否包含"🤖 AI 代码审查结果",如果包含则返回结果
228
+ if (claudeResult && claudeResult.includes('🤖 AI 代码审查结果')) {
229
+ debugLog(`AI审核成功,包含"🤖 AI 代码审查结果" (尝试 ${attempts})`);
230
+
231
+ // 提取REPORT标签内容并返回
232
+ return extractReportContent(claudeResult);
233
+ } else {
234
+ debugLog(`AI审核结果不包含"🤖 AI 代码审查结果" (尝试 ${attempts}),将重试...`);
235
+ if (attempts >= maxAttempts) {
236
+ debugLog(`已达到最大重试次数 ${maxAttempts},返回最后一次结果,${claudeResult}`);
237
+
238
+ // 提取REPORT标签内容并返回
239
+ return extractReportContent(claudeResult);
240
+ }
241
+ }
242
+ } catch (error) {
243
+ console.error(`AI审核失败 (尝试 ${attempts}/${maxAttempts}):`, error.message);
244
+ if (attempts >= maxAttempts) {
245
+ return `审核失败: ${error.message}`;
246
+ }
247
+ // 等待一段时间后重试
248
+ await new Promise(resolve => setTimeout(resolve, 1000 * attempts)); // 递增等待时间
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * 使用线程池控制并发执行
255
+ * @param {Array} tasks 任务数组
256
+ * @param {Function} processor 任务处理器
257
+ * @param {number} maxConcurrency 最大并发数
258
+ * @returns {Promise<Array>} 处理结果数组
259
+ */
260
+ async processWithThreadPool(tasks, processor, maxConcurrency = 3) {
261
+ debugLog(`开始使用线程池处理 ${tasks.length} 个任务,最大并发数: ${maxConcurrency}`);
262
+
263
+ const results = [];
264
+ const executing = [];
265
+
266
+ for (let i = 0; i < tasks.length; i++) {
267
+ const task = tasks[i];
268
+
269
+ // 创建一个异步任务
270
+ const promise = processor(task.diffObject, task.blockIndex)
271
+ .then(result => {
272
+ results.push(result);
273
+ // 从执行队列中移除已完成的任务
274
+ const index = executing.indexOf(promise);
275
+ if (index !== -1) {
276
+ executing.splice(index, 1);
277
+ }
278
+ debugLog(`----------任务完成: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
279
+ return result;
280
+ });
281
+
282
+ executing.push(promise);
283
+
284
+ debugLog(`----------开始处理任务: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
285
+
286
+ // 如果达到最大并发数,等待至少一个任务完成
287
+ if (executing.length >= maxConcurrency) {
288
+ await Promise.race(executing);
289
+ }
290
+ }
291
+
292
+ // 等待所有剩余任务完成
293
+ await Promise.all(executing);
294
+
295
+ debugLog(`线程池处理完成,共处理 ${results.length} 个任务`);
296
+
297
+ return results;
298
+ }
299
+
300
+ /**
301
+ * 按照变更块分割数组并提取行号信息
302
+ * @param {Object} diffObj 包含diff内容和文件信息的对象
303
+ * @returns {Array} 包含diff块内容和行号信息的对象数组
304
+ */
305
+ getDiffBlocks(diffObj) {
306
+ const regex = /(?=@@\s-\d+(?:,\d+)?\s\+\d+(?:,\d+)?\s@@)/g;
307
+ const diffBlocks = diffObj.diff.split(regex);
308
+ // 过滤掉空块并提取行号信息
309
+ return diffBlocks
310
+ .filter(block => block.trim() !== '')
311
+ .map(block => {
312
+ // 解析diff头信息 @@ -old_start,old_count +new_start,new_count @@
313
+ const headerRegex = /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
314
+ const headerMatch = block.match(headerRegex);
315
+
316
+ // 取block第一行是否是加号或者减号开头还是没有开头,block需要用.split(/\r?\n/)
317
+ const firstLine = block.split(/\r?\n/)[1];
318
+ // 取出第一行的第一个字符
319
+ const firstLineFirstChar = firstLine.charAt(0);
320
+
321
+ let old_start = 0;
322
+ let old_count = 0;
323
+ let new_start = 0;
324
+ let new_count = 0;
325
+
326
+ if (headerMatch) {
327
+ old_start = parseInt(headerMatch[1], 10);
328
+ old_count = headerMatch[2] ? parseInt(headerMatch[2], 10) : 1;
329
+ new_start = parseInt(headerMatch[3], 10);
330
+ new_count = headerMatch[4] ? parseInt(headerMatch[4], 10) : 1;
331
+ }
332
+
333
+ return {
334
+ diff: block,
335
+ new_path: diffObj.new_path,
336
+ old_path: diffObj.old_path,
337
+ a_mode: diffObj.a_mode,
338
+ b_mode: diffObj.b_mode,
339
+ new_file: diffObj.new_file,
340
+ renamed_file: diffObj.renamed_file,
341
+ deleted_file: diffObj.deleted_file,
342
+ generated_file: diffObj.generated_file,
343
+ block_index: null, // 会在后续分配
344
+ line_info: {
345
+ old_start,
346
+ old_count,
347
+ new_start,
348
+ new_count,
349
+ firstLineFirstChar
350
+ }
351
+ };
352
+ });
353
+ }
354
+
355
+
356
+ /**
357
+ * LINE_INFO 标签中解析行号信息
358
+ * @param {string} reviewResult 审查结果文本
359
+ * @returns {Object|null} 行号信息对象 {new_path, new_line, old_path, old_line} 或 null
360
+ */
361
+ parseLineInfoFromReviewResult(reviewResult) {
362
+ if (!reviewResult) return null;
363
+
364
+ // 解析<LINE_INFO>[{"new_path":"xxx","new_line":87,"old_path":"yyy","old_line":85}]</LINE_INFO>格式
365
+ const lineInfoRegex = /<LINE_INFO>([\s\S]*?)<\/LINE_INFO>/;
366
+ const match = reviewResult.match(lineInfoRegex);
367
+
368
+ if (match) {
369
+ try {
370
+ const lineInfoJson = match[1].trim();
371
+ const lineInfoArray = JSON.parse(lineInfoJson);
372
+
373
+ if (Array.isArray(lineInfoArray) && lineInfoArray.length > 0) {
374
+ debugLog(`从 LINE_INFO 中解析出行号信息:${JSON.stringify(lineInfoArray)}`);
375
+ // 返回第一个问题的行号信息(后续可扩展为支持多个问题分别评论)
376
+ const lineInfo = lineInfoArray[0];
377
+ // 构建符合 GitLab API 的 position 对象
378
+ const position = {
379
+ new_path: lineInfo.new_path,
380
+ new_line: lineInfo.new_line
381
+ };
382
+ // 可选字段:如果存在 old_path 和 old_line 也加入
383
+ if (lineInfo.old_path) {
384
+ position.old_path = lineInfo.old_path;
385
+ }
386
+ if (lineInfo.old_line) {
387
+ position.old_line = lineInfo.old_line;
388
+ }
389
+ return position;
390
+ }
391
+ } catch (error) {
392
+ debugLog(`解析 LINE_INFO JSON 失败:${error.message}`);
393
+ }
394
+ }
395
+
396
+ debugLog('无法从 LINE_INFO 中解析行号,将使用 diff 块起始行号作为后备方案');
397
+ return null;
398
+ }
399
+
400
+ /**
401
+ * 获取合并请求的最新版本信息
402
+ * @param {number} projectId GitLab项目ID
403
+ * @param {number} mergeRequestIid 合并请求IID
404
+ * @returns {Promise<Object>} 版本信息
405
+ */
406
+ async getMergeRequestVersions(projectId, mergeRequestIid) {
407
+ try {
408
+ const data = await this.gitlabClient.callGitLabAPI(
409
+ `/projects/${projectId}/merge_requests/${mergeRequestIid}/versions`
410
+ );
411
+ // 返回最新版本信息
412
+ return data[0] || null;
413
+ } catch (error) {
414
+ console.error('获取MR版本信息失败:', error.message);
415
+ throw error;
416
+ }
417
+ }
418
+
419
+ /**
420
+ * 发布单个评论到GitLab MR
421
+ * @param {number} projectId GitLab项目ID
422
+ * @param {number} mergeRequestIid 合并请求IID
423
+ * @param {Object} result 单个审核结果
424
+ */
425
+ async postSingleCommentToGitLab(projectId, mergeRequestIid, result) {
426
+ try {
427
+ const { diff_info, review_result, block_index } = result;
428
+ const file_path = diff_info.new_path || diff_info.old_path;
429
+ const file_path_with_line = `${file_path}#L${block_index}`;
430
+
431
+ // 获取MR版本信息
432
+ const versionInfo = await this.getMergeRequestVersions(projectId, mergeRequestIid);
433
+ if (!versionInfo) {
434
+ console.error('无法获取MR版本信息');
435
+ return;
436
+ }
437
+
438
+ const baseSha = versionInfo.base_commit_sha;
439
+ const headSha = versionInfo.head_commit_sha;
440
+ const startSha = versionInfo.start_commit_sha;
441
+
442
+ debugLog(`获取到版本信息 - base: ${baseSha}, head: ${headSha}, start: ${startSha}`);
443
+
444
+ // 直接使用diff_info中的line_info
445
+ const lineInfo = diff_info.line_info;
446
+
447
+ if (!lineInfo) {
448
+ // 如果没有行号信息,创建一般讨论
449
+ await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
450
+ debugLog(`评论已发布到文件 ${file_path_with_line} (无法解析行号)`);
451
+ return;
452
+ }
453
+
454
+ // 如果lineInfo里的firstLineFirstChar为+,则targetLine为new_path的new_start行;为-,则targetLine为old_path的old_start行;否则new和old都要赋值
455
+ let targetLine = lineInfo.firstLineFirstChar === '+'
456
+ ? { new_line: lineInfo.new_start, new_path: diff_info.new_path }
457
+ : lineInfo.firstLineFirstChar === '-'
458
+ ? { old_line: lineInfo.old_start, old_path: diff_info.old_path }
459
+ : { new_line: lineInfo.new_start, new_path: diff_info.new_path, old_line: lineInfo.old_start, old_path: diff_info.old_path };
460
+
461
+ const parsedLineInfo = this.parseLineInfoFromReviewResult(review_result);
462
+ if (parsedLineInfo) {
463
+ debugLog(`从 LINE_INFO 中解析出行号成功,使用解析后的行号覆盖 diff 块起始行号`);
464
+ targetLine = parsedLineInfo;
465
+ }
466
+
467
+
468
+ //打印targetLine
469
+ debugLog(`targetLine: ${JSON.stringify(targetLine)}`);
470
+
471
+ if (targetLine) {
472
+ // 创建diff评论
473
+ const payload = {
474
+ body: review_result,
475
+ position: {
476
+ position_type: 'text',
477
+ base_sha: baseSha,
478
+ head_sha: headSha,
479
+ start_sha: startSha,
480
+ ...targetLine
481
+ }
482
+ };
483
+
484
+ try {
485
+ await this.createDiffDiscussion(projectId, mergeRequestIid, payload);
486
+ debugLog(`评论已发布到文件 ${file_path_with_line} 的相关变更区域`);
487
+ } catch (error) {
488
+ console.error(`发布评论到文件 ${file_path_with_line} 的变更区域失败,改用一般讨论:`, error.message);
489
+ await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
490
+ debugLog(`评论已发布到文件 ${file_path_with_line} (作为一般讨论)`);
491
+ }
492
+ } else {
493
+ // 如果没有找到任何行号,创建一般讨论
494
+ await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
495
+ debugLog(`评论已发布到文件 ${file_path_with_line} (无特定行号)`);
496
+ }
497
+ } catch (error) {
498
+ console.error('发布单个评论到GitLab失败:', error.message);
499
+ throw error;
500
+ }
501
+ }
502
+
503
+ /**
504
+ * 发布评论到GitLab MR
505
+ * @param {number} projectId GitLab项目ID
506
+ * @param {number} mergeRequestIid 合并请求IID
507
+ * @param {Array} reviewResults 审核结果数组
508
+ */
509
+ async postCommentsToGitLab(projectId, mergeRequestIid, reviewResults) {
510
+ // 保持原有的批量发布方法,以防需要兼容旧的调用
511
+ for (const result of reviewResults) {
512
+ await this.postSingleCommentToGitLab(projectId, mergeRequestIid, result);
513
+ }
514
+ }
515
+
516
+ /**
517
+ * 创建一般讨论
518
+ * @param {number} projectId GitLab项目ID
519
+ * @param {number} mergeRequestIid 合并请求IID
520
+ * @param {string} file_path 文件路径
521
+ * @param {string} review_result 审核结果
522
+ */
523
+ async createGeneralDiscussion(projectId, mergeRequestIid, file_path, review_result) {
524
+ const discussionData = {
525
+ body: `**代码审核评论 - 文件: ${file_path}**\n\n${review_result}`
526
+ };
527
+
528
+ await this.gitlabClient.callGitLabAPI(
529
+ `/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
530
+ { method: 'POST', data: discussionData }
531
+ );
532
+ }
533
+
534
+ /**
535
+ * 创建diff讨论
536
+ * @param {number} projectId GitLab项目ID
537
+ * @param {number} mergeRequestIid 合并请求IID
538
+ * @param {Object} payload 讨论数据
539
+ */
540
+ async createDiffDiscussion(projectId, mergeRequestIid, payload) {
541
+ await this.gitlabClient.callGitLabAPI(
542
+ `/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
543
+ { method: 'POST', data: payload }
544
+ );
545
+ }
546
+ }
547
+
548
+ // 主函数
549
+ async function main() {
550
+ debugLog('开始加载环境变量');
551
+ // 从环境变量获取配置
552
+ const gitlabUrl = process.env.CI_API_V4_URL;
553
+ const gitlabToken = process.env.GITLAB_ACCESS_TOKEN;
554
+ const projectId = process.env.CI_PROJECT_ID;
555
+ const mergeRequestIid = process.env.CI_MERGE_REQUEST_IID;
556
+ // 获取最大并发数配置,默认为3
557
+ const maxConcurrency = parseInt(process.env.GITLAB_CR_CONCURRENCY || 3);
558
+
559
+ debugLog(`环境变量加载完成:`);
560
+ debugLog(` GITLAB_API_V4_URL: ${gitlabUrl}`);
561
+ debugLog(` GITLAB_TOKEN存在: ${!!gitlabToken}`);
562
+ debugLog(` GITLAB_PROJECT_ID: ${projectId}`);
563
+ debugLog(` GITLAB_MERGE_REQUEST_IID: ${mergeRequestIid}`);
564
+ debugLog(` 设置最大并发数: ${maxConcurrency}`);
565
+
566
+ if (!gitlabToken || !projectId || !mergeRequestIid) {
567
+ console.error('缺少必要的环境变量配置');
568
+ console.error('请设置: CI_API_V4_URL, GITLAB_ACCESS_TOKEN, CI_PROJECT_ID, CI_MERGE_REQUEST_IID');
569
+ process.exit(1);
570
+ }
571
+
572
+ const reviewer = new GitLabCodeReviewer(gitlabToken, gitlabUrl);
573
+
574
+ try {
575
+ // 审核合并请求 - 现在会在每个块审核后立即发布评论
576
+ debugLog('开始审核合并请求并发布评论...');
577
+ await reviewer.reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency);
578
+ debugLog('所有评论已成功发布到GitLab MR');
579
+ console.log('代码审核完成!');
580
+ } catch (error) {
581
+ console.error('审核过程出错:', error);
582
+ process.exit(1);
583
+ }
584
+ }
585
+
586
+ // 辅助函数:执行本地Claude命令
587
+ function runClaudeCommand(promptContent) {
588
+ return new Promise((resolve, reject) => {
589
+
590
+ // 使用当前工作目录,确保 Claude 能访问临时文件和项目代码
591
+ const projectDir = process.cwd();
592
+ debugLog("AI review命令开始时间, 工作目录:" + projectDir);
593
+
594
+ // 使用spawn替代exec,更安全地处理命令执行并实现环境隔离
595
+ const claudeProcess = spawn('claude', ['--tools', 'default', '-p', '--', promptContent], {
596
+ cwd: projectDir, // 使用项目目录,让 Claude 能访问项目代码作为上下文
597
+ env: process.env,
598
+ stdio: ['ignore', 'pipe', 'pipe']
599
+ });
600
+
601
+ let stdout = '';
602
+ let stderr = '';
603
+
604
+ claudeProcess.stdout.on('data', (data) => {
605
+ stdout += data.toString();
606
+ });
607
+
608
+ claudeProcess.stderr.on('data', (data) => {
609
+ stderr += data.toString();
610
+ });
611
+
612
+ claudeProcess.on('close', (code) => {
613
+ debugLog("AI review命令结束时间")
614
+ resolve(stdout.trim());
615
+ });
616
+
617
+ claudeProcess.on('error', (error) => {
618
+ reject(new Error(`AI命令执行出错: ${error.message}, 错误输出: ${stderr || '无错误输出'}`));
619
+ });
620
+ });
621
+ }
622
+
623
+ // 如果直接运行此文件,则执行主函数
624
+ if (require.main === module) {
625
+ main();
626
+ }
627
+
628
+ module.exports = GitLabCodeReviewer;