plugin-workflow-ci 0.0.0-stage → 0.2.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/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/externalVersion.js +21 -0
- package/dist/index.js +48 -0
- package/dist/locale/en-US.json +105 -0
- package/dist/locale/vi-VN.json +105 -0
- package/dist/locale/zh-CN.json +105 -0
- package/dist/server/actions/ci-manager.js +307 -0
- package/dist/server/collections/ci-gate-runs.js +85 -0
- package/dist/server/collections/ci-git-feedback-outbox.js +51 -0
- package/dist/server/collections/ci-pipelines.js +88 -0
- package/dist/server/index.js +62 -0
- package/dist/server/instructions/CiInstructions.js +180 -0
- package/dist/server/migrations/20261206000001-harden-workflow-ci-v020.js +91 -0
- package/dist/server/plugin.js +255 -0
- package/dist/server/services/AiTriageService.js +215 -0
- package/dist/server/services/CiGateWorkflowService.js +1776 -0
- package/dist/server/services/EphemeralContainerService.js +891 -0
- package/dist/server/services/GitFeedbackService.js +995 -0
- package/dist/server/services/constants-internal.js +65 -0
- package/dist/shared/collection-schemas.js +125 -0
- package/dist/shared/constants.js +120 -0
- package/dist/shared/runtime-context.js +67 -0
- package/dist/shared/types.js +24 -0
- package/dist/shared/ui/CiPipelinesSettingsView.js +700 -0
- package/package.json +58 -4
- package/server.js +1 -0
- package/src/client/index.tsx +10 -0
- package/src/client/locale.ts +31 -0
- package/src/client/plugin.tsx +62 -0
- package/src/client/workflow.tsx +119 -0
- package/src/client-v2/index.tsx +10 -0
- package/src/client-v2/locale.ts +32 -0
- package/src/client-v2/plugin.tsx +77 -0
- package/src/client-v2/workflow.tsx +124 -0
- package/src/index.ts +11 -0
- package/src/locale/en-US.json +105 -0
- package/src/locale/vi-VN.json +105 -0
- package/src/locale/zh-CN.json +105 -0
- package/src/server/actions/ci-manager.ts +377 -0
- package/src/server/collections/ci-gate-runs.ts +65 -0
- package/src/server/collections/ci-git-feedback-outbox.ts +31 -0
- package/src/server/collections/ci-pipelines.ts +68 -0
- package/src/server/index.ts +17 -0
- package/src/server/instructions/CiInstructions.ts +180 -0
- package/src/server/migrations/20261206000001-harden-workflow-ci-v020.ts +78 -0
- package/src/server/plugin.ts +274 -0
- package/src/server/services/AiTriageService.ts +254 -0
- package/src/server/services/CiGateWorkflowService.ts +2310 -0
- package/src/server/services/EphemeralContainerService.ts +1170 -0
- package/src/server/services/GitFeedbackService.ts +1224 -0
- package/src/server/services/constants-internal.ts +27 -0
- package/src/shared/collection-schemas.ts +98 -0
- package/src/shared/constants.ts +50 -0
- package/src/shared/runtime-context.tsx +55 -0
- package/src/shared/types.ts +203 -0
- package/src/shared/ui/CiPipelinesSettingsView.tsx +1035 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
11
|
+
import type { Model } from '@nocobase/database';
|
|
12
|
+
import type Application from '@nocobase/server';
|
|
13
|
+
import {
|
|
14
|
+
CI_GATE_RUNS_COLLECTION,
|
|
15
|
+
CI_GIT_FEEDBACK_OUTBOX_COLLECTION,
|
|
16
|
+
CI_PIPELINES_COLLECTION,
|
|
17
|
+
GIT_ACCOUNTS_COLLECTION,
|
|
18
|
+
GIT_REPOSITORIES_COLLECTION,
|
|
19
|
+
GIT_REVIEW_REQUESTS_COLLECTION,
|
|
20
|
+
} from '../../shared/constants';
|
|
21
|
+
import type {
|
|
22
|
+
CiGateRunRecord,
|
|
23
|
+
CiPipelineRecord,
|
|
24
|
+
CiTriageSummary,
|
|
25
|
+
GitCommitStatusState,
|
|
26
|
+
ParsedGitWebhookEvent,
|
|
27
|
+
} from '../../shared/types';
|
|
28
|
+
|
|
29
|
+
export type HttpFetchLike = (url: string, init?: RequestInit) => Promise<Response>;
|
|
30
|
+
|
|
31
|
+
interface ResolvedRepoGitAuth {
|
|
32
|
+
provider: 'github' | 'gitlab';
|
|
33
|
+
pat: string;
|
|
34
|
+
apiBase: string;
|
|
35
|
+
projectPath: string;
|
|
36
|
+
encodedProject: string;
|
|
37
|
+
repoWebUrl: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const MAX_COMMENT_PAGES = 20;
|
|
41
|
+
const COMMENTS_PER_PAGE = 100;
|
|
42
|
+
const MAX_OUTBOX_ATTEMPTS = 6;
|
|
43
|
+
|
|
44
|
+
function isPlainRecord(val: unknown): val is Record<string, unknown> {
|
|
45
|
+
return Boolean(val) && typeof val === 'object' && !Array.isArray(val);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function verifyConstantTimeSecret(expected: string, actual: string): boolean {
|
|
49
|
+
const cleanExpected = expected.trim();
|
|
50
|
+
const cleanActual = actual.trim();
|
|
51
|
+
if (!cleanExpected || !cleanActual) return false;
|
|
52
|
+
const bufA = Buffer.from(cleanExpected, 'utf8');
|
|
53
|
+
const bufB = Buffer.from(cleanActual, 'utf8');
|
|
54
|
+
if (bufA.length !== bufB.length) return false;
|
|
55
|
+
return timingSafeEqual(bufA, bufB);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function verifyGitHubHmacSignature(secret: string, rawBody: string, signatureHeader: string): boolean {
|
|
59
|
+
const cleanSecret = secret.trim();
|
|
60
|
+
const cleanHeader = signatureHeader.trim();
|
|
61
|
+
if (!cleanSecret || !cleanHeader.startsWith('sha256=')) return false;
|
|
62
|
+
const digest = `sha256=${createHmac('sha256', cleanSecret).update(rawBody, 'utf8').digest('hex')}`;
|
|
63
|
+
return verifyConstantTimeSecret(digest, cleanHeader);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function matchesBranchPattern(branch: string, patternRaw?: string | null): boolean {
|
|
67
|
+
const cleanBranch = branch.trim();
|
|
68
|
+
if (!cleanBranch) return false;
|
|
69
|
+
const raw = String(patternRaw ?? '*').trim();
|
|
70
|
+
if (!raw || raw === '*') return true;
|
|
71
|
+
|
|
72
|
+
const patterns = raw
|
|
73
|
+
.split(',')
|
|
74
|
+
.map((p) => p.trim())
|
|
75
|
+
.filter(Boolean);
|
|
76
|
+
if (patterns.length === 0) return true;
|
|
77
|
+
|
|
78
|
+
return patterns.some((pat) => {
|
|
79
|
+
if (pat === '*') return true;
|
|
80
|
+
const escaped = pat
|
|
81
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
82
|
+
.replace(/\*\*/g, '.*')
|
|
83
|
+
.replace(/\*/g, '[^/]*');
|
|
84
|
+
return new RegExp(`^${escaped}$`).test(cleanBranch);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function parseStickyCommentVersionMarker(body: string): {
|
|
89
|
+
pipelineKey?: string;
|
|
90
|
+
pipelineId?: number;
|
|
91
|
+
mrIid?: number;
|
|
92
|
+
gateRunId?: number;
|
|
93
|
+
commitSha?: string;
|
|
94
|
+
} | null {
|
|
95
|
+
const v2Match = /<!--\s*nocobase-ci:([^\r\n>]+?)\s*-->/.exec(body);
|
|
96
|
+
if (v2Match) {
|
|
97
|
+
const kv: Record<string, string> = {};
|
|
98
|
+
for (const pair of v2Match[1].split(';')) {
|
|
99
|
+
const eq = pair.indexOf('=');
|
|
100
|
+
if (eq > 0) {
|
|
101
|
+
kv[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
pipelineKey: kv.pipeline,
|
|
106
|
+
pipelineId: kv.pipelineId ? Number(kv.pipelineId) : undefined,
|
|
107
|
+
mrIid: kv.mr ? Number(kv.mr) : undefined,
|
|
108
|
+
gateRunId: kv.gateRun ? Number(kv.gateRun) : undefined,
|
|
109
|
+
commitSha: kv.sha,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const legacyMatch = /<!--\s*nocobase-ci-summary:pipeline-(\d+):mr-(\d+)\s*-->/.exec(body);
|
|
113
|
+
if (legacyMatch) {
|
|
114
|
+
return {
|
|
115
|
+
pipelineId: Number(legacyMatch[1]),
|
|
116
|
+
mrIid: Number(legacyMatch[2]),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function hasNextLinkHeader(resp: Response): boolean {
|
|
123
|
+
const link = resp.headers?.get?.('link') || resp.headers?.get?.('Link') || '';
|
|
124
|
+
if (link && /rel=["']?next["']?/i.test(link)) {
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
const nextPage = resp.headers?.get?.('x-next-page') || '';
|
|
128
|
+
return Boolean(nextPage && Number(nextPage) > 0);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function parseGitWebhookPayload(
|
|
132
|
+
headers: Record<string, string | undefined>,
|
|
133
|
+
body: unknown,
|
|
134
|
+
): ParsedGitWebhookEvent {
|
|
135
|
+
const payload = isPlainRecord(body) ? body : {};
|
|
136
|
+
const ghEvent = (headers['x-github-event'] || '').toLowerCase();
|
|
137
|
+
const glEvent = (headers['x-gitlab-event'] || '').toLowerCase();
|
|
138
|
+
|
|
139
|
+
if (ghEvent) {
|
|
140
|
+
const repoObj = isPlainRecord(payload.repository) ? payload.repository : {};
|
|
141
|
+
const repoUrl = typeof repoObj.html_url === 'string' ? repoObj.html_url : undefined;
|
|
142
|
+
const projectPath = typeof repoObj.full_name === 'string' ? repoObj.full_name : undefined;
|
|
143
|
+
const senderObj = isPlainRecord(payload.sender) ? payload.sender : {};
|
|
144
|
+
const sender = typeof senderObj.login === 'string' ? senderObj.login : null;
|
|
145
|
+
|
|
146
|
+
if (ghEvent === 'push') {
|
|
147
|
+
const ref = String(payload.ref || '');
|
|
148
|
+
if (!ref.startsWith('refs/heads/') || payload.deleted === true) {
|
|
149
|
+
return {
|
|
150
|
+
provider: 'github',
|
|
151
|
+
eventType: 'ignored',
|
|
152
|
+
branch: '',
|
|
153
|
+
commitSha: '',
|
|
154
|
+
reason: 'Not an active branch push',
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const branch = ref.slice('refs/heads/'.length);
|
|
158
|
+
const afterSha = String(payload.after || '');
|
|
159
|
+
const headCommit = isPlainRecord(payload.head_commit) ? payload.head_commit : {};
|
|
160
|
+
return {
|
|
161
|
+
provider: 'github',
|
|
162
|
+
eventType: 'push',
|
|
163
|
+
repoUrl,
|
|
164
|
+
projectPath,
|
|
165
|
+
branch,
|
|
166
|
+
commitSha: afterSha,
|
|
167
|
+
baseSha: typeof payload.before === 'string' ? payload.before : null,
|
|
168
|
+
commitMessage: typeof headCommit.message === 'string' ? headCommit.message : null,
|
|
169
|
+
sender,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (ghEvent === 'pull_request') {
|
|
174
|
+
const action = String(payload.action || '');
|
|
175
|
+
const pr = isPlainRecord(payload.pull_request) ? payload.pull_request : {};
|
|
176
|
+
if (!['opened', 'synchronize', 'reopened'].includes(action) || pr.state === 'closed') {
|
|
177
|
+
return {
|
|
178
|
+
provider: 'github',
|
|
179
|
+
eventType: 'ignored',
|
|
180
|
+
branch: '',
|
|
181
|
+
commitSha: '',
|
|
182
|
+
reason: `Unsupported PR action "${action}"`,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const head = isPlainRecord(pr.head) ? pr.head : {};
|
|
186
|
+
const base = isPlainRecord(pr.base) ? pr.base : {};
|
|
187
|
+
return {
|
|
188
|
+
provider: 'github',
|
|
189
|
+
eventType: 'merge_request',
|
|
190
|
+
repoUrl,
|
|
191
|
+
projectPath,
|
|
192
|
+
branch: String(head.ref || ''),
|
|
193
|
+
targetBranch: typeof base.ref === 'string' ? base.ref : null,
|
|
194
|
+
commitSha: String(head.sha || ''),
|
|
195
|
+
baseSha: typeof base.sha === 'string' ? base.sha : null,
|
|
196
|
+
commitMessage: typeof pr.title === 'string' ? pr.title : null,
|
|
197
|
+
mrIid: typeof pr.number === 'number' ? pr.number : Number(payload.number || 0) || null,
|
|
198
|
+
sender,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
provider: 'github',
|
|
204
|
+
eventType: 'ignored',
|
|
205
|
+
branch: '',
|
|
206
|
+
commitSha: '',
|
|
207
|
+
reason: `Unhandled GitHub event "${ghEvent}"`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// GitLab payload detection
|
|
212
|
+
const objectKind = String(payload.object_kind || '');
|
|
213
|
+
const project = isPlainRecord(payload.project) ? payload.project : {};
|
|
214
|
+
const repoUrl = typeof project.web_url === 'string' ? project.web_url : undefined;
|
|
215
|
+
const projectPath = typeof project.path_with_namespace === 'string' ? project.path_with_namespace : undefined;
|
|
216
|
+
const userObj = isPlainRecord(payload.user) ? payload.user : {};
|
|
217
|
+
const sender =
|
|
218
|
+
typeof userObj.username === 'string'
|
|
219
|
+
? userObj.username
|
|
220
|
+
: typeof payload.user_username === 'string'
|
|
221
|
+
? payload.user_username
|
|
222
|
+
: null;
|
|
223
|
+
|
|
224
|
+
if (objectKind === 'push' || glEvent.includes('push')) {
|
|
225
|
+
const ref = String(payload.ref || '');
|
|
226
|
+
const after = String(payload.after || '');
|
|
227
|
+
if (!ref.startsWith('refs/heads/') || /^0+$/.test(after)) {
|
|
228
|
+
return {
|
|
229
|
+
provider: 'gitlab',
|
|
230
|
+
eventType: 'ignored',
|
|
231
|
+
branch: '',
|
|
232
|
+
commitSha: '',
|
|
233
|
+
reason: 'Deleted or non-branch ref',
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
const commits = Array.isArray(payload.commits) ? payload.commits : [];
|
|
237
|
+
const lastCommit =
|
|
238
|
+
commits.length > 0 && isPlainRecord(commits[commits.length - 1]) ? commits[commits.length - 1] : {};
|
|
239
|
+
return {
|
|
240
|
+
provider: 'gitlab',
|
|
241
|
+
eventType: 'push',
|
|
242
|
+
repoUrl,
|
|
243
|
+
projectPath,
|
|
244
|
+
branch: ref.slice('refs/heads/'.length),
|
|
245
|
+
commitSha: after,
|
|
246
|
+
baseSha: typeof payload.before === 'string' ? payload.before : null,
|
|
247
|
+
commitMessage: typeof lastCommit.message === 'string' ? lastCommit.message : null,
|
|
248
|
+
sender,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (objectKind === 'merge_request' || glEvent.includes('merge request')) {
|
|
253
|
+
const attrs = isPlainRecord(payload.object_attributes) ? payload.object_attributes : {};
|
|
254
|
+
const action = String(attrs.action || 'open');
|
|
255
|
+
const state = String(attrs.state || 'opened');
|
|
256
|
+
if (state !== 'opened' || !['open', 'update', 'reopen'].includes(action)) {
|
|
257
|
+
return {
|
|
258
|
+
provider: 'gitlab',
|
|
259
|
+
eventType: 'ignored',
|
|
260
|
+
branch: '',
|
|
261
|
+
commitSha: '',
|
|
262
|
+
reason: `Ignored MR action="${action}" state="${state}"`,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const lastCommit = isPlainRecord(attrs.last_commit) ? attrs.last_commit : {};
|
|
266
|
+
return {
|
|
267
|
+
provider: 'gitlab',
|
|
268
|
+
eventType: 'merge_request',
|
|
269
|
+
repoUrl,
|
|
270
|
+
projectPath,
|
|
271
|
+
branch: String(attrs.source_branch || ''),
|
|
272
|
+
targetBranch: typeof attrs.target_branch === 'string' ? attrs.target_branch : null,
|
|
273
|
+
commitSha: String(lastCommit.id || attrs.last_commit_id || ''),
|
|
274
|
+
commitMessage: typeof attrs.title === 'string' ? attrs.title : null,
|
|
275
|
+
mrIid: typeof attrs.iid === 'number' ? attrs.iid : Number(attrs.iid || 0) || null,
|
|
276
|
+
sender,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return {
|
|
281
|
+
provider: 'gitlab',
|
|
282
|
+
eventType: 'ignored',
|
|
283
|
+
branch: '',
|
|
284
|
+
commitSha: '',
|
|
285
|
+
reason: 'Unrecognized webhook event payload',
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export class GitFeedbackService {
|
|
290
|
+
private fetchImpl: HttpFetchLike = (url, init) => fetch(url, init);
|
|
291
|
+
|
|
292
|
+
constructor(private readonly app: Application) {}
|
|
293
|
+
|
|
294
|
+
setHttpFetch(fn: HttpFetchLike): void {
|
|
295
|
+
this.fetchImpl = fn;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async decryptSecret(raw: unknown): Promise<string> {
|
|
299
|
+
if (typeof raw !== 'string' || !raw.trim()) return '';
|
|
300
|
+
const encryptor = (this.app as unknown as { aesEncryptor?: { decrypt(v: string): Promise<string> | string } })
|
|
301
|
+
.aesEncryptor;
|
|
302
|
+
if (!encryptor) return raw.trim();
|
|
303
|
+
try {
|
|
304
|
+
return await encryptor.decrypt(raw.trim());
|
|
305
|
+
} catch {
|
|
306
|
+
return raw.trim();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async resolveRepoAuth(gitRepositoryId?: number | null): Promise<ResolvedRepoGitAuth | null> {
|
|
311
|
+
if (!gitRepositoryId) return null;
|
|
312
|
+
try {
|
|
313
|
+
if (!this.app.db.getCollection(GIT_REPOSITORIES_COLLECTION)) return null;
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const repo = (await this.app.db
|
|
319
|
+
.getRepository(GIT_REPOSITORIES_COLLECTION)
|
|
320
|
+
.findOne({ filterByTk: gitRepositoryId })) as Model | null;
|
|
321
|
+
if (!repo) return null;
|
|
322
|
+
|
|
323
|
+
const repoUrlRaw = String(repo.get('repoUrl') || '').trim();
|
|
324
|
+
if (!repoUrlRaw) return null;
|
|
325
|
+
const parsedRepoUrl = new URL(repoUrlRaw);
|
|
326
|
+
if (parsedRepoUrl.protocol !== 'https:' && parsedRepoUrl.protocol !== 'http:') {
|
|
327
|
+
throw new Error(`Unsupported Git repository URL protocol: ${parsedRepoUrl.protocol}`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
let pat = '';
|
|
331
|
+
let providerHint = '';
|
|
332
|
+
let accountBaseUrl = '';
|
|
333
|
+
|
|
334
|
+
const gitAccountId = repo.get('gitAccountId');
|
|
335
|
+
if (
|
|
336
|
+
(typeof gitAccountId === 'number' || typeof gitAccountId === 'string') &&
|
|
337
|
+
this.hasCollection(GIT_ACCOUNTS_COLLECTION)
|
|
338
|
+
) {
|
|
339
|
+
const account = (await this.app.db
|
|
340
|
+
.getRepository(GIT_ACCOUNTS_COLLECTION)
|
|
341
|
+
.findOne({ filterByTk: gitAccountId })) as Model | null;
|
|
342
|
+
if (account) {
|
|
343
|
+
pat = await this.decryptSecret(account.get('pat'));
|
|
344
|
+
providerHint = String(account.get('provider') || '').toLowerCase();
|
|
345
|
+
accountBaseUrl = String(account.get('baseUrl') || '').trim();
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const cleanPath = parsedRepoUrl.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
|
|
350
|
+
const isGitHub = providerHint === 'github' || parsedRepoUrl.hostname === 'github.com';
|
|
351
|
+
const origin = (accountBaseUrl || `${parsedRepoUrl.protocol}//${parsedRepoUrl.host}`).replace(/\/+$/, '');
|
|
352
|
+
const apiBase = isGitHub
|
|
353
|
+
? parsedRepoUrl.hostname === 'github.com'
|
|
354
|
+
? 'https://api.github.com'
|
|
355
|
+
: `${origin}/api/v3`
|
|
356
|
+
: `${origin}/api/v4`;
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
provider: isGitHub ? 'github' : 'gitlab',
|
|
360
|
+
pat,
|
|
361
|
+
apiBase,
|
|
362
|
+
projectPath: cleanPath,
|
|
363
|
+
encodedProject: encodeURIComponent(cleanPath),
|
|
364
|
+
repoWebUrl: `${parsedRepoUrl.protocol}//${parsedRepoUrl.host}/${cleanPath}`,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private hasCollection(name: string): boolean {
|
|
369
|
+
try {
|
|
370
|
+
return Boolean(this.app.db.getCollection(name));
|
|
371
|
+
} catch {
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async verifyBranchHeadSha(params: {
|
|
377
|
+
gitRepositoryId?: number | null;
|
|
378
|
+
branch: string;
|
|
379
|
+
expectedSha: string;
|
|
380
|
+
}): Promise<{ verified: boolean; configured: boolean; actualHeadSha?: string | null; detail: string }> {
|
|
381
|
+
const auth = await this.resolveRepoAuth(params.gitRepositoryId);
|
|
382
|
+
if (!auth || !auth.pat) {
|
|
383
|
+
return {
|
|
384
|
+
verified: false,
|
|
385
|
+
configured: false,
|
|
386
|
+
detail: 'Git repository PAT is not configured for remote branch HEAD verification',
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const encodedBranch = encodeURIComponent(params.branch.trim());
|
|
391
|
+
try {
|
|
392
|
+
if (auth.provider === 'github') {
|
|
393
|
+
const resp = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/branches/${encodedBranch}`, {
|
|
394
|
+
method: 'GET',
|
|
395
|
+
headers: {
|
|
396
|
+
Authorization: `Bearer ${auth.pat}`,
|
|
397
|
+
Accept: 'application/vnd.github.v3+json',
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
if (!resp.ok) {
|
|
401
|
+
return {
|
|
402
|
+
verified: false,
|
|
403
|
+
configured: true,
|
|
404
|
+
detail: `GitHub branch API returned HTTP ${resp.status} for branch "${params.branch}"`,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
const data = (await resp.json()) as { commit?: { sha?: string } };
|
|
408
|
+
const headSha = String(data?.commit?.sha || '').trim();
|
|
409
|
+
return {
|
|
410
|
+
verified: Boolean(headSha && headSha === params.expectedSha),
|
|
411
|
+
configured: true,
|
|
412
|
+
actualHeadSha: headSha || null,
|
|
413
|
+
detail:
|
|
414
|
+
headSha === params.expectedSha
|
|
415
|
+
? `Verified GitHub branch "${params.branch}" HEAD matches ${headSha.slice(0, 12)}`
|
|
416
|
+
: `Branch "${params.branch}" HEAD is ${headSha.slice(0, 12)}, expected ${params.expectedSha.slice(
|
|
417
|
+
0,
|
|
418
|
+
12,
|
|
419
|
+
)}`,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const resp = await this.fetchImpl(
|
|
424
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/repository/branches/${encodedBranch}`,
|
|
425
|
+
{
|
|
426
|
+
method: 'GET',
|
|
427
|
+
headers: {
|
|
428
|
+
'PRIVATE-TOKEN': auth.pat,
|
|
429
|
+
Accept: 'application/json',
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
);
|
|
433
|
+
if (!resp.ok) {
|
|
434
|
+
return {
|
|
435
|
+
verified: false,
|
|
436
|
+
configured: true,
|
|
437
|
+
detail: `GitLab branch API returned HTTP ${resp.status} for branch "${params.branch}"`,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
const data = (await resp.json()) as { commit?: { id?: string } };
|
|
441
|
+
const headSha = String(data?.commit?.id || '').trim();
|
|
442
|
+
return {
|
|
443
|
+
verified: Boolean(headSha && headSha === params.expectedSha),
|
|
444
|
+
configured: true,
|
|
445
|
+
actualHeadSha: headSha || null,
|
|
446
|
+
detail:
|
|
447
|
+
headSha === params.expectedSha
|
|
448
|
+
? `Verified GitLab branch "${params.branch}" HEAD matches ${headSha.slice(0, 12)}`
|
|
449
|
+
: `Branch "${params.branch}" HEAD is ${headSha.slice(0, 12)}, expected ${params.expectedSha.slice(0, 12)}`,
|
|
450
|
+
};
|
|
451
|
+
} catch (error) {
|
|
452
|
+
return {
|
|
453
|
+
verified: false,
|
|
454
|
+
configured: true,
|
|
455
|
+
detail: `Failed querying branch HEAD from Git API: ${error instanceof Error ? error.message : String(error)}`,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
private async enqueueOutboxItem(params: {
|
|
461
|
+
gateRunId?: number | null;
|
|
462
|
+
pipelineId?: number | null;
|
|
463
|
+
gitRepositoryId?: number | null;
|
|
464
|
+
kind: 'commit_status' | 'sticky_comment';
|
|
465
|
+
payload: Record<string, unknown>;
|
|
466
|
+
lastError: string;
|
|
467
|
+
}): Promise<void> {
|
|
468
|
+
if (!params.gateRunId || !params.pipelineId || !this.hasCollection(CI_GIT_FEEDBACK_OUTBOX_COLLECTION)) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const repo = this.app.db.getRepository(CI_GIT_FEEDBACK_OUTBOX_COLLECTION);
|
|
472
|
+
const existing = (await repo
|
|
473
|
+
.findOne({
|
|
474
|
+
filter: {
|
|
475
|
+
gateRunId: params.gateRunId,
|
|
476
|
+
kind: params.kind,
|
|
477
|
+
status: 'pending',
|
|
478
|
+
},
|
|
479
|
+
})
|
|
480
|
+
.catch(() => null)) as Model | null;
|
|
481
|
+
|
|
482
|
+
const nextRetryAt = new Date(Date.now() + 15_000).toISOString();
|
|
483
|
+
if (existing) {
|
|
484
|
+
await existing
|
|
485
|
+
.update({
|
|
486
|
+
payload: params.payload,
|
|
487
|
+
lastError: params.lastError.slice(0, 1000),
|
|
488
|
+
nextRetryAt,
|
|
489
|
+
})
|
|
490
|
+
.catch(() => undefined);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
await repo
|
|
495
|
+
.create({
|
|
496
|
+
values: {
|
|
497
|
+
gateRunId: params.gateRunId,
|
|
498
|
+
pipelineId: params.pipelineId,
|
|
499
|
+
gitRepositoryId: params.gitRepositoryId ?? null,
|
|
500
|
+
kind: params.kind,
|
|
501
|
+
payload: params.payload,
|
|
502
|
+
status: 'pending',
|
|
503
|
+
attempts: 1,
|
|
504
|
+
nextRetryAt,
|
|
505
|
+
lastError: params.lastError.slice(0, 1000),
|
|
506
|
+
},
|
|
507
|
+
})
|
|
508
|
+
.catch(() => undefined);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async publishCommitStatus(params: {
|
|
512
|
+
gateRunId?: number | null;
|
|
513
|
+
pipelineId?: number | null;
|
|
514
|
+
gitRepositoryId?: number | null;
|
|
515
|
+
commitSha: string;
|
|
516
|
+
branch?: string | null;
|
|
517
|
+
state: GitCommitStatusState;
|
|
518
|
+
context: string;
|
|
519
|
+
description: string;
|
|
520
|
+
targetUrl?: string;
|
|
521
|
+
skipOutboxOnError?: boolean;
|
|
522
|
+
}): Promise<{ published: boolean; queuedRetry?: boolean; provider?: string; detail: string }> {
|
|
523
|
+
const auth = await this.resolveRepoAuth(params.gitRepositoryId);
|
|
524
|
+
if (!auth || !auth.pat || !params.commitSha) {
|
|
525
|
+
return { published: false, detail: 'Git repository or PAT not configured; skipped commit status' };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const desc = params.description.slice(0, 138);
|
|
529
|
+
try {
|
|
530
|
+
if (auth.provider === 'github') {
|
|
531
|
+
const resp = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/statuses/${params.commitSha}`, {
|
|
532
|
+
method: 'POST',
|
|
533
|
+
headers: {
|
|
534
|
+
Authorization: `Bearer ${auth.pat}`,
|
|
535
|
+
Accept: 'application/vnd.github.v3+json',
|
|
536
|
+
'Content-Type': 'application/json',
|
|
537
|
+
},
|
|
538
|
+
body: JSON.stringify({
|
|
539
|
+
state: params.state,
|
|
540
|
+
context: params.context || 'nocobase/ci-test-manager',
|
|
541
|
+
description: desc,
|
|
542
|
+
...(params.targetUrl ? { target_url: params.targetUrl } : {}),
|
|
543
|
+
}),
|
|
544
|
+
});
|
|
545
|
+
if (!resp.ok) {
|
|
546
|
+
const errDetail = `GitHub status API returned HTTP ${resp.status}`;
|
|
547
|
+
if (!params.skipOutboxOnError) {
|
|
548
|
+
await this.enqueueOutboxItem({
|
|
549
|
+
gateRunId: params.gateRunId,
|
|
550
|
+
pipelineId: params.pipelineId,
|
|
551
|
+
gitRepositoryId: params.gitRepositoryId,
|
|
552
|
+
kind: 'commit_status',
|
|
553
|
+
payload: {
|
|
554
|
+
gitRepositoryId: params.gitRepositoryId ?? null,
|
|
555
|
+
commitSha: params.commitSha,
|
|
556
|
+
branch: params.branch ?? null,
|
|
557
|
+
state: params.state,
|
|
558
|
+
context: params.context,
|
|
559
|
+
description: desc,
|
|
560
|
+
targetUrl: params.targetUrl ?? null,
|
|
561
|
+
},
|
|
562
|
+
lastError: errDetail,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, provider: 'github', detail: errDetail };
|
|
566
|
+
}
|
|
567
|
+
return { published: true, provider: 'github', detail: `Published GitHub commit status "${params.state}"` };
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const glState = params.state === 'pending' ? 'running' : params.state === 'success' ? 'success' : 'failed';
|
|
571
|
+
const resp = await this.fetchImpl(
|
|
572
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/statuses/${params.commitSha}`,
|
|
573
|
+
{
|
|
574
|
+
method: 'POST',
|
|
575
|
+
headers: {
|
|
576
|
+
'PRIVATE-TOKEN': auth.pat,
|
|
577
|
+
Accept: 'application/json',
|
|
578
|
+
'Content-Type': 'application/json',
|
|
579
|
+
},
|
|
580
|
+
body: JSON.stringify({
|
|
581
|
+
state: glState,
|
|
582
|
+
name: params.context || 'nocobase/ci-test-manager',
|
|
583
|
+
description: desc,
|
|
584
|
+
...(params.branch ? { ref: params.branch } : {}),
|
|
585
|
+
...(params.targetUrl ? { target_url: params.targetUrl } : {}),
|
|
586
|
+
}),
|
|
587
|
+
},
|
|
588
|
+
);
|
|
589
|
+
if (!resp.ok) {
|
|
590
|
+
const errDetail = `GitLab status API returned HTTP ${resp.status}`;
|
|
591
|
+
if (!params.skipOutboxOnError) {
|
|
592
|
+
await this.enqueueOutboxItem({
|
|
593
|
+
gateRunId: params.gateRunId,
|
|
594
|
+
pipelineId: params.pipelineId,
|
|
595
|
+
gitRepositoryId: params.gitRepositoryId,
|
|
596
|
+
kind: 'commit_status',
|
|
597
|
+
payload: {
|
|
598
|
+
gitRepositoryId: params.gitRepositoryId ?? null,
|
|
599
|
+
commitSha: params.commitSha,
|
|
600
|
+
branch: params.branch ?? null,
|
|
601
|
+
state: params.state,
|
|
602
|
+
context: params.context,
|
|
603
|
+
description: desc,
|
|
604
|
+
targetUrl: params.targetUrl ?? null,
|
|
605
|
+
},
|
|
606
|
+
lastError: errDetail,
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, provider: 'gitlab', detail: errDetail };
|
|
610
|
+
}
|
|
611
|
+
return { published: true, provider: 'gitlab', detail: `Published GitLab commit status "${glState}"` };
|
|
612
|
+
} catch (error) {
|
|
613
|
+
const errDetail = `Commit status HTTP request failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
614
|
+
if (!params.skipOutboxOnError) {
|
|
615
|
+
await this.enqueueOutboxItem({
|
|
616
|
+
gateRunId: params.gateRunId,
|
|
617
|
+
pipelineId: params.pipelineId,
|
|
618
|
+
gitRepositoryId: params.gitRepositoryId,
|
|
619
|
+
kind: 'commit_status',
|
|
620
|
+
payload: {
|
|
621
|
+
gitRepositoryId: params.gitRepositoryId ?? null,
|
|
622
|
+
commitSha: params.commitSha,
|
|
623
|
+
branch: params.branch ?? null,
|
|
624
|
+
state: params.state,
|
|
625
|
+
context: params.context,
|
|
626
|
+
description: desc,
|
|
627
|
+
targetUrl: params.targetUrl ?? null,
|
|
628
|
+
},
|
|
629
|
+
lastError: errDetail,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
buildStickyCommentMarkdown(params: {
|
|
637
|
+
pipeline: CiPipelineRecord;
|
|
638
|
+
gateRun: CiGateRunRecord;
|
|
639
|
+
testRun: Record<string, unknown> | null;
|
|
640
|
+
triage?: CiTriageSummary | null;
|
|
641
|
+
workbenchUrl?: string;
|
|
642
|
+
}): { marker: string; markdown: string } {
|
|
643
|
+
const marker = `<!-- nocobase-ci:pipeline=${params.pipeline.key};pipelineId=${params.pipeline.id};mr=${
|
|
644
|
+
params.gateRun.mrIid ?? 0
|
|
645
|
+
};gateRun=${params.gateRun.id};sha=${params.gateRun.commitSha} -->`;
|
|
646
|
+
const verdict = String(params.testRun?.verdict || params.gateRun.testVerdict || params.gateRun.state).toUpperCase();
|
|
647
|
+
const approvalState = String(params.gateRun.approvalState || 'not_required').toUpperCase();
|
|
648
|
+
const deployOutcome = String(params.gateRun.deployOutcome || 'not_applicable').toUpperCase();
|
|
649
|
+
const reasonCode = String(params.testRun?.verdictReasonCode || params.gateRun.verdictReasonCode || '');
|
|
650
|
+
|
|
651
|
+
const badge =
|
|
652
|
+
verdict === 'PASSED'
|
|
653
|
+
? '✅ PASSED'
|
|
654
|
+
: verdict === 'DIFF_MISMATCH' && approvalState === 'APPROVED'
|
|
655
|
+
? '✅ DIFF MISMATCH (QA APPROVED)'
|
|
656
|
+
: verdict === 'DIFF_MISMATCH'
|
|
657
|
+
? '⚠️ DIFF MISMATCH'
|
|
658
|
+
: verdict === 'CANCELED'
|
|
659
|
+
? '⚪ CANCELED'
|
|
660
|
+
: `❌ ${verdict}`;
|
|
661
|
+
|
|
662
|
+
const metrics = isPlainRecord(params.testRun?.summaryMetrics) ? params.testRun.summaryMetrics : {};
|
|
663
|
+
const total = Number(metrics.total ?? 0);
|
|
664
|
+
const passed = Number(metrics.passed ?? 0);
|
|
665
|
+
const flaky = Number(metrics.flaky ?? 0);
|
|
666
|
+
const diffMismatch = Number(metrics.diffMismatch ?? 0);
|
|
667
|
+
const failed = Number(metrics.failed ?? 0);
|
|
668
|
+
const skipped = Number(metrics.skipped ?? 0);
|
|
669
|
+
const durationMs = Number(metrics.durationMs ?? params.testRun?.durationMs ?? 0);
|
|
670
|
+
const schemaUsed = String(params.testRun?.ephemeralSchemaName || 'tenant-default');
|
|
671
|
+
|
|
672
|
+
const lines = [
|
|
673
|
+
marker,
|
|
674
|
+
`### NocoBase CI Quality Gate — ${badge}`,
|
|
675
|
+
'',
|
|
676
|
+
`| Pipeline | Commit | Branch | Test Verdict | Approval | Deploy | Schema | Duration |`,
|
|
677
|
+
`| --- | --- | --- | --- | --- | --- | --- | --- |`,
|
|
678
|
+
`| **${params.pipeline.name}** | \`${params.gateRun.commitSha.slice(0, 8)}\` | \`${
|
|
679
|
+
params.gateRun.branch
|
|
680
|
+
}\` | \`${verdict}${
|
|
681
|
+
reasonCode ? ` (${reasonCode})` : ''
|
|
682
|
+
}\` | \`${approvalState}\` | \`${deployOutcome}\` | \`${schemaUsed}\` | ${(durationMs / 1000).toFixed(1)}s |`,
|
|
683
|
+
'',
|
|
684
|
+
`| Total | Passed | Flaky | Diff Mismatch | Failed | Skipped |`,
|
|
685
|
+
`| :---: | :---: | :---: | :---: | :---: | :---: |`,
|
|
686
|
+
`| ${total} | ${passed} | ${flaky} | ${diffMismatch} | ${failed} | ${skipped} |`,
|
|
687
|
+
];
|
|
688
|
+
|
|
689
|
+
if (params.triage) {
|
|
690
|
+
lines.push(
|
|
691
|
+
'',
|
|
692
|
+
`#### 🤖 AI Failure Triage (\`${params.triage.classification}\`, confidence ${Math.round(
|
|
693
|
+
params.triage.confidence * 100,
|
|
694
|
+
)}%)`,
|
|
695
|
+
`- **Root Cause:** ${params.triage.rootCause}`,
|
|
696
|
+
`- **Suggested Action:** ${params.triage.suggestedAction}`,
|
|
697
|
+
);
|
|
698
|
+
if (Array.isArray(params.triage.suspectedFiles) && params.triage.suspectedFiles.length > 0) {
|
|
699
|
+
lines.push(`- **Suspected Files:** ${params.triage.suspectedFiles.map((f) => `\`${f}\``).join(', ')}`);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (params.workbenchUrl) {
|
|
704
|
+
lines.push('', `[🔍 Inspect Multi-Layer Diff & Artifacts in NocoBase](${params.workbenchUrl})`);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
return { marker, markdown: lines.join('\n') };
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
private findMatchingCommentInPage(
|
|
711
|
+
items: Array<{ id?: number; body?: string }>,
|
|
712
|
+
pipeline: CiPipelineRecord,
|
|
713
|
+
mrIid: number,
|
|
714
|
+
): { id: string; gateRunId?: number } | null {
|
|
715
|
+
for (const item of items) {
|
|
716
|
+
if (!item?.id || typeof item.body !== 'string') continue;
|
|
717
|
+
const parsed = parseStickyCommentVersionMarker(item.body);
|
|
718
|
+
if (!parsed) continue;
|
|
719
|
+
const matchesPipeline =
|
|
720
|
+
(parsed.pipelineKey && parsed.pipelineKey === pipeline.key) ||
|
|
721
|
+
(parsed.pipelineId && parsed.pipelineId === pipeline.id);
|
|
722
|
+
const matchesMr = !parsed.mrIid || parsed.mrIid === mrIid;
|
|
723
|
+
if (matchesPipeline && matchesMr) {
|
|
724
|
+
return { id: String(item.id), gateRunId: parsed.gateRunId };
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async upsertStickyPrComment(params: {
|
|
731
|
+
pipeline: CiPipelineRecord;
|
|
732
|
+
gateRun: CiGateRunRecord;
|
|
733
|
+
testRun: Record<string, unknown> | null;
|
|
734
|
+
triage?: CiTriageSummary | null;
|
|
735
|
+
workbenchUrl?: string;
|
|
736
|
+
skipOutboxOnError?: boolean;
|
|
737
|
+
}): Promise<{
|
|
738
|
+
published: boolean;
|
|
739
|
+
skippedStale?: boolean;
|
|
740
|
+
queuedRetry?: boolean;
|
|
741
|
+
commentId?: string;
|
|
742
|
+
detail: string;
|
|
743
|
+
}> {
|
|
744
|
+
const mrIid = params.gateRun.mrIid;
|
|
745
|
+
if (!mrIid || mrIid <= 0) {
|
|
746
|
+
return { published: false, detail: 'No MR/PR number associated with this CI run' };
|
|
747
|
+
}
|
|
748
|
+
const auth = await this.resolveRepoAuth(params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId);
|
|
749
|
+
if (!auth || !auth.pat) {
|
|
750
|
+
return { published: false, detail: 'Git repository PAT unavailable; skipped PR comment' };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const { markdown } = this.buildStickyCommentMarkdown(params);
|
|
754
|
+
|
|
755
|
+
try {
|
|
756
|
+
if (auth.provider === 'github') {
|
|
757
|
+
const headers = {
|
|
758
|
+
Authorization: `Bearer ${auth.pat}`,
|
|
759
|
+
Accept: 'application/vnd.github.v3+json',
|
|
760
|
+
'Content-Type': 'application/json',
|
|
761
|
+
};
|
|
762
|
+
let existingId = params.gateRun.prCommentId || '';
|
|
763
|
+
let existingGateRunId: number | undefined;
|
|
764
|
+
|
|
765
|
+
for (let page = 1; page <= MAX_COMMENT_PAGES; page += 1) {
|
|
766
|
+
const listResp = await this.fetchImpl(
|
|
767
|
+
`${auth.apiBase}/repos/${auth.projectPath}/issues/${mrIid}/comments?per_page=${COMMENTS_PER_PAGE}&page=${page}`,
|
|
768
|
+
{ method: 'GET', headers },
|
|
769
|
+
);
|
|
770
|
+
if (!listResp.ok) break;
|
|
771
|
+
const comments = (await listResp.json()) as Array<{ id?: number; body?: string }>;
|
|
772
|
+
if (!Array.isArray(comments) || comments.length === 0) break;
|
|
773
|
+
|
|
774
|
+
const matched = this.findMatchingCommentInPage(comments, params.pipeline, mrIid);
|
|
775
|
+
if (matched) {
|
|
776
|
+
existingId = matched.id;
|
|
777
|
+
existingGateRunId = matched.gateRunId;
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
if (comments.length < COMMENTS_PER_PAGE && !hasNextLinkHeader(listResp)) {
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (existingGateRunId && existingGateRunId > params.gateRun.id) {
|
|
786
|
+
return {
|
|
787
|
+
published: false,
|
|
788
|
+
skippedStale: true,
|
|
789
|
+
commentId: existingId,
|
|
790
|
+
detail: `Skipped overwriting sticky comment because newer gate run #${existingGateRunId} already published`,
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if (existingId) {
|
|
795
|
+
const patchResp = await this.fetchImpl(
|
|
796
|
+
`${auth.apiBase}/repos/${auth.projectPath}/issues/comments/${existingId}`,
|
|
797
|
+
{
|
|
798
|
+
method: 'PATCH',
|
|
799
|
+
headers,
|
|
800
|
+
body: JSON.stringify({ body: markdown }),
|
|
801
|
+
},
|
|
802
|
+
);
|
|
803
|
+
if (patchResp.ok) {
|
|
804
|
+
return { published: true, commentId: existingId, detail: `Updated GitHub PR #${mrIid} comment` };
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const createResp = await this.fetchImpl(`${auth.apiBase}/repos/${auth.projectPath}/issues/${mrIid}/comments`, {
|
|
809
|
+
method: 'POST',
|
|
810
|
+
headers,
|
|
811
|
+
body: JSON.stringify({ body: markdown }),
|
|
812
|
+
});
|
|
813
|
+
if (!createResp.ok) {
|
|
814
|
+
const errDetail = `Failed to post GitHub PR comment (HTTP ${createResp.status})`;
|
|
815
|
+
if (!params.skipOutboxOnError) {
|
|
816
|
+
await this.enqueueOutboxItem({
|
|
817
|
+
gateRunId: params.gateRun.id,
|
|
818
|
+
pipelineId: params.pipeline.id,
|
|
819
|
+
gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
|
|
820
|
+
kind: 'sticky_comment',
|
|
821
|
+
payload: { workbenchUrl: params.workbenchUrl ?? null },
|
|
822
|
+
lastError: errDetail,
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
|
|
826
|
+
}
|
|
827
|
+
const created = (await createResp.json()) as { id?: number };
|
|
828
|
+
return {
|
|
829
|
+
published: true,
|
|
830
|
+
commentId: created.id ? String(created.id) : undefined,
|
|
831
|
+
detail: `Created GitHub PR #${mrIid} sticky summary comment`,
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// GitLab MR Note upsert with full pagination
|
|
836
|
+
const headers = {
|
|
837
|
+
'PRIVATE-TOKEN': auth.pat,
|
|
838
|
+
Accept: 'application/json',
|
|
839
|
+
'Content-Type': 'application/json',
|
|
840
|
+
};
|
|
841
|
+
let existingNoteId = params.gateRun.prCommentId || '';
|
|
842
|
+
let existingGateRunId: number | undefined;
|
|
843
|
+
|
|
844
|
+
for (let page = 1; page <= MAX_COMMENT_PAGES; page += 1) {
|
|
845
|
+
const listResp = await this.fetchImpl(
|
|
846
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes?per_page=${COMMENTS_PER_PAGE}&page=${page}`,
|
|
847
|
+
{ method: 'GET', headers },
|
|
848
|
+
);
|
|
849
|
+
if (!listResp.ok) break;
|
|
850
|
+
const notes = (await listResp.json()) as Array<{ id?: number; body?: string }>;
|
|
851
|
+
if (!Array.isArray(notes) || notes.length === 0) break;
|
|
852
|
+
|
|
853
|
+
const matched = this.findMatchingCommentInPage(notes, params.pipeline, mrIid);
|
|
854
|
+
if (matched) {
|
|
855
|
+
existingNoteId = matched.id;
|
|
856
|
+
existingGateRunId = matched.gateRunId;
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
if (notes.length < COMMENTS_PER_PAGE && !hasNextLinkHeader(listResp)) {
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
if (existingGateRunId && existingGateRunId > params.gateRun.id) {
|
|
865
|
+
return {
|
|
866
|
+
published: false,
|
|
867
|
+
skippedStale: true,
|
|
868
|
+
commentId: existingNoteId,
|
|
869
|
+
detail: `Skipped overwriting GitLab MR note because newer gate run #${existingGateRunId} already published`,
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (existingNoteId) {
|
|
874
|
+
const putResp = await this.fetchImpl(
|
|
875
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes/${existingNoteId}`,
|
|
876
|
+
{
|
|
877
|
+
method: 'PUT',
|
|
878
|
+
headers,
|
|
879
|
+
body: JSON.stringify({ body: markdown }),
|
|
880
|
+
},
|
|
881
|
+
);
|
|
882
|
+
if (putResp.ok) {
|
|
883
|
+
return { published: true, commentId: existingNoteId, detail: `Updated GitLab MR !${mrIid} note` };
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
const createResp = await this.fetchImpl(
|
|
888
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/merge_requests/${mrIid}/notes`,
|
|
889
|
+
{
|
|
890
|
+
method: 'POST',
|
|
891
|
+
headers,
|
|
892
|
+
body: JSON.stringify({ body: markdown }),
|
|
893
|
+
},
|
|
894
|
+
);
|
|
895
|
+
if (!createResp.ok) {
|
|
896
|
+
const errDetail = `Failed to post GitLab MR note (HTTP ${createResp.status})`;
|
|
897
|
+
if (!params.skipOutboxOnError) {
|
|
898
|
+
await this.enqueueOutboxItem({
|
|
899
|
+
gateRunId: params.gateRun.id,
|
|
900
|
+
pipelineId: params.pipeline.id,
|
|
901
|
+
gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
|
|
902
|
+
kind: 'sticky_comment',
|
|
903
|
+
payload: { workbenchUrl: params.workbenchUrl ?? null },
|
|
904
|
+
lastError: errDetail,
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
|
|
908
|
+
}
|
|
909
|
+
const created = (await createResp.json()) as { id?: number };
|
|
910
|
+
return {
|
|
911
|
+
published: true,
|
|
912
|
+
commentId: created.id ? String(created.id) : undefined,
|
|
913
|
+
detail: `Created GitLab MR !${mrIid} sticky summary note`,
|
|
914
|
+
};
|
|
915
|
+
} catch (error) {
|
|
916
|
+
const errDetail = `Sticky comment HTTP error: ${error instanceof Error ? error.message : String(error)}`;
|
|
917
|
+
if (!params.skipOutboxOnError) {
|
|
918
|
+
await this.enqueueOutboxItem({
|
|
919
|
+
gateRunId: params.gateRun.id,
|
|
920
|
+
pipelineId: params.pipeline.id,
|
|
921
|
+
gitRepositoryId: params.gateRun.gitRepositoryId ?? params.pipeline.gitRepositoryId,
|
|
922
|
+
kind: 'sticky_comment',
|
|
923
|
+
payload: { workbenchUrl: params.workbenchUrl ?? null },
|
|
924
|
+
lastError: errDetail,
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
return { published: false, queuedRetry: !params.skipOutboxOnError, detail: errDetail };
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
async flushOutboxBatch(
|
|
932
|
+
loadTestRun: (testRunId: number) => Promise<Record<string, unknown> | null>,
|
|
933
|
+
limit = 15,
|
|
934
|
+
): Promise<number> {
|
|
935
|
+
if (!this.hasCollection(CI_GIT_FEEDBACK_OUTBOX_COLLECTION)) return 0;
|
|
936
|
+
const repo = this.app.db.getRepository(CI_GIT_FEEDBACK_OUTBOX_COLLECTION);
|
|
937
|
+
const nowIso = new Date().toISOString();
|
|
938
|
+
const dueRows = (await repo
|
|
939
|
+
.find({
|
|
940
|
+
filter: {
|
|
941
|
+
status: 'pending',
|
|
942
|
+
$or: [{ nextRetryAt: null }, { nextRetryAt: { $lte: nowIso } }],
|
|
943
|
+
},
|
|
944
|
+
sort: ['id'],
|
|
945
|
+
limit,
|
|
946
|
+
})
|
|
947
|
+
.catch(() => [])) as Model[];
|
|
948
|
+
|
|
949
|
+
let deliveredCount = 0;
|
|
950
|
+
for (const item of dueRows) {
|
|
951
|
+
const gateRunId = Number(item.get('gateRunId') || 0);
|
|
952
|
+
const pipelineId = Number(item.get('pipelineId') || 0);
|
|
953
|
+
const kind = String(item.get('kind') || '');
|
|
954
|
+
const attempts = Number(item.get('attempts') || 1);
|
|
955
|
+
const payload = isPlainRecord(item.get('payload')) ? item.get('payload') : {};
|
|
956
|
+
|
|
957
|
+
const gateModel = (await this.app.db
|
|
958
|
+
.getRepository(CI_GATE_RUNS_COLLECTION)
|
|
959
|
+
.findOne({ filterByTk: gateRunId })
|
|
960
|
+
.catch(() => null)) as Model | null;
|
|
961
|
+
const pipeModel = (await this.app.db
|
|
962
|
+
.getRepository(CI_PIPELINES_COLLECTION)
|
|
963
|
+
.findOne({ filterByTk: pipelineId })
|
|
964
|
+
.catch(() => null)) as Model | null;
|
|
965
|
+
|
|
966
|
+
if (!gateModel || !pipeModel) {
|
|
967
|
+
await item.update({ status: 'exhausted', lastError: 'Gate run or pipeline deleted' }).catch(() => undefined);
|
|
968
|
+
continue;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
const gateRun = gateModel.toJSON() as CiGateRunRecord;
|
|
972
|
+
const pipeline = pipeModel.toJSON() as CiPipelineRecord;
|
|
973
|
+
let ok = false;
|
|
974
|
+
let errText = '';
|
|
975
|
+
|
|
976
|
+
if (kind === 'commit_status') {
|
|
977
|
+
const res = await this.publishCommitStatus({
|
|
978
|
+
gitRepositoryId:
|
|
979
|
+
Number(payload.gitRepositoryId || gateRun.gitRepositoryId || pipeline.gitRepositoryId || 0) || null,
|
|
980
|
+
commitSha: String(payload.commitSha || gateRun.commitSha),
|
|
981
|
+
branch: payload.branch ? String(payload.branch) : gateRun.branch,
|
|
982
|
+
state: (payload.state as GitCommitStatusState) || 'error',
|
|
983
|
+
context: String(payload.context || pipeline.statusContext || 'nocobase/ci-test-manager'),
|
|
984
|
+
description: String(payload.description || ''),
|
|
985
|
+
targetUrl: payload.targetUrl ? String(payload.targetUrl) : undefined,
|
|
986
|
+
skipOutboxOnError: true,
|
|
987
|
+
});
|
|
988
|
+
ok = res.published;
|
|
989
|
+
errText = res.detail;
|
|
990
|
+
if (ok) {
|
|
991
|
+
await gateModel
|
|
992
|
+
.update({
|
|
993
|
+
commitStatusState: (payload.state as GitCommitStatusState) || gateRun.commitStatusState,
|
|
994
|
+
gitFeedbackSyncState: 'synced',
|
|
995
|
+
})
|
|
996
|
+
.catch(() => undefined);
|
|
997
|
+
}
|
|
998
|
+
} else if (kind === 'sticky_comment') {
|
|
999
|
+
const testRun = gateRun.testRunId ? await loadTestRun(gateRun.testRunId) : null;
|
|
1000
|
+
const res = await this.upsertStickyPrComment({
|
|
1001
|
+
pipeline,
|
|
1002
|
+
gateRun,
|
|
1003
|
+
testRun,
|
|
1004
|
+
triage: gateRun.triageResult ?? null,
|
|
1005
|
+
workbenchUrl: payload.workbenchUrl ? String(payload.workbenchUrl) : undefined,
|
|
1006
|
+
skipOutboxOnError: true,
|
|
1007
|
+
});
|
|
1008
|
+
ok = res.published || Boolean(res.skippedStale);
|
|
1009
|
+
errText = res.detail;
|
|
1010
|
+
if (ok) {
|
|
1011
|
+
await gateModel
|
|
1012
|
+
.update({
|
|
1013
|
+
...(res.commentId ? { prCommentId: res.commentId } : {}),
|
|
1014
|
+
gitFeedbackSyncState: 'synced',
|
|
1015
|
+
})
|
|
1016
|
+
.catch(() => undefined);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
if (ok) {
|
|
1021
|
+
deliveredCount += 1;
|
|
1022
|
+
await item.update({ status: 'delivered', lastError: null }).catch(() => undefined);
|
|
1023
|
+
} else {
|
|
1024
|
+
const nextAttempts = attempts + 1;
|
|
1025
|
+
if (nextAttempts > MAX_OUTBOX_ATTEMPTS) {
|
|
1026
|
+
await item.update({ status: 'exhausted', attempts: nextAttempts, lastError: errText }).catch(() => undefined);
|
|
1027
|
+
await gateModel.update({ gitFeedbackSyncState: 'failed' }).catch(() => undefined);
|
|
1028
|
+
} else {
|
|
1029
|
+
const backoffMs = Math.min(300_000, 15_000 * 2 ** (nextAttempts - 1));
|
|
1030
|
+
await item
|
|
1031
|
+
.update({
|
|
1032
|
+
attempts: nextAttempts,
|
|
1033
|
+
nextRetryAt: new Date(Date.now() + backoffMs).toISOString(),
|
|
1034
|
+
lastError: errText,
|
|
1035
|
+
})
|
|
1036
|
+
.catch(() => undefined);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
return deliveredCount;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
private hasAttr(collectionName: string, attrName: string): boolean {
|
|
1045
|
+
try {
|
|
1046
|
+
const col = this.app.db.getCollection(collectionName) as
|
|
1047
|
+
| { getField?: (n: string) => unknown; model?: { rawAttributes?: Record<string, unknown> } }
|
|
1048
|
+
| undefined;
|
|
1049
|
+
return Boolean(col?.getField?.(attrName) || col?.model?.rawAttributes?.[attrName]);
|
|
1050
|
+
} catch {
|
|
1051
|
+
return false;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
async enrichPendingGitReviewRequests(params: {
|
|
1056
|
+
gitRepositoryId?: number | null;
|
|
1057
|
+
mrIid?: number | null;
|
|
1058
|
+
commitSha: string;
|
|
1059
|
+
testRun: Record<string, unknown> | null;
|
|
1060
|
+
triage?: CiTriageSummary | null;
|
|
1061
|
+
}): Promise<number> {
|
|
1062
|
+
if (!params.gitRepositoryId) {
|
|
1063
|
+
return 0;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
const verdict = String(params.testRun?.verdict || 'unknown');
|
|
1067
|
+
const metrics = isPlainRecord(params.testRun?.summaryMetrics) ? params.testRun.summaryMetrics : {};
|
|
1068
|
+
const ciContextLine = [
|
|
1069
|
+
`[NocoBase CI Verdict on ${params.commitSha.slice(0, 8)}]`,
|
|
1070
|
+
`verdict=${verdict}, passed=${Number(metrics.passed ?? 0)}, failed=${Number(
|
|
1071
|
+
metrics.failed ?? 0,
|
|
1072
|
+
)}, diffMismatch=${Number(metrics.diffMismatch ?? 0)}, flaky=${Number(metrics.flaky ?? 0)}.`,
|
|
1073
|
+
params.triage ? `AI Triage (${params.triage.classification}): ${params.triage.rootCause}` : '',
|
|
1074
|
+
]
|
|
1075
|
+
.filter(Boolean)
|
|
1076
|
+
.join(' ');
|
|
1077
|
+
|
|
1078
|
+
let enriched = 0;
|
|
1079
|
+
|
|
1080
|
+
if (this.hasAttr('gitCodeReviews', 'repositoryId') && this.hasAttr('gitCodeReviews', 'metadata')) {
|
|
1081
|
+
const reviewFilter: Record<string, unknown> = {
|
|
1082
|
+
repositoryId: params.gitRepositoryId,
|
|
1083
|
+
...(params.mrIid && this.hasAttr('gitCodeReviews', 'mrIid') ? { mrIid: params.mrIid } : {}),
|
|
1084
|
+
...(this.hasAttr('gitCodeReviews', 'headSha')
|
|
1085
|
+
? { headSha: params.commitSha }
|
|
1086
|
+
: this.hasAttr('gitCodeReviews', 'commitSha')
|
|
1087
|
+
? { commitSha: params.commitSha }
|
|
1088
|
+
: {}),
|
|
1089
|
+
};
|
|
1090
|
+
const reviewModels = (await this.app.db.getRepository('gitCodeReviews').find({
|
|
1091
|
+
filter: reviewFilter,
|
|
1092
|
+
limit: 10,
|
|
1093
|
+
})) as Model[];
|
|
1094
|
+
|
|
1095
|
+
for (const revModel of reviewModels) {
|
|
1096
|
+
const status = String(revModel.get('status') || '');
|
|
1097
|
+
if (status === 'completed' || status === 'approved') continue;
|
|
1098
|
+
const meta = isPlainRecord(revModel.get('metadata'))
|
|
1099
|
+
? { ...(revModel.get('metadata') as Record<string, unknown>) }
|
|
1100
|
+
: {};
|
|
1101
|
+
meta.ciSummary = ciContextLine;
|
|
1102
|
+
meta.ciVerdict = verdict;
|
|
1103
|
+
await revModel.update({ metadata: meta });
|
|
1104
|
+
enriched += 1;
|
|
1105
|
+
|
|
1106
|
+
if (this.hasAttr('gitReviewInbox', 'reviewId') && this.hasAttr('gitReviewInbox', 'payload')) {
|
|
1107
|
+
const inboxRows = (await this.app.db.getRepository('gitReviewInbox').find({
|
|
1108
|
+
filter: { repositoryId: params.gitRepositoryId, reviewId: revModel.get('id'), state: 'queued' },
|
|
1109
|
+
limit: 5,
|
|
1110
|
+
})) as Model[];
|
|
1111
|
+
for (const inbox of inboxRows) {
|
|
1112
|
+
const payload = isPlainRecord(inbox.get('payload'))
|
|
1113
|
+
? { ...(inbox.get('payload') as Record<string, unknown>) }
|
|
1114
|
+
: {};
|
|
1115
|
+
const existingInst = typeof payload.instructions === 'string' ? payload.instructions : '';
|
|
1116
|
+
if (!existingInst.includes('[NocoBase CI Verdict on')) {
|
|
1117
|
+
payload.instructions = existingInst ? `${existingInst}\n\n${ciContextLine}` : ciContextLine;
|
|
1118
|
+
await inbox.update({ payload });
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
if (
|
|
1126
|
+
this.hasAttr(GIT_REVIEW_REQUESTS_COLLECTION, 'headSha') &&
|
|
1127
|
+
this.hasAttr(GIT_REVIEW_REQUESTS_COLLECTION, 'payload')
|
|
1128
|
+
) {
|
|
1129
|
+
const reqRepo = this.app.db.getRepository(GIT_REVIEW_REQUESTS_COLLECTION);
|
|
1130
|
+
const candidates = (await reqRepo.find({
|
|
1131
|
+
filter: {
|
|
1132
|
+
repositoryId: params.gitRepositoryId,
|
|
1133
|
+
...(params.mrIid && this.hasAttr(GIT_REVIEW_REQUESTS_COLLECTION, 'mrIid') ? { mrIid: params.mrIid } : {}),
|
|
1134
|
+
headSha: params.commitSha,
|
|
1135
|
+
},
|
|
1136
|
+
limit: 10,
|
|
1137
|
+
})) as Model[];
|
|
1138
|
+
|
|
1139
|
+
for (const reqModel of candidates) {
|
|
1140
|
+
if (reqModel.get('executionId')) continue;
|
|
1141
|
+
const payload = isPlainRecord(reqModel.get('payload'))
|
|
1142
|
+
? { ...(reqModel.get('payload') as Record<string, unknown>) }
|
|
1143
|
+
: {};
|
|
1144
|
+
const existingInstructions = typeof payload.instructions === 'string' ? payload.instructions : '';
|
|
1145
|
+
if (existingInstructions.includes('[NocoBase CI Verdict on')) continue;
|
|
1146
|
+
payload.instructions = existingInstructions ? `${existingInstructions}\n\n${ciContextLine}` : ciContextLine;
|
|
1147
|
+
await reqModel.update({ payload });
|
|
1148
|
+
enriched += 1;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
return enriched;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
async listOpenMergeRequests(gitRepositoryId: number): Promise<
|
|
1156
|
+
Array<{
|
|
1157
|
+
mrIid: number;
|
|
1158
|
+
sourceBranch: string;
|
|
1159
|
+
targetBranch: string;
|
|
1160
|
+
headSha: string;
|
|
1161
|
+
title: string;
|
|
1162
|
+
}>
|
|
1163
|
+
> {
|
|
1164
|
+
const auth = await this.resolveRepoAuth(gitRepositoryId);
|
|
1165
|
+
if (!auth || !auth.pat) return [];
|
|
1166
|
+
|
|
1167
|
+
if (auth.provider === 'github') {
|
|
1168
|
+
const resp = await this.fetchImpl(
|
|
1169
|
+
`${auth.apiBase}/repos/${auth.projectPath}/pulls?state=open&per_page=25&sort=updated&direction=desc`,
|
|
1170
|
+
{
|
|
1171
|
+
method: 'GET',
|
|
1172
|
+
headers: {
|
|
1173
|
+
Authorization: `Bearer ${auth.pat}`,
|
|
1174
|
+
Accept: 'application/vnd.github.v3+json',
|
|
1175
|
+
},
|
|
1176
|
+
},
|
|
1177
|
+
);
|
|
1178
|
+
if (!resp.ok) return [];
|
|
1179
|
+
const prs = (await resp.json()) as Array<{
|
|
1180
|
+
number?: number;
|
|
1181
|
+
title?: string;
|
|
1182
|
+
head?: { ref?: string; sha?: string };
|
|
1183
|
+
base?: { ref?: string };
|
|
1184
|
+
}>;
|
|
1185
|
+
return prs
|
|
1186
|
+
.filter((pr) => Boolean(pr.number && pr.head?.sha && pr.head?.ref))
|
|
1187
|
+
.map((pr) => ({
|
|
1188
|
+
mrIid: Number(pr.number),
|
|
1189
|
+
sourceBranch: String(pr.head?.ref || ''),
|
|
1190
|
+
targetBranch: String(pr.base?.ref || 'main'),
|
|
1191
|
+
headSha: String(pr.head?.sha || ''),
|
|
1192
|
+
title: String(pr.title || ''),
|
|
1193
|
+
}));
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
const resp = await this.fetchImpl(
|
|
1197
|
+
`${auth.apiBase}/projects/${auth.encodedProject}/merge_requests?state=opened&per_page=25&order_by=updated_at&sort=desc`,
|
|
1198
|
+
{
|
|
1199
|
+
method: 'GET',
|
|
1200
|
+
headers: {
|
|
1201
|
+
'PRIVATE-TOKEN': auth.pat,
|
|
1202
|
+
Accept: 'application/json',
|
|
1203
|
+
},
|
|
1204
|
+
},
|
|
1205
|
+
);
|
|
1206
|
+
if (!resp.ok) return [];
|
|
1207
|
+
const mrs = (await resp.json()) as Array<{
|
|
1208
|
+
iid?: number;
|
|
1209
|
+
title?: string;
|
|
1210
|
+
source_branch?: string;
|
|
1211
|
+
target_branch?: string;
|
|
1212
|
+
sha?: string;
|
|
1213
|
+
}>;
|
|
1214
|
+
return mrs
|
|
1215
|
+
.filter((mr) => Boolean(mr.iid && mr.sha && mr.source_branch))
|
|
1216
|
+
.map((mr) => ({
|
|
1217
|
+
mrIid: Number(mr.iid),
|
|
1218
|
+
sourceBranch: String(mr.source_branch || ''),
|
|
1219
|
+
targetBranch: String(mr.target_branch || 'main'),
|
|
1220
|
+
headSha: String(mr.sha || ''),
|
|
1221
|
+
title: String(mr.title || ''),
|
|
1222
|
+
}));
|
|
1223
|
+
}
|
|
1224
|
+
}
|