job51-gitlab-cr-node-skill-prompt-optimize 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/README.md +58 -0
- package/analyze_filepath.js +66 -0
- package/analyze_issue.js +68 -0
- package/debug_test.js +89 -0
- package/env_check.js +32 -0
- package/example.js +29 -0
- package/index.js +532 -0
- package/log.txt +519 -0
- package/mr-review-template.md +65 -0
- package/package.json +23 -0
- package/simulate_ci.js +57 -0
- package/simulate_no_claude.js +61 -0
- package/temp-diff-block-1772527822359-0.diff +10 -0
- package/temp-diff-block-1772527823803-2.diff +9 -0
- package/temp-diff-block-1772527949844-0.diff +10 -0
- package/temp-diff-block-1772527949860-2.diff +9 -0
- package/temp-diff-block-1772528045156-0.diff +10 -0
- package/temp-diff-block-1772528045169-1.diff +8 -0
- package/temp-diff-block-1772528045180-2.diff +9 -0
- package/temp-diff-block-1772528185915-0.diff +10 -0
- package/temp-diff-block-1772528185952-2.diff +9 -0
- package/test_claude_file_access.js +125 -0
- package/test_filepath.js +98 -0
- package/test_no_nested_session.js +117 -0
- package/test_path_recognition.js +119 -0
- package/utils.js +67 -0
package/index.js
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
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
|
+
break;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
continue; // 尝试下一个路径
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 如果没有找到模板文件,使用默认的prompt
|
|
78
|
+
if (!templateContent) {
|
|
79
|
+
console.warn('未找到模板文件,使用默认模板');
|
|
80
|
+
templateContent =
|
|
81
|
+
`你是一个代码审核员,请从以下角度进行审核,并输出中文报告:
|
|
82
|
+
0. 请先输出行号
|
|
83
|
+
1. 代码质量问题
|
|
84
|
+
2. 安全漏洞
|
|
85
|
+
3. 性能问题
|
|
86
|
+
4. 最佳实践
|
|
87
|
+
5. 代码风格
|
|
88
|
+
请对以下代码变更进行审核:
|
|
89
|
+
${diff.diff}
|
|
90
|
+
`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const prompt = templateContent;
|
|
94
|
+
|
|
95
|
+
// 最多重试3次,直到结果包含"AI代码审查结果"或达到最大重试次数
|
|
96
|
+
let attempts = 0;
|
|
97
|
+
const maxAttempts = 5;
|
|
98
|
+
|
|
99
|
+
while (attempts < maxAttempts) {
|
|
100
|
+
attempts++;
|
|
101
|
+
try {
|
|
102
|
+
debugLog(`调用本地AI命令审核文件 (尝试 ${attempts}/${maxAttempts})`);
|
|
103
|
+
|
|
104
|
+
// 直接将prompt内容传递给Claude命令
|
|
105
|
+
const claudeResult = await runClaudeCommand(prompt);
|
|
106
|
+
|
|
107
|
+
debugLog(`本地AI命令审核完成文件`);
|
|
108
|
+
|
|
109
|
+
// 检查结果是否包含"AI代码审查结果",如果包含则返回结果
|
|
110
|
+
if (claudeResult && claudeResult.includes('AI代码审查结果')) {
|
|
111
|
+
debugLog(`AI审核成功,包含"AI代码审查结果" (尝试 ${attempts})`);
|
|
112
|
+
|
|
113
|
+
// 提取REPORT标签内容并返回
|
|
114
|
+
return extractReportContent(claudeResult);
|
|
115
|
+
} else {
|
|
116
|
+
debugLog(`AI审核结果不包含"AI代码审查结果" (尝试 ${attempts}),将重试...`);
|
|
117
|
+
if (attempts >= maxAttempts) {
|
|
118
|
+
debugLog(`已达到最大重试次数 ${maxAttempts},返回最后一次结果,${claudeResult}`);
|
|
119
|
+
|
|
120
|
+
// 提取REPORT标签内容并返回
|
|
121
|
+
return extractReportContent(claudeResult);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch (error) {
|
|
125
|
+
console.error(`AI审核失败 (尝试 ${attempts}/${maxAttempts}):`, error.message);
|
|
126
|
+
if (attempts >= maxAttempts) {
|
|
127
|
+
return `审核失败: ${error.message}`;
|
|
128
|
+
}
|
|
129
|
+
// 等待一段时间后重试
|
|
130
|
+
await new Promise(resolve => setTimeout(resolve, 1000 * attempts)); // 递增等待时间
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 对合并请求的所有diff进行审核(逐个处理并立即发布评论)
|
|
137
|
+
* @param {number} projectId GitLab项目ID
|
|
138
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
139
|
+
* @returns {Promise<Array>} 审核结果数组
|
|
140
|
+
*/
|
|
141
|
+
async reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency = 3) {
|
|
142
|
+
debugLog(`开始审核项目 ${projectId} 的合并请求 ${mergeRequestIid}`);
|
|
143
|
+
|
|
144
|
+
// 获取diff信息
|
|
145
|
+
const diffs = await this.getMergeRequestDiffs(projectId, mergeRequestIid);
|
|
146
|
+
debugLog(`获取到 ${diffs.length} 个diff块`);
|
|
147
|
+
|
|
148
|
+
// 对每个diff进一步按变更块拆分并审核
|
|
149
|
+
debugLog('开始处理所有diff块的变更块拆分');
|
|
150
|
+
|
|
151
|
+
// 创建处理单个块的函数
|
|
152
|
+
const processBlock = async (diffObject, blockIndex) => {
|
|
153
|
+
// 审核当前块
|
|
154
|
+
const review_result = await this.reviewDiffWithClaude(diffObject);
|
|
155
|
+
const blockObj = { ...diffObject, review_result };
|
|
156
|
+
|
|
157
|
+
// 检查审查结果中是否包含严重问题,只有包含严重问题才发布评论
|
|
158
|
+
if (blockObj.review_result && blockObj.review_result.includes('🔴 严重问题')) {
|
|
159
|
+
// 立即发布评论
|
|
160
|
+
await this.postSingleCommentToGitLab(projectId, mergeRequestIid, {
|
|
161
|
+
diff_info: blockObj,
|
|
162
|
+
block_index: blockObj.block_index,
|
|
163
|
+
review_result: blockObj.review_result,
|
|
164
|
+
});
|
|
165
|
+
} else {
|
|
166
|
+
debugLog(`该块不包含严重问题,跳过评论发布: ${blockObj.new_path || blockObj.old_path}#${blockObj.block_index}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
diff_info: blockObj,
|
|
171
|
+
block_index: blockObj.block_index,
|
|
172
|
+
review_result: blockObj.review_result,
|
|
173
|
+
};
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// 收集所有需要处理的块
|
|
177
|
+
const allBlocks = [];
|
|
178
|
+
for (const diff of diffs) {
|
|
179
|
+
const diffObjects = this.getDiffBlocks(diff);
|
|
180
|
+
for (let i = 0; i < diffObjects.length; i++) {
|
|
181
|
+
// 更新块索引
|
|
182
|
+
diffObjects[i].block_index = i;
|
|
183
|
+
allBlocks.push({ diffObject: diffObjects[i], blockIndex: i });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 使用线程池控制并发数量
|
|
188
|
+
const results = await this.processWithThreadPool(allBlocks, processBlock, maxConcurrency);
|
|
189
|
+
|
|
190
|
+
debugLog(`总共处理了 ${results.length} 个diff block块`);
|
|
191
|
+
|
|
192
|
+
debugLog('所有diff块审核并发布评论完成');
|
|
193
|
+
|
|
194
|
+
return results;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* 使用线程池控制并发执行
|
|
199
|
+
* @param {Array} tasks 任务数组
|
|
200
|
+
* @param {Function} processor 任务处理器
|
|
201
|
+
* @param {number} maxConcurrency 最大并发数
|
|
202
|
+
* @returns {Promise<Array>} 处理结果数组
|
|
203
|
+
*/
|
|
204
|
+
async processWithThreadPool(tasks, processor, maxConcurrency = 3) {
|
|
205
|
+
debugLog(`开始使用线程池处理 ${tasks.length} 个任务,最大并发数: ${maxConcurrency}`);
|
|
206
|
+
|
|
207
|
+
const results = [];
|
|
208
|
+
const executing = [];
|
|
209
|
+
|
|
210
|
+
for (let i = 0; i < tasks.length; i++) {
|
|
211
|
+
const task = tasks[i];
|
|
212
|
+
|
|
213
|
+
// 创建一个异步任务
|
|
214
|
+
const promise = processor(task.diffObject, task.blockIndex)
|
|
215
|
+
.then(result => {
|
|
216
|
+
results.push(result);
|
|
217
|
+
// 从执行队列中移除已完成的任务
|
|
218
|
+
const index = executing.indexOf(promise);
|
|
219
|
+
if (index !== -1) {
|
|
220
|
+
executing.splice(index, 1);
|
|
221
|
+
}
|
|
222
|
+
debugLog(`----------任务完成: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
|
|
223
|
+
return result;
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
executing.push(promise);
|
|
227
|
+
|
|
228
|
+
debugLog(`----------开始处理任务: ${i + 1}/${tasks.length} (${((i + 1) / tasks.length * 100).toFixed(1)}%)----------`);
|
|
229
|
+
|
|
230
|
+
// 如果达到最大并发数,等待至少一个任务完成
|
|
231
|
+
if (executing.length >= maxConcurrency) {
|
|
232
|
+
await Promise.race(executing);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// 等待所有剩余任务完成
|
|
237
|
+
await Promise.all(executing);
|
|
238
|
+
|
|
239
|
+
debugLog(`线程池处理完成,共处理 ${results.length} 个任务`);
|
|
240
|
+
|
|
241
|
+
return results;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 按照变更块分割数组并提取行号信息
|
|
246
|
+
* @param {Object} diffObj 包含diff内容和文件信息的对象
|
|
247
|
+
* @returns {Array} 包含diff块内容和行号信息的对象数组
|
|
248
|
+
*/
|
|
249
|
+
getDiffBlocks(diffObj) {
|
|
250
|
+
const regex = /(?=@@\s-\d+(?:,\d+)?\s\+\d+(?:,\d+)?\s@@)/g;
|
|
251
|
+
const diffBlocks = diffObj.diff.split(regex);
|
|
252
|
+
// 过滤掉空块并提取行号信息
|
|
253
|
+
return diffBlocks
|
|
254
|
+
.filter(block => block.trim() !== '')
|
|
255
|
+
.map(block => {
|
|
256
|
+
// 解析diff头信息 @@ -old_start,old_count +new_start,new_count @@
|
|
257
|
+
const headerRegex = /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
|
|
258
|
+
const headerMatch = block.match(headerRegex);
|
|
259
|
+
|
|
260
|
+
// 取block第一行是否是加号或者减号开头还是没有开头,block需要用.split(/\r?\n/)
|
|
261
|
+
const firstLine = block.split(/\r?\n/)[1];
|
|
262
|
+
// 取出第一行的第一个字符
|
|
263
|
+
const firstLineFirstChar = firstLine.charAt(0);
|
|
264
|
+
|
|
265
|
+
let old_start = 0;
|
|
266
|
+
let old_count = 0;
|
|
267
|
+
let new_start = 0;
|
|
268
|
+
let new_count = 0;
|
|
269
|
+
|
|
270
|
+
if (headerMatch) {
|
|
271
|
+
old_start = parseInt(headerMatch[1], 10);
|
|
272
|
+
old_count = headerMatch[2] ? parseInt(headerMatch[2], 10) : 1;
|
|
273
|
+
new_start = parseInt(headerMatch[3], 10);
|
|
274
|
+
new_count = headerMatch[4] ? parseInt(headerMatch[4], 10) : 1;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
diff: block,
|
|
279
|
+
new_path: diffObj.new_path,
|
|
280
|
+
old_path: diffObj.old_path,
|
|
281
|
+
a_mode: diffObj.a_mode,
|
|
282
|
+
b_mode: diffObj.b_mode,
|
|
283
|
+
new_file: diffObj.new_file,
|
|
284
|
+
renamed_file: diffObj.renamed_file,
|
|
285
|
+
deleted_file: diffObj.deleted_file,
|
|
286
|
+
generated_file: diffObj.generated_file,
|
|
287
|
+
block_index: null, // 会在后续分配
|
|
288
|
+
line_info: {
|
|
289
|
+
old_start,
|
|
290
|
+
old_count,
|
|
291
|
+
new_start,
|
|
292
|
+
new_count,
|
|
293
|
+
firstLineFirstChar
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* 获取合并请求的最新版本信息
|
|
301
|
+
* @param {number} projectId GitLab项目ID
|
|
302
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
303
|
+
* @returns {Promise<Object>} 版本信息
|
|
304
|
+
*/
|
|
305
|
+
async getMergeRequestVersions(projectId, mergeRequestIid) {
|
|
306
|
+
try {
|
|
307
|
+
const data = await this.gitlabClient.callGitLabAPI(
|
|
308
|
+
`/projects/${projectId}/merge_requests/${mergeRequestIid}/versions`
|
|
309
|
+
);
|
|
310
|
+
// 返回最新版本信息
|
|
311
|
+
return data[0] || null;
|
|
312
|
+
} catch (error) {
|
|
313
|
+
console.error('获取MR版本信息失败:', error.message);
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 发布单个评论到GitLab MR
|
|
320
|
+
* @param {number} projectId GitLab项目ID
|
|
321
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
322
|
+
* @param {Object} result 单个审核结果
|
|
323
|
+
*/
|
|
324
|
+
async postSingleCommentToGitLab(projectId, mergeRequestIid, result) {
|
|
325
|
+
try {
|
|
326
|
+
const { diff_info, review_result, block_index } = result;
|
|
327
|
+
const file_path = diff_info.new_path || diff_info.old_path;
|
|
328
|
+
const file_path_with_line = `${file_path}#L${block_index}`;
|
|
329
|
+
|
|
330
|
+
// 获取MR版本信息
|
|
331
|
+
const versionInfo = await this.getMergeRequestVersions(projectId, mergeRequestIid);
|
|
332
|
+
if (!versionInfo) {
|
|
333
|
+
console.error('无法获取MR版本信息');
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const baseSha = versionInfo.base_commit_sha;
|
|
338
|
+
const headSha = versionInfo.head_commit_sha;
|
|
339
|
+
const startSha = versionInfo.start_commit_sha;
|
|
340
|
+
|
|
341
|
+
debugLog(`获取到版本信息 - base: ${baseSha}, head: ${headSha}, start: ${startSha}`);
|
|
342
|
+
|
|
343
|
+
// 直接使用diff_info中的line_info
|
|
344
|
+
const lineInfo = diff_info.line_info;
|
|
345
|
+
|
|
346
|
+
if (!lineInfo) {
|
|
347
|
+
// 如果没有行号信息,创建一般讨论
|
|
348
|
+
await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
|
|
349
|
+
debugLog(`评论已发布到文件 ${file_path_with_line} (无法解析行号)`);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// 如果lineInfo里的firstLineFirstChar为+,则targetLine为new_path的new_start行;为-,则targetLine为old_path的old_start行;否则new和old都要赋值
|
|
354
|
+
const targetLine = lineInfo.firstLineFirstChar === '+'
|
|
355
|
+
? { new_line: lineInfo.new_start, new_path: diff_info.new_path }
|
|
356
|
+
: lineInfo.firstLineFirstChar === '-'
|
|
357
|
+
? { old_line: lineInfo.old_start, old_path: diff_info.old_path }
|
|
358
|
+
: { new_line: lineInfo.new_start, new_path: diff_info.new_path, old_line: lineInfo.old_start, old_path: diff_info.old_path };
|
|
359
|
+
|
|
360
|
+
if (targetLine) {
|
|
361
|
+
// 创建diff评论
|
|
362
|
+
const payload = {
|
|
363
|
+
body: review_result,
|
|
364
|
+
position: {
|
|
365
|
+
position_type: 'text',
|
|
366
|
+
base_sha: baseSha,
|
|
367
|
+
head_sha: headSha,
|
|
368
|
+
start_sha: startSha,
|
|
369
|
+
...targetLine
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
await this.createDiffDiscussion(projectId, mergeRequestIid, payload);
|
|
375
|
+
debugLog(`评论已发布到文件 ${file_path_with_line} 的相关变更区域`);
|
|
376
|
+
} catch (error) {
|
|
377
|
+
console.error(`发布评论到文件 ${file_path_with_line} 的变更区域失败,改用一般讨论:`, error.message);
|
|
378
|
+
await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
|
|
379
|
+
debugLog(`评论已发布到文件 ${file_path_with_line} (作为一般讨论)`);
|
|
380
|
+
}
|
|
381
|
+
} else {
|
|
382
|
+
// 如果没有找到任何行号,创建一般讨论
|
|
383
|
+
await this.createGeneralDiscussion(projectId, mergeRequestIid, file_path_with_line, review_result);
|
|
384
|
+
debugLog(`评论已发布到文件 ${file_path_with_line} (无特定行号)`);
|
|
385
|
+
}
|
|
386
|
+
} catch (error) {
|
|
387
|
+
console.error('发布单个评论到GitLab失败:', error.message);
|
|
388
|
+
throw error;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* 发布评论到GitLab MR
|
|
394
|
+
* @param {number} projectId GitLab项目ID
|
|
395
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
396
|
+
* @param {Array} reviewResults 审核结果数组
|
|
397
|
+
*/
|
|
398
|
+
async postCommentsToGitLab(projectId, mergeRequestIid, reviewResults) {
|
|
399
|
+
// 保持原有的批量发布方法,以防需要兼容旧的调用
|
|
400
|
+
for (const result of reviewResults) {
|
|
401
|
+
await this.postSingleCommentToGitLab(projectId, mergeRequestIid, result);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* 创建一般讨论
|
|
407
|
+
* @param {number} projectId GitLab项目ID
|
|
408
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
409
|
+
* @param {string} file_path 文件路径
|
|
410
|
+
* @param {string} review_result 审核结果
|
|
411
|
+
*/
|
|
412
|
+
async createGeneralDiscussion(projectId, mergeRequestIid, file_path, review_result) {
|
|
413
|
+
const discussionData = {
|
|
414
|
+
body: `**代码审核评论 - 文件: ${file_path}**\n\n${review_result}`
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
await this.gitlabClient.callGitLabAPI(
|
|
418
|
+
`/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
|
|
419
|
+
{ method: 'POST', data: discussionData }
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* 创建diff讨论
|
|
425
|
+
* @param {number} projectId GitLab项目ID
|
|
426
|
+
* @param {number} mergeRequestIid 合并请求IID
|
|
427
|
+
* @param {Object} payload 讨论数据
|
|
428
|
+
*/
|
|
429
|
+
async createDiffDiscussion(projectId, mergeRequestIid, payload) {
|
|
430
|
+
await this.gitlabClient.callGitLabAPI(
|
|
431
|
+
`/projects/${projectId}/merge_requests/${mergeRequestIid}/discussions`,
|
|
432
|
+
{ method: 'POST', data: payload }
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// 主函数
|
|
438
|
+
async function main() {
|
|
439
|
+
debugLog('开始加载环境变量');
|
|
440
|
+
// 从环境变量获取配置
|
|
441
|
+
const gitlabUrl = process.env.CI_API_V4_URL;
|
|
442
|
+
const gitlabToken = process.env.GITLAB_ACCESS_TOKEN;
|
|
443
|
+
const projectId = process.env.CI_PROJECT_ID;
|
|
444
|
+
const mergeRequestIid = process.env.CI_MERGE_REQUEST_IID;
|
|
445
|
+
// 获取最大并发数配置,默认为3
|
|
446
|
+
const maxConcurrency = parseInt(process.env.GITLAB_CR_CONCURRENCY || 3);
|
|
447
|
+
|
|
448
|
+
debugLog(`环境变量加载完成:`);
|
|
449
|
+
debugLog(` GITLAB_API_V4_URL: ${gitlabUrl}`);
|
|
450
|
+
debugLog(` GITLAB_TOKEN存在: ${!!gitlabToken}`);
|
|
451
|
+
debugLog(` GITLAB_PROJECT_ID: ${projectId}`);
|
|
452
|
+
debugLog(` GITLAB_MERGE_REQUEST_IID: ${mergeRequestIid}`);
|
|
453
|
+
debugLog(` 设置最大并发数: ${maxConcurrency}`);
|
|
454
|
+
|
|
455
|
+
if (!gitlabToken || !projectId || !mergeRequestIid) {
|
|
456
|
+
console.error('缺少必要的环境变量配置');
|
|
457
|
+
console.error('请设置: CI_API_V4_URL, GITLAB_ACCESS_TOKEN, CI_PROJECT_ID, CI_MERGE_REQUEST_IID');
|
|
458
|
+
process.exit(1);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const reviewer = new GitLabCodeReviewer(gitlabToken, gitlabUrl);
|
|
462
|
+
|
|
463
|
+
try {
|
|
464
|
+
// 审核合并请求 - 现在会在每个块审核后立即发布评论
|
|
465
|
+
debugLog('开始审核合并请求并发布评论...');
|
|
466
|
+
await reviewer.reviewMergeRequest(projectId, mergeRequestIid, maxConcurrency);
|
|
467
|
+
debugLog('所有评论已成功发布到GitLab MR');
|
|
468
|
+
console.log('代码审核完成!');
|
|
469
|
+
} catch (error) {
|
|
470
|
+
console.error('审核过程出错:', error);
|
|
471
|
+
process.exit(1);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// 辅助函数:执行本地Claude命令
|
|
476
|
+
function runClaudeCommand(promptContent) {
|
|
477
|
+
return new Promise((resolve, reject) => {
|
|
478
|
+
// 创建当前目录下的临时文件
|
|
479
|
+
const tmpFileName = `./temp-prompt-${Date.now()}.md`;
|
|
480
|
+
debugLog('临时文件路径:', tmpFileName);
|
|
481
|
+
|
|
482
|
+
// 将prompt内容写入临时文件
|
|
483
|
+
fs.writeFileSync(tmpFileName, promptContent);
|
|
484
|
+
|
|
485
|
+
debugLog("AI review命令开始时间")
|
|
486
|
+
// 使用spawn替代exec,更安全地处理命令执行并实现环境隔离
|
|
487
|
+
const claudeProcess = spawn('claude', ['-p', tmpFileName], {
|
|
488
|
+
shell: true, // ✅ 启用 shell,支持别名和完整 PATH
|
|
489
|
+
env: process.env,
|
|
490
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
let stdout = '';
|
|
494
|
+
let stderr = '';
|
|
495
|
+
|
|
496
|
+
claudeProcess.stdout.on('data', (data) => {
|
|
497
|
+
stdout += data.toString();
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
claudeProcess.stderr.on('data', (data) => {
|
|
501
|
+
stderr += data.toString();
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
claudeProcess.on('close', (code) => {
|
|
505
|
+
debugLog("AI review命令结束时间")
|
|
506
|
+
// 清理临时文件
|
|
507
|
+
try {
|
|
508
|
+
fs.unlinkSync(tmpFileName);
|
|
509
|
+
} catch (cleanupError) {
|
|
510
|
+
console.error('清理临时文件失败:', cleanupError.message);
|
|
511
|
+
}
|
|
512
|
+
resolve(stdout.trim());
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
claudeProcess.on('error', (error) => {
|
|
516
|
+
// 出错时也要清理临时文件
|
|
517
|
+
try {
|
|
518
|
+
fs.unlinkSync(tmpFileName);
|
|
519
|
+
} catch (cleanupError) {
|
|
520
|
+
console.error('清理临时文件失败:', cleanupError.message);
|
|
521
|
+
}
|
|
522
|
+
reject(new Error(`AI命令执行出错: ${error.message}, 错误输出: ${stderr || '无错误输出'}`));
|
|
523
|
+
});
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// 如果直接运行此文件,则执行主函数
|
|
528
|
+
if (require.main === module) {
|
|
529
|
+
main();
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
module.exports = GitLabCodeReviewer;
|