opencode-forgekeeper 6.2.1 → 6.3.1
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 +5 -4
- package/dist/gui-experimental.cjs +173 -172
- package/dist/index.js +6047 -5543
- package/dist/tui.js +1601 -1360
- package/package.json +1 -1
package/dist/tui.js
CHANGED
|
@@ -11,11 +11,21 @@ import { createElement as _$createElement } from "@opentui/solid";
|
|
|
11
11
|
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js";
|
|
12
12
|
// packages/_shared/src/exec.ts
|
|
13
13
|
import { execFile } from "child_process";
|
|
14
|
+
function mergeEnv(overrides) {
|
|
15
|
+
const merged = { ...process.env };
|
|
16
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
17
|
+
if (value === undefined)
|
|
18
|
+
delete merged[key];
|
|
19
|
+
else
|
|
20
|
+
merged[key] = value;
|
|
21
|
+
}
|
|
22
|
+
return merged;
|
|
23
|
+
}
|
|
14
24
|
function exec(file, args, options = {}) {
|
|
15
25
|
return new Promise((resolve) => {
|
|
16
26
|
const child = execFile(file, args, {
|
|
17
27
|
cwd: options.cwd,
|
|
18
|
-
env: options.env ?
|
|
28
|
+
env: options.env ? mergeEnv(options.env) : process.env,
|
|
19
29
|
timeout: options.timeout,
|
|
20
30
|
maxBuffer: 16 * 1024 * 1024,
|
|
21
31
|
encoding: "utf8",
|
|
@@ -44,11 +54,19 @@ function exec(file, args, options = {}) {
|
|
|
44
54
|
var execWithTimeout = (timeout) => (file, args, cwd) => exec(file, args, { cwd, timeout });
|
|
45
55
|
var exec2 = execWithTimeout(30000);
|
|
46
56
|
|
|
47
|
-
// packages/
|
|
57
|
+
// packages/_merge-readiness/src/types.ts
|
|
48
58
|
var FINISHED = new Set(["SUCCESS", "FAILED", "CANCELED", "CANCELLED", "SKIPPED", "MANUAL"]);
|
|
49
59
|
var pipelineRunning = (pipeline) => !!pipeline && (pipeline.running ?? !FINISHED.has(pipeline.status));
|
|
50
60
|
var unlistedFailure = (pipeline) => pipeline?.failedJobsComplete === false && !pipeline.failedJobs?.length && pipeline.status === "FAILED";
|
|
51
61
|
var pipelineFails = (pipeline) => !!pipeline?.failedJobs?.length || unlistedFailure(pipeline);
|
|
62
|
+
|
|
63
|
+
class ForgeError extends Error {
|
|
64
|
+
kind;
|
|
65
|
+
constructor(kind, message) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.kind = kind;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
52
70
|
function approversOf(request) {
|
|
53
71
|
if (request.approvers)
|
|
54
72
|
return request.approvers;
|
|
@@ -61,11 +79,14 @@ var approvalsComplete = (request) => request.approvalsComplete !== false && requ
|
|
|
61
79
|
function changesRequestedState(request) {
|
|
62
80
|
return request.state === "opened" && !request.draft ? request.changesRequested : false;
|
|
63
81
|
}
|
|
64
|
-
var
|
|
65
|
-
var
|
|
66
|
-
function
|
|
67
|
-
|
|
82
|
+
var yesNo = (value) => value ? "yes" : "no";
|
|
83
|
+
var humanize = (value) => value.toLowerCase().replace(/_/g, " ");
|
|
84
|
+
function awaitingText(reviewers) {
|
|
85
|
+
if (reviewers.length > 2)
|
|
86
|
+
return `awaiting ${reviewers.length} reviewers`;
|
|
87
|
+
return `awaiting ${reviewers.map((username) => `@${username}`).join(", ")}`;
|
|
68
88
|
}
|
|
89
|
+
var isGitLabHost = (host) => /(^|\.)gitlab\./.test(host);
|
|
69
90
|
function parseWebUrl(kind, value, pattern) {
|
|
70
91
|
let url;
|
|
71
92
|
try {
|
|
@@ -78,30 +99,280 @@ function parseWebUrl(kind, value, pattern) {
|
|
|
78
99
|
const match = url.pathname.match(pattern);
|
|
79
100
|
if (!match)
|
|
80
101
|
return;
|
|
102
|
+
let project;
|
|
103
|
+
try {
|
|
104
|
+
project = decodeURIComponent(match[1]);
|
|
105
|
+
} catch {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
81
108
|
return {
|
|
82
109
|
forge: kind,
|
|
83
|
-
host: url.
|
|
84
|
-
project
|
|
110
|
+
host: url.host.toLowerCase(),
|
|
111
|
+
project,
|
|
85
112
|
iid: match[2]
|
|
86
113
|
};
|
|
87
114
|
}
|
|
88
|
-
var
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return `awaiting ${reviewers.length} reviewers`;
|
|
93
|
-
return `awaiting ${reviewers.map((username) => `@${username}`).join(", ")}`;
|
|
115
|
+
var parseGitLabUrl = (url) => parseWebUrl("gitlab", url, /^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);
|
|
116
|
+
function parseGitHubUrl(url) {
|
|
117
|
+
const ref = parseWebUrl("github", url, /^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/);
|
|
118
|
+
return ref && !isGitLabHost(ref.host) ? ref : undefined;
|
|
94
119
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
120
|
+
// packages/_merge-readiness/src/legacy.ts
|
|
121
|
+
function isAutomatedReviewRunning(request) {
|
|
122
|
+
if (request.forge === "gitlab")
|
|
123
|
+
return request.duoReviewState === "REVIEW_STARTED";
|
|
124
|
+
return request.copilotReview?.requested === true;
|
|
125
|
+
}
|
|
126
|
+
function autoMergeCandidate(request) {
|
|
127
|
+
if (request.state !== "opened" || request.draft || request.autoMergeEnabled === true || request.mergeTrainIndex != null)
|
|
128
|
+
return false;
|
|
129
|
+
if (!request.conflictsKnown || !approvalsComplete(request) || request.autoMergeEnabled !== false)
|
|
130
|
+
return;
|
|
131
|
+
if (!approvalsSatisfied(request) || request.conflicts || request.changesRequested || request.duoReviewState === "REVIEW_STARTED")
|
|
132
|
+
return false;
|
|
133
|
+
if (mergeBlocker(request) || pipelineFails(request.pipeline) || request.pipeline?.status === "FAILED")
|
|
134
|
+
return false;
|
|
135
|
+
if (!request.threadsComplete || request.unresolvedThreads > 0 && request.discussionResolutionRequired !== false)
|
|
136
|
+
return;
|
|
137
|
+
if (!request.mergeStatus)
|
|
138
|
+
return;
|
|
139
|
+
return request.mergeStatus === "MERGEABLE" || request.mergeStatus === "CI_STILL_RUNNING" && pipelineRunning(request.pipeline);
|
|
140
|
+
}
|
|
141
|
+
function readyToMergeState(request) {
|
|
142
|
+
const candidate = autoMergeCandidate(request);
|
|
143
|
+
if (candidate === false)
|
|
144
|
+
return "none";
|
|
145
|
+
if (candidate === undefined)
|
|
146
|
+
return;
|
|
147
|
+
if (request.autoMergeAvailable === true)
|
|
148
|
+
return "auto-merge";
|
|
149
|
+
if (request.mergeStatus === "MERGEABLE") {
|
|
150
|
+
if (request.canMerge === true)
|
|
151
|
+
return "merge";
|
|
152
|
+
if (request.canMerge === false)
|
|
153
|
+
return "maintainer-merge";
|
|
154
|
+
}
|
|
155
|
+
if (request.autoMergeAvailable === false)
|
|
156
|
+
return "none";
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
function readyToMerge(request) {
|
|
160
|
+
const state = readyToMergeState(request);
|
|
161
|
+
if (state === undefined)
|
|
162
|
+
return;
|
|
163
|
+
return state !== "none";
|
|
164
|
+
}
|
|
165
|
+
function requestReadyToMergeState(request) {
|
|
166
|
+
return request.forge === "gitlab" ? readyToMergeState(request) : undefined;
|
|
167
|
+
}
|
|
168
|
+
function gitlabMergeStatusBlocker(mergeStatus) {
|
|
169
|
+
switch (mergeStatus) {
|
|
170
|
+
case "NEED_REBASE":
|
|
171
|
+
return "rebase";
|
|
172
|
+
case "JIRA_ASSOCIATION_MISSING":
|
|
173
|
+
return "jira";
|
|
174
|
+
case "EXTERNAL_STATUS_CHECKS":
|
|
175
|
+
return "status-checks";
|
|
176
|
+
case "BLOCKED_STATUS":
|
|
177
|
+
return "blocked";
|
|
178
|
+
default:
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function hasUnresolvedThreads(request) {
|
|
183
|
+
return request.mergeStatus === "DISCUSSIONS_NOT_RESOLVED" || request.discussionResolutionRequired === true && request.unresolvedThreads > 0;
|
|
184
|
+
}
|
|
185
|
+
function autoMergeDetail(request) {
|
|
186
|
+
if (hasUnresolvedThreads(request))
|
|
187
|
+
return "Auto-merge: set (blocked by unresolved threads)";
|
|
188
|
+
if (gitlabMergeStatusBlocker(request.mergeStatus) && request.mergeStatus) {
|
|
189
|
+
return `Auto-merge: set (blocked: ${humanize(request.mergeStatus)})`;
|
|
190
|
+
}
|
|
191
|
+
return "Auto-merge: set";
|
|
192
|
+
}
|
|
193
|
+
function manualBlockerIndicator(blocker) {
|
|
194
|
+
switch (blocker) {
|
|
195
|
+
case "rebase":
|
|
196
|
+
return { text: "needs rebase", tone: "warning", optional: true };
|
|
197
|
+
case "jira":
|
|
198
|
+
return { text: "missing Jira issue", tone: "warning", optional: true };
|
|
199
|
+
case "status-checks":
|
|
200
|
+
return { text: "status checks pending", tone: "warning", optional: true };
|
|
201
|
+
case "blocked":
|
|
202
|
+
return { text: "merge blocked", tone: "warning", optional: true };
|
|
203
|
+
default:
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function needsApproval(request) {
|
|
208
|
+
return (request.missingRules?.length ?? 0) > 0 || (request.approvalsLeft ?? 0) > 0 || request.mergeStatus === "NOT_APPROVED";
|
|
209
|
+
}
|
|
210
|
+
function approvalsSatisfied(request) {
|
|
211
|
+
if (needsApproval(request))
|
|
212
|
+
return false;
|
|
213
|
+
return request.approvalRequirementsSatisfied ?? (request.approved && request.awaitingReviewers.length === 0);
|
|
214
|
+
}
|
|
215
|
+
function requestApprovalsSatisfied(request) {
|
|
216
|
+
if (request.forge === "gitlab")
|
|
217
|
+
return approvalsSatisfied(request);
|
|
218
|
+
return request.approved && request.awaitingReviewers.length === 0;
|
|
219
|
+
}
|
|
220
|
+
function mergeBlocker(request) {
|
|
221
|
+
if (hasUnresolvedThreads(request))
|
|
222
|
+
return "threads";
|
|
223
|
+
return gitlabMergeStatusBlocker(request.mergeStatus);
|
|
224
|
+
}
|
|
225
|
+
function canProceedToMerge(request) {
|
|
226
|
+
return !request.conflicts && request.pipeline?.status !== "FAILED";
|
|
227
|
+
}
|
|
228
|
+
function hasAutoMergeReadyApprovals(request) {
|
|
229
|
+
return Boolean(request.autoMergeEnabled) && !needsApproval(request) && (request.approvalRequirementsSatisfied === true || request.mergeStatus === "MERGEABLE");
|
|
230
|
+
}
|
|
231
|
+
function approvalCount(request) {
|
|
232
|
+
const left = request.approvalsLeft ?? 0;
|
|
233
|
+
if (left <= 0 || request.approvalRequirementsSatisfied === true)
|
|
234
|
+
return;
|
|
235
|
+
const given = approversOf(request).filter((approver) => !approver.bot).length;
|
|
236
|
+
return {
|
|
237
|
+
text: given ? `${given} approval${given === 1 ? "" : "s"} \xB7 ${left} more needed` : `${left} approval${left === 1 ? "" : "s"} needed`,
|
|
238
|
+
compact: given ? `${given} \u2713 +${left}` : `+${left}`,
|
|
239
|
+
tone: "muted",
|
|
240
|
+
optional: true
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function waitingOn(request) {
|
|
244
|
+
const awaiting = request.awaitingReviewers.length ? { text: awaitingText(request.awaitingReviewers), tone: "muted" } : undefined;
|
|
245
|
+
if (awaiting && !approvalsSatisfied(request))
|
|
246
|
+
return awaiting;
|
|
247
|
+
if (request.draft || request.changesRequested === true)
|
|
248
|
+
return awaiting;
|
|
249
|
+
const statusBlocker = gitlabMergeStatusBlocker(request.mergeStatus);
|
|
250
|
+
if (canProceedToMerge(request)) {
|
|
251
|
+
if (request.mergeTrainIndex != null)
|
|
252
|
+
return { text: `merge train #${request.mergeTrainIndex + 1}`, tone: "muted", optional: true };
|
|
253
|
+
if (hasAutoMergeReadyApprovals(request)) {
|
|
254
|
+
if (hasUnresolvedThreads(request) || statusBlocker)
|
|
255
|
+
return {
|
|
256
|
+
text: "auto-merge blocked",
|
|
257
|
+
compact: "auto-merge \u26D4",
|
|
258
|
+
tone: "warning",
|
|
259
|
+
optional: true
|
|
260
|
+
};
|
|
261
|
+
return awaiting ?? { text: "auto-merge set", tone: "success", optional: true };
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (request.approved || request.approvalRequirementsSatisfied === true) {
|
|
265
|
+
if (canProceedToMerge(request) && !needsApproval(request)) {
|
|
266
|
+
if (hasUnresolvedThreads(request))
|
|
267
|
+
return { text: "merge blocked", tone: "warning", optional: true };
|
|
268
|
+
return manualBlockerIndicator(statusBlocker) ?? awaiting;
|
|
269
|
+
}
|
|
270
|
+
return awaiting;
|
|
271
|
+
}
|
|
272
|
+
const missingRules = request.missingRules ?? [];
|
|
273
|
+
const rule = missingRules.find((item) => item.type === "CODE_OWNER" || item.type === "REGULAR");
|
|
274
|
+
if (rule)
|
|
275
|
+
return {
|
|
276
|
+
text: rule.type === "CODE_OWNER" ? "needs a code owner" : "needs an approver",
|
|
277
|
+
tone: "warning",
|
|
278
|
+
optional: true
|
|
279
|
+
};
|
|
280
|
+
if (request.reviewersComplete && needsApproval(request))
|
|
281
|
+
return { text: "needs a reviewer", tone: "muted", optional: true };
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
function reviewIndicators(request) {
|
|
285
|
+
const count = approvalCount(request);
|
|
286
|
+
const next = waitingOn(request);
|
|
287
|
+
return [
|
|
288
|
+
...count ? [count] : [],
|
|
289
|
+
...request.changesRequested === true ? [{ text: "changes requested", tone: "warning", essential: true }] : [],
|
|
290
|
+
...request.approved && !request.awaitingReviewers.length ? [{ text: "approved", tone: "success" }] : [],
|
|
291
|
+
...next ? [next] : []
|
|
292
|
+
];
|
|
293
|
+
}
|
|
294
|
+
function discussionBlocker(request) {
|
|
295
|
+
if (request.discussionResolutionRequired === false)
|
|
296
|
+
return "none";
|
|
297
|
+
if (request.unresolvedThreads > 0)
|
|
298
|
+
return request.discussionResolutionRequired === true ? "threads" : undefined;
|
|
299
|
+
return request.threadsComplete ? "none" : undefined;
|
|
300
|
+
}
|
|
301
|
+
function mergeBlockedState(request) {
|
|
302
|
+
if (request.state !== "opened" || request.draft)
|
|
303
|
+
return "none";
|
|
304
|
+
if (!approvalsComplete(request) || !request.conflictsKnown)
|
|
305
|
+
return;
|
|
306
|
+
if (isAutomatedReviewRunning(request))
|
|
307
|
+
return;
|
|
308
|
+
const satisfied = requestApprovalsSatisfied(request);
|
|
309
|
+
if (!satisfied || request.conflicts || changesRequestedState(request) === true)
|
|
310
|
+
return "none";
|
|
311
|
+
if (pipelineFails(request.pipeline) || request.pipeline?.status === "FAILED")
|
|
312
|
+
return "none";
|
|
313
|
+
const forgeBlocker = request.forge === "gitlab" ? mergeBlocker(request) : undefined;
|
|
314
|
+
return forgeBlocker ?? discussionBlocker(request);
|
|
315
|
+
}
|
|
316
|
+
function mergeBlockedReason(request) {
|
|
317
|
+
const state = mergeBlockedState(request);
|
|
318
|
+
return state === "none" ? undefined : state;
|
|
319
|
+
}
|
|
320
|
+
function mergeNextStep(request, options = {}) {
|
|
321
|
+
if (mergeBlockedReason(request) === "threads") {
|
|
322
|
+
const offerAutoMergeAfterThreads = request.forge === "gitlab" && request.autoMergeEnabled === false && request.mergeTrainIndex == null;
|
|
323
|
+
const base = offerAutoMergeAfterThreads ? "Resolve the blocking threads, then select Set to auto-merge in GitLab when available." : "Resolve the blocking threads.";
|
|
324
|
+
const shortcut = options.canReviewThreads ? " In /forge-feedback, select the merge-blocked item and choose Review blocking threads." : "";
|
|
325
|
+
return {
|
|
326
|
+
text: offerAutoMergeAfterThreads ? "resolve threads \u2192 Set to auto-merge" : "resolve threads",
|
|
327
|
+
compact: offerAutoMergeAfterThreads ? "threads \u2192 auto-merge" : "resolve threads",
|
|
328
|
+
tone: "warning",
|
|
329
|
+
essential: true,
|
|
330
|
+
detail: `${base}${shortcut}`
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
switch (requestReadyToMergeState(request)) {
|
|
334
|
+
case "auto-merge":
|
|
335
|
+
return {
|
|
336
|
+
text: "Set to auto-merge",
|
|
337
|
+
tone: "warning",
|
|
338
|
+
essential: true,
|
|
339
|
+
url: request.url,
|
|
340
|
+
detail: "Open the merge request in GitLab and select Set to auto-merge."
|
|
341
|
+
};
|
|
342
|
+
case "merge":
|
|
343
|
+
return {
|
|
344
|
+
text: "ready to merge",
|
|
345
|
+
tone: "warning",
|
|
346
|
+
essential: true,
|
|
347
|
+
url: request.url,
|
|
348
|
+
detail: "Open the merge request in GitLab and select Merge."
|
|
349
|
+
};
|
|
350
|
+
case "maintainer-merge":
|
|
351
|
+
return {
|
|
352
|
+
text: "ready for maintainer merge",
|
|
353
|
+
compact: "needs maintainer merge",
|
|
354
|
+
tone: "warning",
|
|
355
|
+
essential: true,
|
|
356
|
+
url: request.url,
|
|
357
|
+
detail: "All merge requirements are met, but your account does not have permission to merge. Ask a maintainer to merge it."
|
|
358
|
+
};
|
|
359
|
+
default:
|
|
360
|
+
return;
|
|
101
361
|
}
|
|
102
362
|
}
|
|
363
|
+
function newestRequestsFirst(requests) {
|
|
364
|
+
return requests.map((request) => {
|
|
365
|
+
const updatedAt = Date.parse(request.updatedAt ?? "");
|
|
366
|
+
return { request, updatedAt: Number.isNaN(updatedAt) ? Number.MIN_SAFE_INTEGER : updatedAt };
|
|
367
|
+
}).sort((a, b) => b.updatedAt - a.updatedAt).map(({ request }) => request);
|
|
368
|
+
}
|
|
103
369
|
|
|
104
|
-
// packages/
|
|
370
|
+
// packages/_merge-readiness/src/evaluate.ts
|
|
371
|
+
var DUO_FEEDBACK = new Set(["REVIEWED", "REQUESTED_CHANGES"]);
|
|
372
|
+
// packages/_merge-readiness/src/sources.ts
|
|
373
|
+
var query = (text) => text;
|
|
374
|
+
var typed = (transport) => async (host, doc, variables) => await transport(host, doc, variables);
|
|
375
|
+
var MAX_DISCUSSION_PAGES = 50;
|
|
105
376
|
var MAX_REVIEW_THREADS = 30;
|
|
106
377
|
async function discussionPages(limit, read) {
|
|
107
378
|
const nodes = [];
|
|
@@ -125,29 +396,1190 @@ async function discussionPages(limit, read) {
|
|
|
125
396
|
}
|
|
126
397
|
return { nodes, complete: false };
|
|
127
398
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
var
|
|
131
|
-
var
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
var
|
|
135
|
-
var
|
|
136
|
-
var
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
399
|
+
var GITLAB_DISCUSSIONS = "pageInfo { hasNextPage endCursor } nodes { resolvable resolved }";
|
|
400
|
+
var GITLAB_PAGE_SIZE = 100;
|
|
401
|
+
var FIRST_FAILED_JOBS = 10;
|
|
402
|
+
var FAILED_JOBS = "pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }";
|
|
403
|
+
var RECHECKING = new Set(["CHECKING", "UNCHECKED", "PREPARING"]);
|
|
404
|
+
var CONFLICT_RECHECK = "CANNOT_BE_MERGED_RECHECK";
|
|
405
|
+
var REVIEWER_FIELDS = (includeApprovedAt) => `pageInfo { hasNextPage endCursor } nodes { id type username bot mergeRequestInteraction { reviewState approved${includeApprovedAt ? " approvedAt" : ""} } }`;
|
|
406
|
+
var APPROVED_BY_FIELDS = "pageInfo { hasNextPage endCursor } nodes { id username bot }";
|
|
407
|
+
var mergeRequestFields = (includeApprovedAt, includeExtendedStatus) => `
|
|
408
|
+
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
409
|
+
autoMergeEnabled
|
|
410
|
+
${includeExtendedStatus ? `
|
|
411
|
+
approvalsRequired approvalsLeft mergeTrainCar { index }
|
|
412
|
+
approvalState { rules { name type approvalsRequired approved eligibleApprovers { username type bot } } }
|
|
413
|
+
` : ""}
|
|
414
|
+
approvedBy(first: ${GITLAB_PAGE_SIZE}) { ${APPROVED_BY_FIELDS} }
|
|
415
|
+
sourceProject { fullPath }
|
|
416
|
+
targetProject { fullPath }
|
|
417
|
+
author { id username }
|
|
418
|
+
headPipeline {
|
|
419
|
+
id status path detailedStatus { label }
|
|
420
|
+
jobs(statuses: [FAILED], retried: false, first: ${FIRST_FAILED_JOBS}) { ${FAILED_JOBS} }
|
|
421
|
+
}
|
|
422
|
+
reviewers(first: ${GITLAB_PAGE_SIZE}) { ${REVIEWER_FIELDS(includeApprovedAt)} }
|
|
423
|
+
discussions(first: ${GITLAB_PAGE_SIZE}) { ${GITLAB_DISCUSSIONS} }
|
|
424
|
+
`;
|
|
425
|
+
function mergeRequestsQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
426
|
+
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
427
|
+
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
428
|
+
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) {
|
|
429
|
+
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${fields} } }
|
|
430
|
+
}`).join(`
|
|
431
|
+
`);
|
|
432
|
+
return query(`query($branch: String!, ${variables}) {
|
|
433
|
+
${projects}
|
|
434
|
+
}`);
|
|
435
|
+
}
|
|
436
|
+
function mergeRequestQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
437
|
+
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
438
|
+
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
439
|
+
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) { mergeRequest(iid: $iid) { ${fields} } }`).join(`
|
|
440
|
+
`);
|
|
441
|
+
return query(`query($iid: String!, ${variables}) {
|
|
442
|
+
${projects}
|
|
443
|
+
}`);
|
|
444
|
+
}
|
|
445
|
+
var DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
446
|
+
project(fullPath: $project) {
|
|
447
|
+
mergeRequest(iid: $iid) { discussions(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${GITLAB_DISCUSSIONS} } }
|
|
448
|
+
}
|
|
449
|
+
}`);
|
|
450
|
+
var reviewersQuery = (includeApprovedAt) => query(`query($project: ID!, $iid: String!, $after: String) {
|
|
451
|
+
project(fullPath: $project) {
|
|
452
|
+
mergeRequest(iid: $iid) { reviewers(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${REVIEWER_FIELDS(includeApprovedAt)} } }
|
|
453
|
+
}
|
|
454
|
+
}`);
|
|
455
|
+
var APPROVED_BY_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
456
|
+
project(fullPath: $project) {
|
|
457
|
+
mergeRequest(iid: $iid) { approvedBy(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${APPROVED_BY_FIELDS} } }
|
|
458
|
+
}
|
|
459
|
+
}`);
|
|
460
|
+
var UNRESOLVED_DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
461
|
+
project(fullPath: $project) {
|
|
462
|
+
mergeRequest(iid: $iid) {
|
|
463
|
+
state
|
|
464
|
+
discussions(first: ${GITLAB_PAGE_SIZE}, after: $after) {
|
|
465
|
+
pageInfo { hasNextPage endCursor }
|
|
466
|
+
nodes {
|
|
467
|
+
id resolvable resolved
|
|
468
|
+
notes(first: 1) { nodes { id } }
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}`);
|
|
474
|
+
var DISCUSSION_BY_NOTE = query(`
|
|
475
|
+
query($note: NoteID!, $after: String) {
|
|
476
|
+
note(id: $note) {
|
|
477
|
+
discussion {
|
|
478
|
+
id resolvable resolved
|
|
479
|
+
noteable { ... on MergeRequest { webUrl } }
|
|
480
|
+
notes(first: 20, after: $after) {
|
|
481
|
+
pageInfo { hasNextPage endCursor }
|
|
482
|
+
nodes { id url body createdAt system position { newPath newLine oldPath oldLine } author { id username bot } }
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
`);
|
|
488
|
+
var GITLAB_VIEWER_QUERY = query("query { currentUser { id username } }");
|
|
489
|
+
var isMissingExtendedStatus = (error) => /(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState).*?(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*?(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState)|Field ['"]index['"] doesn't exist on type ['"]MergeTrainCar['"]/i.test(error instanceof Error ? error.message : String(error));
|
|
490
|
+
var isMissingApprovedAt = (error) => /approvedAt.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*approvedAt/i.test(error instanceof Error ? error.message : String(error));
|
|
491
|
+
function classifyGitLabError(message, code) {
|
|
492
|
+
const text = message.trim().replace(/^glab:\s*/, "") || `glab exited with code ${code}`;
|
|
493
|
+
if (/ENOENT|command not found/i.test(text))
|
|
494
|
+
return new ForgeError("missing-glab", "glab is not installed");
|
|
495
|
+
if (/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(text)) {
|
|
496
|
+
return new ForgeError("auth", "GitLab authentication failed. Run `glab auth status`.");
|
|
497
|
+
}
|
|
498
|
+
if (/\b429\b|rate limit|too many requests/i.test(text))
|
|
499
|
+
return new ForgeError("rate-limit", "GitLab rate limit reached");
|
|
500
|
+
return new ForgeError("request", text.split(`
|
|
501
|
+
`)[0]);
|
|
502
|
+
}
|
|
503
|
+
var countUnresolved = (page) => page.nodes.filter((discussion) => discussion.resolvable && !discussion.resolved).length;
|
|
504
|
+
function requiredFailures(host, nodes) {
|
|
505
|
+
return nodes.flatMap((job) => !job.allowFailure && job.name ? [
|
|
506
|
+
{
|
|
507
|
+
...job.id ? { id: job.id } : {},
|
|
508
|
+
name: job.name,
|
|
509
|
+
...job.webPath ? { url: `https://${host}${job.webPath}` } : {},
|
|
510
|
+
...job.stage?.name ? { stage: job.stage.name } : {}
|
|
511
|
+
}
|
|
512
|
+
] : []);
|
|
513
|
+
}
|
|
514
|
+
function gitlabFailedJobs(host, pipeline) {
|
|
515
|
+
if (!pipeline.id || !pipeline.jobs)
|
|
516
|
+
return {};
|
|
517
|
+
return {
|
|
518
|
+
id: pipeline.id,
|
|
519
|
+
failedJobs: requiredFailures(host, pipeline.jobs.nodes),
|
|
520
|
+
failedJobsComplete: !pipeline.jobs.pageInfo?.hasNextPage
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
var isGitLabDuo = (reviewer, username, bot) => reviewer?.type === "DUO_CODE_REVIEW_BOT" || bot === true && username?.toLowerCase() === "gitlabduo";
|
|
524
|
+
function mergeReviewerEntry(found, entry) {
|
|
525
|
+
const lower = entry.username.toLowerCase();
|
|
526
|
+
const index = found.findIndex((existing) => entry.id && existing.id ? existing.id === entry.id : existing.username.toLowerCase() === lower && (!entry.id || !existing.id));
|
|
527
|
+
if (index < 0) {
|
|
528
|
+
found.push(entry);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
const existing = found[index];
|
|
532
|
+
found[index] = {
|
|
533
|
+
...existing,
|
|
534
|
+
...entry,
|
|
535
|
+
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
536
|
+
...existing.bot || entry.bot ? { bot: true } : {},
|
|
537
|
+
...existing.automated || entry.automated ? { automated: true } : {},
|
|
538
|
+
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function normalizeGitLabApprovers(reviewers, approvedBy) {
|
|
542
|
+
const byId = new Map;
|
|
543
|
+
const byUsername = new Map;
|
|
544
|
+
for (const reviewer of reviewers) {
|
|
545
|
+
if (reviewer.id)
|
|
546
|
+
byId.set(reviewer.id, reviewer);
|
|
547
|
+
if (reviewer.username)
|
|
548
|
+
byUsername.set(reviewer.username.toLowerCase(), reviewer);
|
|
549
|
+
}
|
|
550
|
+
const inactiveReview = (reviewer) => {
|
|
551
|
+
const state = reviewer?.mergeRequestInteraction?.reviewState;
|
|
552
|
+
return !!state && state !== "APPROVED";
|
|
553
|
+
};
|
|
554
|
+
const found = [];
|
|
555
|
+
for (const reviewer of reviewers) {
|
|
556
|
+
const interaction = reviewer.mergeRequestInteraction;
|
|
557
|
+
const approving = interaction?.reviewState === "APPROVED" || !interaction?.reviewState && interaction?.approved === true;
|
|
558
|
+
if (!approving)
|
|
559
|
+
continue;
|
|
560
|
+
const duo = isGitLabDuo(reviewer, reviewer.username, reviewer.bot);
|
|
561
|
+
const username = reviewer.username ?? (duo ? "GitLabDuo" : undefined);
|
|
562
|
+
if (!username)
|
|
563
|
+
continue;
|
|
564
|
+
const bot = reviewer.bot === true || duo;
|
|
565
|
+
mergeReviewerEntry(found, {
|
|
566
|
+
...reviewer.id ? { id: reviewer.id } : {},
|
|
567
|
+
username,
|
|
568
|
+
...bot ? { bot: true } : {},
|
|
569
|
+
...duo ? { automated: true } : {},
|
|
570
|
+
...interaction?.approvedAt ? { reviewID: interaction.approvedAt } : {}
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
for (const approver of approvedBy) {
|
|
574
|
+
const matched = (approver.id ? byId.get(approver.id) : undefined) ?? (approver.username ? byUsername.get(approver.username.toLowerCase()) : undefined);
|
|
575
|
+
if (inactiveReview(matched))
|
|
576
|
+
continue;
|
|
577
|
+
const duo = isGitLabDuo(matched, approver.username ?? matched?.username, approver.bot ?? matched?.bot);
|
|
578
|
+
const username = approver.username ?? matched?.username ?? (duo ? "GitLabDuo" : undefined);
|
|
579
|
+
if (!username)
|
|
580
|
+
continue;
|
|
581
|
+
const bot = approver.bot === true || matched?.bot === true || duo;
|
|
582
|
+
mergeReviewerEntry(found, {
|
|
583
|
+
...approver.id || matched?.id ? { id: approver.id ?? matched?.id ?? undefined } : {},
|
|
584
|
+
username,
|
|
585
|
+
...bot ? { bot: true } : {},
|
|
586
|
+
...duo ? { automated: true } : {}
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
return found;
|
|
590
|
+
}
|
|
591
|
+
function normalizeGitLabChangeRequesters(reviewers, complete) {
|
|
592
|
+
let anyRequested = false;
|
|
593
|
+
let allStatesKnown = true;
|
|
594
|
+
let allRequestersIdentified = true;
|
|
595
|
+
const found = [];
|
|
596
|
+
for (const reviewer of reviewers) {
|
|
597
|
+
const state = reviewer.mergeRequestInteraction?.reviewState;
|
|
598
|
+
if (!state) {
|
|
599
|
+
allStatesKnown = false;
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (state !== "REQUESTED_CHANGES")
|
|
603
|
+
continue;
|
|
604
|
+
anyRequested = true;
|
|
605
|
+
const duo = isGitLabDuo(reviewer, reviewer.username, reviewer.bot);
|
|
606
|
+
const username = reviewer.username ?? (duo ? "GitLabDuo" : undefined);
|
|
607
|
+
if (!username) {
|
|
608
|
+
allRequestersIdentified = false;
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
const bot = reviewer.bot === true || duo;
|
|
612
|
+
mergeReviewerEntry(found, {
|
|
613
|
+
...reviewer.id ? { id: reviewer.id } : {},
|
|
614
|
+
username,
|
|
615
|
+
...bot ? { bot: true } : {},
|
|
616
|
+
...duo ? { automated: true } : {}
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
const allComplete = complete && allStatesKnown && allRequestersIdentified;
|
|
620
|
+
let changesRequested;
|
|
621
|
+
if (anyRequested)
|
|
622
|
+
changesRequested = true;
|
|
623
|
+
else if (complete && allStatesKnown)
|
|
624
|
+
changesRequested = false;
|
|
625
|
+
return {
|
|
626
|
+
...changesRequested === undefined ? {} : { changesRequested },
|
|
627
|
+
...found.length > 0 || allComplete ? { changeRequesters: found } : {},
|
|
628
|
+
changeRequestersComplete: allComplete
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function createGitLabSource(transport, options = {}) {
|
|
632
|
+
const graphql = typed(transport);
|
|
633
|
+
const unsupportedApprovedAt = options.unsupportedApprovedAt ?? new Set;
|
|
634
|
+
const unsupportedExtendedStatus = options.unsupportedExtendedStatus ?? new Set;
|
|
635
|
+
async function queryWithApprovedAt(host, build, variables) {
|
|
636
|
+
if (unsupportedApprovedAt.has(host)) {
|
|
637
|
+
return graphql(host, build(false), variables);
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
return await graphql(host, build(true), variables);
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (!isMissingApprovedAt(error))
|
|
643
|
+
throw error;
|
|
644
|
+
unsupportedApprovedAt.add(host);
|
|
645
|
+
return graphql(host, build(false), variables);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
async function queryStatus(host, build, variables) {
|
|
649
|
+
const run = (extended) => queryWithApprovedAt(host, (approvedAt) => build(approvedAt, extended), variables);
|
|
650
|
+
if (unsupportedExtendedStatus.has(host))
|
|
651
|
+
return run(false);
|
|
652
|
+
try {
|
|
653
|
+
return await run(true);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
if (!isMissingExtendedStatus(error))
|
|
656
|
+
throw error;
|
|
657
|
+
unsupportedExtendedStatus.add(host);
|
|
658
|
+
return run(false);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
async function discussionRequirement(host, node) {
|
|
662
|
+
if (node.detailedMergeStatus === "DISCUSSIONS_NOT_RESOLVED")
|
|
663
|
+
return true;
|
|
664
|
+
const data = await graphql(host, query(`query($project: ID!) { project(fullPath: $project) { onlyAllowMergeIfAllDiscussionsAreResolved } }`), { project: node.targetProject.fullPath }).catch(() => {
|
|
665
|
+
return;
|
|
666
|
+
});
|
|
667
|
+
return data?.project?.onlyAllowMergeIfAllDiscussionsAreResolved ?? undefined;
|
|
668
|
+
}
|
|
669
|
+
async function unresolvedThreads(host, node) {
|
|
670
|
+
let count = countUnresolved(node.discussions);
|
|
671
|
+
let page = node.discussions.pageInfo;
|
|
672
|
+
let pages = 1;
|
|
673
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
674
|
+
const data = await graphql(host, DISCUSSIONS_QUERY, {
|
|
675
|
+
project: node.targetProject.fullPath,
|
|
676
|
+
iid: node.iid,
|
|
677
|
+
after: page.endCursor
|
|
678
|
+
});
|
|
679
|
+
const next = data.project?.mergeRequest?.discussions;
|
|
680
|
+
if (!next)
|
|
681
|
+
break;
|
|
682
|
+
count += countUnresolved(next);
|
|
683
|
+
page = next.pageInfo;
|
|
684
|
+
pages++;
|
|
685
|
+
}
|
|
686
|
+
return { count, complete: !page.hasNextPage };
|
|
687
|
+
}
|
|
688
|
+
async function allReviewers(host, node) {
|
|
689
|
+
if (!node.reviewers?.pageInfo)
|
|
690
|
+
return { nodes: [...node.reviewers?.nodes ?? []], complete: false };
|
|
691
|
+
const nodes = [...node.reviewers.nodes];
|
|
692
|
+
let page = node.reviewers.pageInfo;
|
|
693
|
+
let pages = 1;
|
|
694
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
695
|
+
const data = await queryWithApprovedAt(host, (includeApprovedAt) => reviewersQuery(includeApprovedAt), {
|
|
696
|
+
project: node.targetProject.fullPath,
|
|
697
|
+
iid: node.iid,
|
|
698
|
+
after: page.endCursor
|
|
699
|
+
});
|
|
700
|
+
const next = data.project?.mergeRequest?.reviewers;
|
|
701
|
+
if (!next?.pageInfo)
|
|
702
|
+
return { nodes, complete: false };
|
|
703
|
+
nodes.push(...next.nodes);
|
|
704
|
+
page = next.pageInfo;
|
|
705
|
+
pages++;
|
|
706
|
+
}
|
|
707
|
+
return { nodes, complete: !page.hasNextPage };
|
|
708
|
+
}
|
|
709
|
+
async function allApprovedBy(host, node) {
|
|
710
|
+
if (!node.approvedBy?.pageInfo)
|
|
711
|
+
return { nodes: [...node.approvedBy?.nodes ?? []], complete: false };
|
|
712
|
+
const nodes = [...node.approvedBy.nodes];
|
|
713
|
+
let page = node.approvedBy.pageInfo;
|
|
714
|
+
let pages = 1;
|
|
715
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
716
|
+
const data = await graphql(host, APPROVED_BY_QUERY, {
|
|
717
|
+
project: node.targetProject.fullPath,
|
|
718
|
+
iid: node.iid,
|
|
719
|
+
after: page.endCursor
|
|
720
|
+
});
|
|
721
|
+
const next = data.project?.mergeRequest?.approvedBy;
|
|
722
|
+
if (!next?.pageInfo)
|
|
723
|
+
return { nodes, complete: false };
|
|
724
|
+
nodes.push(...next.nodes);
|
|
725
|
+
page = next.pageInfo;
|
|
726
|
+
pages++;
|
|
727
|
+
}
|
|
728
|
+
return { nodes, complete: !page.hasNextPage };
|
|
729
|
+
}
|
|
730
|
+
async function normalize(host, node) {
|
|
731
|
+
const [threads, reviewersPage, approvedByPage] = await Promise.all([
|
|
732
|
+
unresolvedThreads(host, node),
|
|
733
|
+
allReviewers(host, node),
|
|
734
|
+
allApprovedBy(host, node)
|
|
735
|
+
]);
|
|
736
|
+
const pipeline = node.headPipeline;
|
|
737
|
+
const discussionResolutionRequired = threads.count > 0 ? await discussionRequirement(host, node) : undefined;
|
|
738
|
+
const hasApprovals = approvedByPage.nodes.some((approver) => approver.bot !== true);
|
|
739
|
+
const unapproved = reviewersPage.nodes.filter((reviewer) => reviewer.bot !== true && reviewer.username && reviewer.mergeRequestInteraction?.approved !== true);
|
|
740
|
+
const pendingHumans = unapproved.filter((reviewer) => reviewer.mergeRequestInteraction?.reviewState !== "REQUESTED_CHANGES");
|
|
741
|
+
const awaitingReviewers = pendingHumans.map((reviewer) => reviewer.username);
|
|
742
|
+
const pendingHumanReviewers = pendingHumans.map((reviewer) => ({
|
|
743
|
+
...reviewer.id ? { id: reviewer.id } : {},
|
|
744
|
+
username: reviewer.username
|
|
745
|
+
}));
|
|
746
|
+
const approvers = normalizeGitLabApprovers(reviewersPage.nodes, approvedByPage.nodes);
|
|
747
|
+
const approvedNames = new Set([...approvedByPage.nodes, ...approvers].flatMap(({ username }) => username ? [username.toLowerCase()] : []));
|
|
748
|
+
const missingRules = (node.approvalState?.rules ?? []).flatMap((rule) => {
|
|
749
|
+
if (rule.approvalsRequired == null || rule.approvalsRequired <= 0 || rule.approved !== false)
|
|
750
|
+
return [];
|
|
751
|
+
const eligible = (rule.eligibleApprovers ?? []).filter(({ username, bot }) => !bot && !approvedNames.has(username.toLowerCase()));
|
|
752
|
+
const eligibleNames = new Set(eligible.map(({ username }) => username.toLowerCase()));
|
|
753
|
+
const humans = eligible.filter(({ type }) => type === "HUMAN");
|
|
754
|
+
const humanNames = new Set(humans.map(({ username }) => username.toLowerCase()));
|
|
755
|
+
const eligibleReviewers = unapproved.map((reviewer) => reviewer.username).filter((username) => eligibleNames.has(username.toLowerCase())).sort((a, b) => Number(humanNames.has(b.toLowerCase())) - Number(humanNames.has(a.toLowerCase())));
|
|
756
|
+
const candidates = humans.length ? humans : eligible;
|
|
757
|
+
return [
|
|
758
|
+
{
|
|
759
|
+
name: rule.name ?? "Unnamed approval rule",
|
|
760
|
+
type: rule.type ?? undefined,
|
|
761
|
+
required: rule.approvalsRequired,
|
|
762
|
+
eligibleReviewers,
|
|
763
|
+
eligible: candidates.slice(0, 2).map(({ username }) => username),
|
|
764
|
+
eligibleCount: candidates.length
|
|
765
|
+
}
|
|
766
|
+
];
|
|
767
|
+
});
|
|
768
|
+
const request = {
|
|
769
|
+
forge: "gitlab",
|
|
770
|
+
iid: node.iid,
|
|
771
|
+
title: node.title,
|
|
772
|
+
url: node.webUrl,
|
|
773
|
+
state: node.state.toLowerCase(),
|
|
774
|
+
draft: node.draft,
|
|
775
|
+
conflicts: node.conflicts || node.mergeStatusEnum === CONFLICT_RECHECK,
|
|
776
|
+
conflictsKnown: node.mergeStatusEnum !== CONFLICT_RECHECK && !RECHECKING.has(node.detailedMergeStatus ?? ""),
|
|
777
|
+
approved: node.approved === true && hasApprovals && unapproved.length === 0,
|
|
778
|
+
hasApprovals,
|
|
779
|
+
approvalRequirementsSatisfied: node.approved,
|
|
780
|
+
discussionResolutionRequired,
|
|
781
|
+
approvalsRequired: node.approvalsRequired ?? undefined,
|
|
782
|
+
approvalsLeft: node.approvalsLeft ?? undefined,
|
|
783
|
+
missingRules,
|
|
784
|
+
autoMergeEnabled: node.autoMergeEnabled,
|
|
785
|
+
mergeTrainIndex: node.mergeTrainCar?.index,
|
|
786
|
+
awaitingReviewers,
|
|
787
|
+
pendingHumanReviewers,
|
|
788
|
+
reviewersComplete: reviewersPage.complete,
|
|
789
|
+
...normalizeGitLabChangeRequesters(reviewersPage.nodes, reviewersPage.complete),
|
|
790
|
+
approvalsComplete: reviewersPage.complete && approvedByPage.complete,
|
|
791
|
+
reviewerIDs: reviewersPage.nodes.flatMap((reviewer) => reviewer.id ?? []),
|
|
792
|
+
approvers,
|
|
793
|
+
mergeStatus: node.detailedMergeStatus ?? undefined,
|
|
794
|
+
targetProject: node.targetProject.fullPath,
|
|
795
|
+
targetBranch: node.targetBranch,
|
|
796
|
+
...node.sourceProject ? { sourceProject: node.sourceProject.fullPath } : {},
|
|
797
|
+
sourceBranch: node.sourceBranch,
|
|
798
|
+
headSha: node.diffHeadSha ?? undefined,
|
|
799
|
+
...node.author?.id ? { authorID: node.author.id } : {},
|
|
800
|
+
...node.author?.username ? { authorUsername: node.author.username } : {},
|
|
801
|
+
updatedAt: node.updatedAt ?? undefined,
|
|
802
|
+
pipeline: pipeline ? {
|
|
803
|
+
status: pipeline.status,
|
|
804
|
+
label: pipeline.detailedStatus?.label ?? pipeline.status.toLowerCase().replace(/_/g, " "),
|
|
805
|
+
url: pipeline.path ? `https://${host}${pipeline.path}` : undefined,
|
|
806
|
+
...gitlabFailedJobs(host, pipeline)
|
|
807
|
+
} : undefined,
|
|
808
|
+
unresolvedThreads: threads.count,
|
|
809
|
+
threadsComplete: threads.complete,
|
|
810
|
+
duoReviewState: reviewersPage.nodes.find((reviewer) => reviewer.type === "DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState ?? undefined
|
|
811
|
+
};
|
|
812
|
+
if (autoMergeCandidate(request) === true && request.headSha) {
|
|
813
|
+
const data = await graphql(host, query(`query($project: ID!, $iid: String!) {
|
|
814
|
+
project(fullPath: $project) { mergeRequest(iid: $iid) {
|
|
815
|
+
diffHeadSha autoMergeEnabled detailedMergeStatus userPermissions { canMerge }
|
|
816
|
+
availableAutoMergeStrategies
|
|
817
|
+
} }
|
|
818
|
+
}`), { project: request.targetProject, iid: request.iid }).catch(() => {
|
|
819
|
+
return;
|
|
820
|
+
});
|
|
821
|
+
const live = data?.project?.mergeRequest;
|
|
822
|
+
if (live?.diffHeadSha === request.headSha && live.autoMergeEnabled === false && live.detailedMergeStatus === request.mergeStatus) {
|
|
823
|
+
if (typeof live.userPermissions?.canMerge === "boolean") {
|
|
824
|
+
request.canMerge = live.userPermissions.canMerge;
|
|
825
|
+
}
|
|
826
|
+
if (live.userPermissions?.canMerge === false)
|
|
827
|
+
request.autoMergeAvailable = false;
|
|
828
|
+
else if (live.userPermissions?.canMerge === true && Array.isArray(live.availableAutoMergeStrategies))
|
|
829
|
+
request.autoMergeAvailable = live.availableAutoMergeStrategies.length > 0;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
return request;
|
|
833
|
+
}
|
|
834
|
+
async function discussion(ref, { id, anchor }) {
|
|
835
|
+
if (!anchor)
|
|
836
|
+
return;
|
|
837
|
+
let resolved = false;
|
|
838
|
+
let owned = false;
|
|
839
|
+
const replies = await discussionPages(10, async (after) => {
|
|
840
|
+
const data = await graphql(ref.host, DISCUSSION_BY_NOTE, {
|
|
841
|
+
note: anchor,
|
|
842
|
+
...after ? { after } : {}
|
|
843
|
+
});
|
|
844
|
+
const thread = data.note?.discussion;
|
|
845
|
+
const owner = thread?.noteable?.webUrl && parseGitLabUrl(thread.noteable.webUrl);
|
|
846
|
+
owned = Boolean(thread?.id === id && owner && owner.host === ref.host && owner.project === ref.project && owner.iid === ref.iid);
|
|
847
|
+
if (!owned || !thread)
|
|
848
|
+
return;
|
|
849
|
+
resolved = thread.resolved;
|
|
850
|
+
return resolved || !thread.resolvable ? undefined : thread.notes;
|
|
851
|
+
});
|
|
852
|
+
if (!owned)
|
|
853
|
+
return;
|
|
854
|
+
if (resolved)
|
|
855
|
+
return "resolved";
|
|
856
|
+
const notes = [];
|
|
857
|
+
let incomplete = !replies.complete;
|
|
858
|
+
for (const note of replies.nodes) {
|
|
859
|
+
if (note.system)
|
|
860
|
+
continue;
|
|
861
|
+
if (!note.id || !note.author?.username || typeof note.body !== "string") {
|
|
862
|
+
incomplete = true;
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
notes.push({
|
|
866
|
+
id: note.id.slice(note.id.lastIndexOf("/") + 1),
|
|
867
|
+
url: note.url ?? undefined,
|
|
868
|
+
authorID: note.author.id,
|
|
869
|
+
username: note.author.username,
|
|
870
|
+
bot: note.author.bot === true,
|
|
871
|
+
body: note.body,
|
|
872
|
+
createdAt: note.createdAt ?? undefined,
|
|
873
|
+
path: note.position?.newPath ?? note.position?.oldPath ?? undefined,
|
|
874
|
+
line: note.position?.newLine ?? note.position?.oldLine ?? undefined
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
return {
|
|
878
|
+
id,
|
|
879
|
+
anchor,
|
|
880
|
+
notes,
|
|
881
|
+
url: notes.find((note) => note.url)?.url,
|
|
882
|
+
incomplete: incomplete || notes.length === 0
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
async function unresolvedDiscussions(ref) {
|
|
886
|
+
const list = await discussionPages(MAX_DISCUSSION_PAGES, async (after) => {
|
|
887
|
+
const data = await graphql(ref.host, UNRESOLVED_DISCUSSIONS_QUERY, {
|
|
888
|
+
project: ref.project,
|
|
889
|
+
iid: ref.iid,
|
|
890
|
+
...after ? { after } : {}
|
|
891
|
+
});
|
|
892
|
+
return data.project?.mergeRequest?.discussions;
|
|
893
|
+
});
|
|
894
|
+
const discussions = [];
|
|
895
|
+
const candidates = list.nodes.filter(({ id, resolvable, resolved }) => id && resolvable && !resolved);
|
|
896
|
+
for (const node of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
897
|
+
const noteID = node.notes?.nodes[0]?.id?.match(/^gid:\/\/gitlab\/\w+\/(\d+)$/)?.[1];
|
|
898
|
+
const anchor = noteID ? `gid://gitlab/Note/${noteID}` : undefined;
|
|
899
|
+
const thread = await discussion(ref, { id: node.id, anchor }).catch(() => {
|
|
900
|
+
return;
|
|
901
|
+
});
|
|
902
|
+
if (thread !== "resolved")
|
|
903
|
+
discussions.push(thread ?? { id: node.id, notes: [], incomplete: true });
|
|
904
|
+
}
|
|
905
|
+
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
906
|
+
}
|
|
907
|
+
async function fetchByProjects(projects, iid) {
|
|
908
|
+
if (projects.length === 0)
|
|
909
|
+
return;
|
|
910
|
+
const host = projects[0].host;
|
|
911
|
+
const variables = { iid };
|
|
912
|
+
projects.forEach((project, index) => variables[`p${index}`] = project.path);
|
|
913
|
+
const data = await queryStatus(host, (approvedAt, extended) => mergeRequestQuery(projects.length, approvedAt, extended), variables);
|
|
914
|
+
for (let index = 0;index < projects.length; index++) {
|
|
915
|
+
const node = data[`p${index}`]?.mergeRequest;
|
|
916
|
+
if (node)
|
|
917
|
+
return normalize(host, node);
|
|
918
|
+
}
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
async function fetchByBranch(source, targets, sourceBranch) {
|
|
922
|
+
if (targets.length === 0)
|
|
923
|
+
return [];
|
|
924
|
+
const variables = { branch: sourceBranch };
|
|
925
|
+
targets.forEach((target, index) => variables[`p${index}`] = target.path);
|
|
926
|
+
const data = await queryStatus(source.host, (approvedAt, extended) => mergeRequestsQuery(targets.length, approvedAt, extended), variables);
|
|
927
|
+
const sourcePath = source.path.toLowerCase();
|
|
928
|
+
const seen = new Set;
|
|
929
|
+
const nodes = [];
|
|
930
|
+
targets.forEach((_, index) => {
|
|
931
|
+
for (const node of data[`p${index}`]?.mergeRequests?.nodes ?? []) {
|
|
932
|
+
if (node.sourceProject?.fullPath.toLowerCase() !== sourcePath)
|
|
933
|
+
continue;
|
|
934
|
+
const key = `${node.targetProject.fullPath}!${node.iid}`;
|
|
935
|
+
if (seen.has(key))
|
|
936
|
+
continue;
|
|
937
|
+
seen.add(key);
|
|
938
|
+
nodes.push(node);
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
const requests = await Promise.all(nodes.map((node) => normalize(source.host, node)));
|
|
942
|
+
return requests.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
943
|
+
}
|
|
944
|
+
async function viewer(host) {
|
|
945
|
+
const data = await graphql(host, GITLAB_VIEWER_QUERY, {});
|
|
946
|
+
const user = data.currentUser;
|
|
947
|
+
if (!user?.id && !user?.username)
|
|
948
|
+
return;
|
|
949
|
+
return {
|
|
950
|
+
...user.id ? { id: user.id } : {},
|
|
951
|
+
...user.username ? { username: user.username } : {}
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
return {
|
|
955
|
+
forge: "gitlab",
|
|
956
|
+
fetchRequest: (ref) => fetchByProjects([{ host: ref.host, path: ref.project }], ref.iid),
|
|
957
|
+
fetchByProjects,
|
|
958
|
+
fetchByBranch,
|
|
959
|
+
unresolvedDiscussions,
|
|
960
|
+
discussion,
|
|
961
|
+
viewer
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
var COPILOT_AUTHOR = "copilot-pull-request-reviewer[bot]";
|
|
965
|
+
var GITHUB_MAX_PAGES = 50;
|
|
966
|
+
var githubPullFields = (includeAutoMerge) => `number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
967
|
+
${includeAutoMerge ? "autoMergeRequest { enabledAt }" : ""}
|
|
968
|
+
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
969
|
+
author { login ... on User { id } ... on Bot { id } }
|
|
970
|
+
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
971
|
+
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
972
|
+
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
973
|
+
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
974
|
+
copilotReviews: reviews(last:1, author:"${COPILOT_AUTHOR}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } author { __typename login ... on Bot { id } ... on User { id } } } }
|
|
975
|
+
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
976
|
+
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
977
|
+
pageInfo { hasNextPage endCursor }
|
|
978
|
+
} } } } }`;
|
|
979
|
+
var isMissingAutoMerge = (error) => /autoMergeRequest.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*autoMergeRequest/i.test(error instanceof Error ? error.message : String(error));
|
|
980
|
+
var GITHUB_VIEWER_QUERY = query("query { viewer { id login } }");
|
|
981
|
+
function classifyGitHubError(message, code) {
|
|
982
|
+
const text = message.trim() || `gh exited with code ${code}`;
|
|
983
|
+
if (/ENOENT|command not found/i.test(text))
|
|
984
|
+
return new ForgeError("missing-gh", "gh is not installed");
|
|
985
|
+
if (/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(text))
|
|
986
|
+
return new ForgeError("auth", "GitHub authentication failed. Run `gh auth status`.");
|
|
987
|
+
if (/429|rate limit|too many requests/i.test(text))
|
|
988
|
+
return new ForgeError("rate-limit", "GitHub rate limit reached");
|
|
989
|
+
return new ForgeError("request", text.split(`
|
|
990
|
+
`)[0]);
|
|
991
|
+
}
|
|
992
|
+
var FAILED_CHECKS = ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"];
|
|
993
|
+
var CHECK_CONCLUSIONS = [
|
|
994
|
+
"SUCCESS",
|
|
995
|
+
"NEUTRAL",
|
|
996
|
+
"SKIPPED",
|
|
997
|
+
"FAILURE",
|
|
998
|
+
"TIMED_OUT",
|
|
999
|
+
"CANCELLED",
|
|
1000
|
+
"ACTION_REQUIRED",
|
|
1001
|
+
"STARTUP_FAILURE",
|
|
1002
|
+
"STALE"
|
|
1003
|
+
];
|
|
1004
|
+
var CHECK_STATES = ["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED"];
|
|
1005
|
+
var checkKey = (node) => node.__typename === "CheckRun" && node.name && node.checkSuite?.app?.id && node.checkSuite.workflowRun?.workflow?.id && JSON.stringify([node.checkSuite.app.id, node.checkSuite.workflowRun?.workflow?.id, node.name]);
|
|
1006
|
+
var checkTime = (node) => Date.parse(node.checkSuite?.createdAt ?? "");
|
|
1007
|
+
var newerCheck = (node, previous) => checkTime(node) > checkTime(previous);
|
|
1008
|
+
function checks(nodes, complete, url, id) {
|
|
1009
|
+
const latest = new Map;
|
|
1010
|
+
for (const node of nodes) {
|
|
1011
|
+
const time = checkTime(node);
|
|
1012
|
+
const key = checkKey(node);
|
|
1013
|
+
if (!key || !Number.isFinite(time))
|
|
1014
|
+
continue;
|
|
1015
|
+
const previous = latest.get(key);
|
|
1016
|
+
if (!previous || newerCheck(node, previous))
|
|
1017
|
+
latest.set(key, node);
|
|
1018
|
+
}
|
|
1019
|
+
nodes = nodes.filter((node) => {
|
|
1020
|
+
const key = checkKey(node);
|
|
1021
|
+
const replacement = key && latest.get(key);
|
|
1022
|
+
return !replacement || !newerCheck(replacement, node);
|
|
1023
|
+
});
|
|
1024
|
+
const count = (value) => `${value} check${value === 1 ? "" : "s"}`;
|
|
1025
|
+
const cancelled = nodes.filter((node) => node.conclusion === "CANCELLED").length;
|
|
1026
|
+
const stale = nodes.filter((node) => node.conclusion === "STALE").length;
|
|
1027
|
+
const stopped = [
|
|
1028
|
+
...cancelled ? [`${count(cancelled)} cancelled`] : [],
|
|
1029
|
+
...stale ? [`${count(stale)} stale`] : []
|
|
1030
|
+
];
|
|
1031
|
+
const failing = nodes.filter((node) => FAILED_CHECKS.includes(node.conclusion ?? node.state ?? ""));
|
|
1032
|
+
const failed = failing.length;
|
|
1033
|
+
const run = id ? {
|
|
1034
|
+
id,
|
|
1035
|
+
failedJobs: failing.flatMap((node) => {
|
|
1036
|
+
const name = node.name ?? node.context;
|
|
1037
|
+
const link = node.detailsUrl ?? node.targetUrl;
|
|
1038
|
+
return name ? [{ ...node.id ? { id: node.id } : {}, name, ...link ? { url: link } : {} }] : [];
|
|
1039
|
+
}),
|
|
1040
|
+
failedJobsComplete: complete
|
|
1041
|
+
} : {};
|
|
1042
|
+
const pending = nodes.filter((node) => node.status ? node.status !== "COMPLETED" : ["PENDING", "EXPECTED"].includes(node.state ?? "")).length;
|
|
1043
|
+
const unknown = nodes.some((node) => node.status === "COMPLETED" ? !CHECK_CONCLUSIONS.includes(node.conclusion ?? "") : !node.status && !CHECK_STATES.includes(node.state ?? ""));
|
|
1044
|
+
if (failed)
|
|
1045
|
+
return {
|
|
1046
|
+
status: "FAILED",
|
|
1047
|
+
label: [
|
|
1048
|
+
`${count(failed)} failed`,
|
|
1049
|
+
...stopped,
|
|
1050
|
+
...pending ? [`${count(pending)} pending`] : []
|
|
1051
|
+
].join(", ") + (complete ? "" : " (partial)"),
|
|
1052
|
+
url,
|
|
1053
|
+
...run,
|
|
1054
|
+
running: pending > 0
|
|
1055
|
+
};
|
|
1056
|
+
if (pending || !complete || unknown)
|
|
1057
|
+
return {
|
|
1058
|
+
status: "PENDING",
|
|
1059
|
+
label: [...stopped, pending ? `${count(pending)} pending` : "unknown"].join(", ") + (complete ? "" : " (partial)"),
|
|
1060
|
+
url,
|
|
1061
|
+
...run
|
|
1062
|
+
};
|
|
1063
|
+
if (cancelled || stale)
|
|
1064
|
+
return { status: "CANCELLED", label: stopped.join(", "), url, ...run };
|
|
1065
|
+
const label = [
|
|
1066
|
+
["SUCCESS", "passed"],
|
|
1067
|
+
["SKIPPED", "skipped"],
|
|
1068
|
+
["NEUTRAL", "neutral"]
|
|
1069
|
+
].flatMap(([result, text]) => {
|
|
1070
|
+
const total = nodes.filter((node) => (node.conclusion ?? node.state) === result).length;
|
|
1071
|
+
return total ? [`${count(total)} ${text}`] : [];
|
|
1072
|
+
}).join(", ");
|
|
1073
|
+
return { status: "SUCCESS", label: label || "0 checks", url, ...run };
|
|
1074
|
+
}
|
|
1075
|
+
var isCopilotReviewer = (login) => /^copilot-pull-request-reviewer(\[bot\])?$/i.test(login ?? "");
|
|
1076
|
+
var isCopilotBot = (reviewer) => reviewer?.__typename === "Bot" && isCopilotReviewer(reviewer.login);
|
|
1077
|
+
function botUsername(login, typename) {
|
|
1078
|
+
return typename === "Bot" && !login.endsWith("[bot]") ? `${login}[bot]` : login;
|
|
1079
|
+
}
|
|
1080
|
+
function copilotReview(node) {
|
|
1081
|
+
const requested = node.reviewRequests.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
1082
|
+
const latest = node.copilotReviews?.nodes?.find((review) => review);
|
|
1083
|
+
if (!requested && !latest)
|
|
1084
|
+
return;
|
|
1085
|
+
return {
|
|
1086
|
+
requested,
|
|
1087
|
+
reviewID: latest?.id,
|
|
1088
|
+
comments: latest?.comments.totalCount ?? 0,
|
|
1089
|
+
...latest?.state === "DISMISSED" ? { dismissed: true } : {}
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
function pendingReviewer(reviewers) {
|
|
1093
|
+
const pendingIDs = new Set;
|
|
1094
|
+
const pendingWithoutID = new Set;
|
|
1095
|
+
const pendingTypedLogins = new Set;
|
|
1096
|
+
const typedLoginKey = (typename, login) => `${typename ?? "Unknown"}:${botUsername(login, typename).toLowerCase()}`;
|
|
1097
|
+
for (const request of reviewers.nodes) {
|
|
1098
|
+
const reviewer = request.requestedReviewer;
|
|
1099
|
+
if (reviewer?.id)
|
|
1100
|
+
pendingIDs.add(reviewer.id);
|
|
1101
|
+
if (reviewer?.login) {
|
|
1102
|
+
const key = typedLoginKey(reviewer.__typename, reviewer.login);
|
|
1103
|
+
pendingTypedLogins.add(key);
|
|
1104
|
+
if (!reviewer.id)
|
|
1105
|
+
pendingWithoutID.add(key);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return (id, typename, login) => {
|
|
1109
|
+
const key = typedLoginKey(typename, login);
|
|
1110
|
+
if (id)
|
|
1111
|
+
return pendingIDs.has(id) || pendingWithoutID.has(key);
|
|
1112
|
+
return pendingTypedLogins.has(key);
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
function normalizeGitHubApprovers(node, reviewers, opinionated) {
|
|
1116
|
+
const isPending = pendingReviewer(reviewers);
|
|
1117
|
+
const found = new Map;
|
|
1118
|
+
const add = (entry) => {
|
|
1119
|
+
const key = `${entry.bot ? "bot" : "user"}:${entry.username.toLowerCase()}`;
|
|
1120
|
+
const existing = found.get(key);
|
|
1121
|
+
if (!existing) {
|
|
1122
|
+
found.set(key, entry);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
found.set(key, {
|
|
1126
|
+
...existing,
|
|
1127
|
+
...entry,
|
|
1128
|
+
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
1129
|
+
...existing.bot || entry.bot ? { bot: true } : {},
|
|
1130
|
+
...existing.automated || entry.automated ? { automated: true } : {},
|
|
1131
|
+
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
1132
|
+
});
|
|
1133
|
+
};
|
|
1134
|
+
for (const review of opinionated) {
|
|
1135
|
+
if (review?.state !== "APPROVED" || !review.author?.login)
|
|
1136
|
+
continue;
|
|
1137
|
+
const { id, login, __typename } = review.author;
|
|
1138
|
+
if (isPending(id, __typename, login))
|
|
1139
|
+
continue;
|
|
1140
|
+
const bot = __typename === "Bot";
|
|
1141
|
+
const automated = bot && isCopilotReviewer(login);
|
|
1142
|
+
const username = automated ? COPILOT_AUTHOR : botUsername(login, __typename);
|
|
1143
|
+
add({
|
|
1144
|
+
...id ? { id } : {},
|
|
1145
|
+
username,
|
|
1146
|
+
...bot ? { bot: true } : {},
|
|
1147
|
+
...automated ? { automated: true } : {},
|
|
1148
|
+
...review.id ? { reviewID: review.id } : {}
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
const latestCopilot = node.copilotReviews?.nodes?.find((review) => review);
|
|
1152
|
+
const copilotPending = reviewers.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
1153
|
+
if (latestCopilot?.state === "APPROVED" && isCopilotBot(latestCopilot.author) && !copilotPending) {
|
|
1154
|
+
add({
|
|
1155
|
+
...latestCopilot.author?.id ? { id: latestCopilot.author.id } : {},
|
|
1156
|
+
username: COPILOT_AUTHOR,
|
|
1157
|
+
bot: true,
|
|
1158
|
+
automated: true,
|
|
1159
|
+
...latestCopilot.id ? { reviewID: latestCopilot.id } : {}
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
return [...found.values()];
|
|
1163
|
+
}
|
|
1164
|
+
function changeRequests(reviewers, opinionated) {
|
|
1165
|
+
if (!reviewers.pageInfo || reviewers.pageInfo.hasNextPage) {
|
|
1166
|
+
return { changeRequestersComplete: false };
|
|
1167
|
+
}
|
|
1168
|
+
const pending = pendingReviewer(reviewers);
|
|
1169
|
+
const ids = [];
|
|
1170
|
+
const found = new Map;
|
|
1171
|
+
let complete = opinionated.complete;
|
|
1172
|
+
for (const review of opinionated.nodes) {
|
|
1173
|
+
if (review?.state !== "CHANGES_REQUESTED")
|
|
1174
|
+
continue;
|
|
1175
|
+
const author = review.author;
|
|
1176
|
+
if (!author?.login || !review.id) {
|
|
1177
|
+
complete = false;
|
|
1178
|
+
continue;
|
|
1179
|
+
}
|
|
1180
|
+
if (pending(author.id, author.__typename, author.login))
|
|
1181
|
+
continue;
|
|
1182
|
+
ids.push(review.id);
|
|
1183
|
+
const bot = author.__typename === "Bot";
|
|
1184
|
+
const automated = bot && isCopilotReviewer(author.login);
|
|
1185
|
+
const username = automated ? COPILOT_AUTHOR : botUsername(author.login, author.__typename);
|
|
1186
|
+
const key = author.id ? `id:${author.id}` : `${bot ? "bot" : "user"}:${username.toLowerCase()}`;
|
|
1187
|
+
found.set(key, {
|
|
1188
|
+
...author.id ? { id: author.id } : {},
|
|
1189
|
+
username,
|
|
1190
|
+
...bot ? { bot: true } : {},
|
|
1191
|
+
...automated ? { automated: true } : {},
|
|
1192
|
+
reviewID: review.id
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
if (ids.length) {
|
|
1196
|
+
return {
|
|
1197
|
+
changesRequested: true,
|
|
1198
|
+
changeReviewIDs: ids,
|
|
1199
|
+
changeRequesters: [...found.values()],
|
|
1200
|
+
changeRequestersComplete: complete
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
return complete ? { changesRequested: false, changeRequesters: [], changeRequestersComplete: true } : { changeRequestersComplete: false };
|
|
1204
|
+
}
|
|
1205
|
+
function createGitHubSource(transport, options = {}) {
|
|
1206
|
+
const graphql = typed(transport);
|
|
1207
|
+
const unsupportedAutoMerge = options.unsupportedAutoMerge ?? new Set;
|
|
1208
|
+
async function queryPull(host, build, variables) {
|
|
1209
|
+
if (unsupportedAutoMerge.has(host)) {
|
|
1210
|
+
return graphql(host, build(false), variables);
|
|
1211
|
+
}
|
|
1212
|
+
try {
|
|
1213
|
+
return await graphql(host, build(true), variables);
|
|
1214
|
+
} catch (error) {
|
|
1215
|
+
if (!isMissingAutoMerge(error))
|
|
1216
|
+
throw error;
|
|
1217
|
+
unsupportedAutoMerge.add(host);
|
|
1218
|
+
return graphql(host, build(false), variables);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
async function discussionRequirement(host, node) {
|
|
1222
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1223
|
+
let after;
|
|
1224
|
+
let unknown = false;
|
|
1225
|
+
for (let page = 0;page < GITHUB_MAX_PAGES; page++) {
|
|
1226
|
+
const response = await graphql(host, query(`query($owner:String!,$repo:String!,$branch:String!,$after:String) {
|
|
1227
|
+
repository(owner:$owner,name:$repo) {
|
|
1228
|
+
ref(qualifiedName:$branch) {
|
|
1229
|
+
branchProtectionRule { requiresConversationResolution }
|
|
1230
|
+
rules(first:50,after:$after) {
|
|
1231
|
+
nodes { type repositoryRuleset { enforcement } parameters { ... on PullRequestParameters { requiredReviewThreadResolution } } }
|
|
1232
|
+
pageInfo { hasNextPage endCursor }
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}`), { owner, repo, branch: `refs/heads/${node.baseRefName}`, ...after ? { after } : {} }).catch(() => {
|
|
1237
|
+
return;
|
|
1238
|
+
});
|
|
1239
|
+
const ref = response?.repository?.ref;
|
|
1240
|
+
if (ref?.branchProtectionRule?.requiresConversationResolution)
|
|
1241
|
+
return true;
|
|
1242
|
+
const rules = ref?.rules;
|
|
1243
|
+
if (!rules?.pageInfo)
|
|
1244
|
+
return;
|
|
1245
|
+
for (const rule of rules.nodes) {
|
|
1246
|
+
if (rule.type !== "PULL_REQUEST")
|
|
1247
|
+
continue;
|
|
1248
|
+
const required = rule.parameters?.requiredReviewThreadResolution;
|
|
1249
|
+
const enforcement = rule.repositoryRuleset?.enforcement;
|
|
1250
|
+
if (enforcement === "ACTIVE" && required === true)
|
|
1251
|
+
return true;
|
|
1252
|
+
if (!enforcement || required === undefined)
|
|
1253
|
+
unknown = true;
|
|
1254
|
+
}
|
|
1255
|
+
if (!rules.pageInfo.hasNextPage)
|
|
1256
|
+
return unknown ? undefined : false;
|
|
1257
|
+
const cursor = rules.pageInfo.endCursor;
|
|
1258
|
+
if (!cursor || cursor === after)
|
|
1259
|
+
return;
|
|
1260
|
+
after = cursor;
|
|
1261
|
+
}
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
async function threads(host, node) {
|
|
1265
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1266
|
+
const items = [...node.reviewThreads.nodes];
|
|
1267
|
+
let page = node.reviewThreads.pageInfo;
|
|
1268
|
+
for (let count = 1;page?.hasNextPage && page.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1269
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1270
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1271
|
+
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
1272
|
+
} } }`), { owner, repo, number: node.number, after: page.endCursor });
|
|
1273
|
+
const next = data.repository?.pullRequest?.reviewThreads;
|
|
1274
|
+
if (!next)
|
|
1275
|
+
break;
|
|
1276
|
+
items.push(...next.nodes);
|
|
1277
|
+
page = next.pageInfo;
|
|
1278
|
+
}
|
|
1279
|
+
return {
|
|
1280
|
+
unresolved: items.filter((thread) => !thread.isResolved).length,
|
|
1281
|
+
complete: !page?.hasNextPage
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
async function contexts(host, node) {
|
|
1285
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1286
|
+
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
|
|
1287
|
+
const items = [...rollup?.nodes ?? []];
|
|
1288
|
+
let cursor = rollup?.pageInfo;
|
|
1289
|
+
for (let count = 1;cursor?.hasNextPage && cursor.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1290
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
1291
|
+
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
1292
|
+
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
1293
|
+
} } } } }`), { owner, repo, oid: node.headRefOid, after: cursor.endCursor });
|
|
1294
|
+
const next = data.repository?.object?.statusCheckRollup?.contexts;
|
|
1295
|
+
if (!next)
|
|
1296
|
+
break;
|
|
1297
|
+
items.push(...next.nodes);
|
|
1298
|
+
cursor = next.pageInfo;
|
|
1299
|
+
}
|
|
1300
|
+
return { nodes: items, complete: !cursor?.hasNextPage };
|
|
1301
|
+
}
|
|
1302
|
+
async function reviewers(host, node) {
|
|
1303
|
+
const nodes = [...node.reviewRequests.nodes];
|
|
1304
|
+
let reviewerPage = node.reviewRequests.pageInfo;
|
|
1305
|
+
for (let count = 1;reviewerPage?.hasNextPage && count < GITHUB_MAX_PAGES; count++) {
|
|
1306
|
+
if (!reviewerPage.endCursor) {
|
|
1307
|
+
return { nodes, pageInfo: { hasNextPage: true } };
|
|
1308
|
+
}
|
|
1309
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1310
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1311
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1312
|
+
reviewRequests(first:100,after:$after) {
|
|
1313
|
+
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
1314
|
+
pageInfo { hasNextPage endCursor }
|
|
1315
|
+
}
|
|
1316
|
+
} }
|
|
1317
|
+
}`), { owner, repo, number: node.number, after: reviewerPage.endCursor });
|
|
1318
|
+
const next = data.repository?.pullRequest?.reviewRequests;
|
|
1319
|
+
if (!next)
|
|
1320
|
+
return { nodes, pageInfo: { hasNextPage: true } };
|
|
1321
|
+
nodes.push(...next.nodes);
|
|
1322
|
+
reviewerPage = next.pageInfo;
|
|
1323
|
+
}
|
|
1324
|
+
return { nodes, pageInfo: reviewerPage };
|
|
1325
|
+
}
|
|
1326
|
+
async function opinionatedReviews(host, node) {
|
|
1327
|
+
if (!node.latestOpinionatedReviews?.pageInfo)
|
|
1328
|
+
return { nodes: [...node.latestOpinionatedReviews?.nodes ?? []], complete: false };
|
|
1329
|
+
const nodes = [...node.latestOpinionatedReviews.nodes];
|
|
1330
|
+
let page = node.latestOpinionatedReviews.pageInfo;
|
|
1331
|
+
for (let count = 1;page.hasNextPage && page.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1332
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1333
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1334
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1335
|
+
latestOpinionatedReviews(first:100,after:$after) {
|
|
1336
|
+
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
1337
|
+
pageInfo { hasNextPage endCursor }
|
|
1338
|
+
}
|
|
1339
|
+
} }
|
|
1340
|
+
}`), { owner, repo, number: node.number, after: page.endCursor });
|
|
1341
|
+
const next = data.repository?.pullRequest?.latestOpinionatedReviews;
|
|
1342
|
+
if (!next?.pageInfo)
|
|
1343
|
+
return { nodes, complete: false };
|
|
1344
|
+
nodes.push(...next.nodes);
|
|
1345
|
+
page = next.pageInfo;
|
|
1346
|
+
}
|
|
1347
|
+
return { nodes, complete: !page.hasNextPage };
|
|
1348
|
+
}
|
|
1349
|
+
async function normalize(host, node) {
|
|
1350
|
+
const reviewerList = await reviewers(host, node);
|
|
1351
|
+
const [threadData, contextData, opinionated] = await Promise.all([
|
|
1352
|
+
threads(host, node),
|
|
1353
|
+
contexts(host, node),
|
|
1354
|
+
opinionatedReviews(host, node)
|
|
1355
|
+
]);
|
|
1356
|
+
const changes = changeRequests(reviewerList, opinionated);
|
|
1357
|
+
const awaitingReviewers = reviewerList.nodes.flatMap((request) => {
|
|
1358
|
+
const reviewer = request.requestedReviewer;
|
|
1359
|
+
if (reviewer?.__typename === "Bot")
|
|
1360
|
+
return [];
|
|
1361
|
+
const name = reviewer?.login || reviewer?.name;
|
|
1362
|
+
return name ? [name] : [];
|
|
1363
|
+
});
|
|
1364
|
+
const pendingHumanReviewers = reviewerList.nodes.flatMap((request) => {
|
|
1365
|
+
const reviewer = request.requestedReviewer;
|
|
1366
|
+
if (reviewer?.__typename !== "User" || !reviewer.login)
|
|
1367
|
+
return [];
|
|
1368
|
+
return [{ ...reviewer.id ? { id: reviewer.id } : {}, username: reviewer.login }];
|
|
1369
|
+
});
|
|
1370
|
+
return {
|
|
1371
|
+
forge: "github",
|
|
1372
|
+
iid: String(node.number),
|
|
1373
|
+
title: node.title,
|
|
1374
|
+
url: node.url,
|
|
1375
|
+
state: node.state === "OPEN" ? "opened" : node.state.toLowerCase(),
|
|
1376
|
+
draft: node.isDraft,
|
|
1377
|
+
conflicts: node.mergeable === "CONFLICTING",
|
|
1378
|
+
conflictsKnown: node.mergeable !== "UNKNOWN",
|
|
1379
|
+
approved: node.reviewDecision === "APPROVED" && awaitingReviewers.length === 0 && changes.changesRequested !== true,
|
|
1380
|
+
reviewDecision: node.reviewDecision ?? undefined,
|
|
1381
|
+
...node.autoMergeRequest === undefined ? {} : { autoMergeEnabled: node.autoMergeRequest !== null },
|
|
1382
|
+
...changes,
|
|
1383
|
+
copilotReview: copilotReview({ ...node, reviewRequests: reviewerList }),
|
|
1384
|
+
awaitingReviewers,
|
|
1385
|
+
pendingHumanReviewers,
|
|
1386
|
+
reviewersComplete: !!reviewerList.pageInfo && !reviewerList.pageInfo.hasNextPage,
|
|
1387
|
+
approvalsComplete: !!reviewerList.pageInfo && !reviewerList.pageInfo.hasNextPage && opinionated.complete,
|
|
1388
|
+
reviewerIDs: [
|
|
1389
|
+
...new Set([
|
|
1390
|
+
...reviewerList.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" ? request.requestedReviewer.id ?? [] : []),
|
|
1391
|
+
...[...node.latestReviews?.nodes ?? [], ...opinionated.nodes].flatMap((review) => !review?.author?.__typename || review.author.__typename === "User" ? review?.author?.id ?? [] : [])
|
|
1392
|
+
])
|
|
1393
|
+
],
|
|
1394
|
+
approvers: normalizeGitHubApprovers(node, reviewerList, opinionated.nodes),
|
|
1395
|
+
targetProject: node.baseRepository.nameWithOwner,
|
|
1396
|
+
targetBranch: node.baseRefName,
|
|
1397
|
+
...node.headRepository ? { sourceProject: node.headRepository.nameWithOwner } : {},
|
|
1398
|
+
sourceBranch: node.headRefName,
|
|
1399
|
+
headSha: node.headRefOid,
|
|
1400
|
+
...node.author?.id ? { authorID: node.author.id } : {},
|
|
1401
|
+
...node.author?.login ? { authorUsername: node.author.login } : {},
|
|
1402
|
+
updatedAt: node.updatedAt,
|
|
1403
|
+
pipeline: contextData.nodes.length || !contextData.complete ? checks(contextData.nodes, contextData.complete, `${node.url}/checks`, node.headRefOid) : undefined,
|
|
1404
|
+
unresolvedThreads: threadData.unresolved,
|
|
1405
|
+
discussionResolutionRequired: threadData.unresolved > 0 ? await discussionRequirement(host, node) : undefined,
|
|
1406
|
+
threadsComplete: threadData.complete
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
async function discussion(ref, { id }) {
|
|
1410
|
+
let thread;
|
|
1411
|
+
const replies = await discussionPages(10, async (after) => {
|
|
1412
|
+
const data = await graphql(ref.host, query(`
|
|
1413
|
+
query($id:ID!,$after:String) {
|
|
1414
|
+
node(id:$id) { ... on PullRequestReviewThread {
|
|
1415
|
+
id isResolved path line pullRequest { url }
|
|
1416
|
+
comments(first:20,after:$after) {
|
|
1417
|
+
pageInfo { hasNextPage endCursor }
|
|
1418
|
+
nodes { id url body createdAt isMinimized author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
1419
|
+
}
|
|
1420
|
+
} }
|
|
1421
|
+
}`), { id, ...after ? { after } : {} });
|
|
1422
|
+
const candidate = data.node;
|
|
1423
|
+
const owner = candidate?.pullRequest && parseGitHubUrl(candidate.pullRequest.url);
|
|
1424
|
+
if (!candidate || candidate.id !== id || !owner || owner.host !== ref.host || owner.project.toLowerCase() !== ref.project.toLowerCase() || owner.iid !== ref.iid) {
|
|
1425
|
+
thread = undefined;
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1428
|
+
thread = candidate;
|
|
1429
|
+
return thread.isResolved ? undefined : thread.comments;
|
|
1430
|
+
});
|
|
1431
|
+
if (!thread)
|
|
1432
|
+
return;
|
|
1433
|
+
if (thread.isResolved)
|
|
1434
|
+
return "resolved";
|
|
1435
|
+
const notes = [];
|
|
1436
|
+
let incomplete = !replies.complete;
|
|
1437
|
+
for (const comment of replies.nodes) {
|
|
1438
|
+
const author = comment.author;
|
|
1439
|
+
if (!comment.id || comment.isMinimized || !author?.login || typeof comment.body !== "string") {
|
|
1440
|
+
incomplete = true;
|
|
1441
|
+
continue;
|
|
1442
|
+
}
|
|
1443
|
+
notes.push({
|
|
1444
|
+
id: comment.id,
|
|
1445
|
+
url: comment.url,
|
|
1446
|
+
authorID: author.id,
|
|
1447
|
+
username: botUsername(author.login, author.__typename),
|
|
1448
|
+
bot: author.__typename === "Bot" || author.login.endsWith("[bot]"),
|
|
1449
|
+
body: comment.body,
|
|
1450
|
+
createdAt: comment.createdAt,
|
|
1451
|
+
path: thread.path ?? undefined,
|
|
1452
|
+
line: thread.line ?? undefined
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
return {
|
|
1456
|
+
id,
|
|
1457
|
+
notes,
|
|
1458
|
+
url: notes.find((note) => note.url)?.url,
|
|
1459
|
+
incomplete: incomplete || notes.length === 0
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
async function unresolvedDiscussions(ref) {
|
|
1463
|
+
const [owner, repo] = ref.project.split("/");
|
|
1464
|
+
const number = Number(ref.iid);
|
|
1465
|
+
if (!owner || !repo || !Number.isInteger(number) || number < 1)
|
|
1466
|
+
return;
|
|
1467
|
+
const list = await discussionPages(GITHUB_MAX_PAGES, async (after) => {
|
|
1468
|
+
const data = await graphql(ref.host, query(`query($owner:String!,$repo:String!,$number:Int!${after ? ",$after:String!" : ""}) {
|
|
1469
|
+
repository(owner:$owner,name:$repo) {
|
|
1470
|
+
pullRequest(number:$number) {
|
|
1471
|
+
reviewThreads(first:100${after ? ",after:$after" : ""}) {
|
|
1472
|
+
nodes { id isResolved }
|
|
1473
|
+
pageInfo { hasNextPage endCursor }
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
}`), { owner, repo, number, ...after ? { after } : {} });
|
|
1478
|
+
return data.repository?.pullRequest?.reviewThreads;
|
|
1479
|
+
});
|
|
1480
|
+
const discussions = [];
|
|
1481
|
+
const candidates = list.nodes.filter(({ id, isResolved }) => id && !isResolved);
|
|
1482
|
+
for (const { id } of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
1483
|
+
const thread = await discussion(ref, { id }).catch(() => {
|
|
1484
|
+
return;
|
|
1485
|
+
});
|
|
1486
|
+
if (thread !== "resolved")
|
|
1487
|
+
discussions.push(thread ?? { id, notes: [], incomplete: true });
|
|
1488
|
+
}
|
|
1489
|
+
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
1490
|
+
}
|
|
1491
|
+
async function fetchByProjects(projects, number) {
|
|
1492
|
+
for (const project of projects) {
|
|
1493
|
+
const [owner, repo] = project.path.split("/");
|
|
1494
|
+
const data = await queryPull(project.host, (includeAutoMerge) => query(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
1495
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${githubPullFields(includeAutoMerge)} } }
|
|
1496
|
+
}`), { owner, repo, number: Number(number) });
|
|
1497
|
+
const node = data.repository?.pullRequest;
|
|
1498
|
+
if (node)
|
|
1499
|
+
return normalize(project.host, node);
|
|
1500
|
+
}
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
async function fetchByBranch(source, targets, sourceBranch) {
|
|
1504
|
+
const found = new Map;
|
|
1505
|
+
for (const target of targets) {
|
|
1506
|
+
const [owner, repo] = target.path.split("/");
|
|
1507
|
+
let after;
|
|
1508
|
+
let complete = false;
|
|
1509
|
+
for (let page = 0;page < GITHUB_MAX_PAGES; page++) {
|
|
1510
|
+
const data = await queryPull(target.host, (includeAutoMerge) => query(`query($owner:String!,$repo:String!,$branch:String!${after ? ",$after:String!" : ""}) {
|
|
1511
|
+
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${after ? ",after:$after" : ""}) {
|
|
1512
|
+
nodes { ${githubPullFields(includeAutoMerge)} } pageInfo { hasNextPage endCursor }
|
|
1513
|
+
} } }`), { owner, repo, branch: sourceBranch, ...after ? { after } : {} });
|
|
1514
|
+
const pulls = data.repository?.pullRequests;
|
|
1515
|
+
if (!pulls)
|
|
1516
|
+
throw new ForgeError("request", "GitHub repository unavailable");
|
|
1517
|
+
for (const node of pulls.nodes) {
|
|
1518
|
+
if (node.headRepository?.nameWithOwner.toLowerCase() !== source.path.toLowerCase())
|
|
1519
|
+
continue;
|
|
1520
|
+
if (!found.has(node.url))
|
|
1521
|
+
found.set(node.url, await normalize(target.host, node));
|
|
1522
|
+
}
|
|
1523
|
+
if (!pulls.pageInfo?.hasNextPage) {
|
|
1524
|
+
complete = true;
|
|
1525
|
+
break;
|
|
1526
|
+
}
|
|
1527
|
+
after = pulls.pageInfo.endCursor;
|
|
1528
|
+
if (!after)
|
|
1529
|
+
break;
|
|
1530
|
+
}
|
|
1531
|
+
if (!complete)
|
|
1532
|
+
throw new ForgeError("request", "GitHub PR discovery exceeded its pagination limit");
|
|
1533
|
+
}
|
|
1534
|
+
return [...found.values()].sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
1535
|
+
}
|
|
1536
|
+
async function viewer(host) {
|
|
1537
|
+
const data = await graphql(host, GITHUB_VIEWER_QUERY, {});
|
|
1538
|
+
const user = data.viewer;
|
|
1539
|
+
if (!user?.id && !user?.login)
|
|
1540
|
+
return;
|
|
1541
|
+
return {
|
|
1542
|
+
...user.id ? { id: user.id } : {},
|
|
1543
|
+
...user.login ? { username: user.login } : {}
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
return {
|
|
1547
|
+
forge: "github",
|
|
1548
|
+
fetchRequest: (ref) => fetchByProjects([{ host: ref.host, path: ref.project }], ref.iid),
|
|
1549
|
+
fetchByProjects,
|
|
1550
|
+
fetchByBranch,
|
|
1551
|
+
unresolvedDiscussions,
|
|
1552
|
+
discussion,
|
|
1553
|
+
viewer
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
// packages/_merge-readiness/src/transports/http.ts
|
|
1557
|
+
var LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
1558
|
+
// packages/forgekeeper/src/forge.ts
|
|
1559
|
+
var ownedBy = (kind) => (request) => request.forge === kind;
|
|
1560
|
+
var titlePrefix = (title) => title?.match(/^\[[^\]]*\]/)?.[0] ?? "";
|
|
1561
|
+
function prefixReferences(title, sigil) {
|
|
1562
|
+
return titlePrefix(title).slice(1, -1).split(/[\s,]+/).flatMap((token) => token.startsWith(sigil) && /^[1-9]\d*$/.test(token.slice(sigil.length)) ? [token.slice(sigil.length)] : []);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// packages/forgekeeper/src/review-summary.ts
|
|
1566
|
+
var MESSAGE_PREFIX = "msg_forgekeeper_";
|
|
1567
|
+
var SUMMARY_PREFIX = `${MESSAGE_PREFIX}summary_`;
|
|
1568
|
+
var EXCERPT_RADIUS = 10;
|
|
1569
|
+
var MAX_EXCERPT_FILES = 10;
|
|
1570
|
+
var MAX_LINE = 300;
|
|
1571
|
+
var LINKED_NOTE_TOOL = "fetch_linked_review_note";
|
|
1572
|
+
var MAX_LINKED_NOTES = 5;
|
|
1573
|
+
var MAX_LINK_LENGTH = 300;
|
|
1574
|
+
function excerpt(content, line) {
|
|
1575
|
+
const lines = content.split(`
|
|
1576
|
+
`);
|
|
1577
|
+
if (line < 1 || line > lines.length)
|
|
1578
|
+
return;
|
|
1579
|
+
const start = Math.max(1, line - EXCERPT_RADIUS);
|
|
1580
|
+
const end = Math.min(lines.length, line + EXCERPT_RADIUS);
|
|
1581
|
+
return lines.slice(start - 1, end).map((text, index) => {
|
|
1582
|
+
const number = start + index;
|
|
151
1583
|
const shown = text.length > MAX_LINE ? `${text.slice(0, MAX_LINE)}\u2026` : text;
|
|
152
1584
|
return `${number === line ? ">" : " "}${number}: ${shown}`;
|
|
153
1585
|
}).join(`
|
|
@@ -193,10 +1625,10 @@ var LIFECYCLE_SYSTEM = [
|
|
|
193
1625
|
"the change was detected, as given. Then say in a few sentences what happened, with its",
|
|
194
1626
|
"link: for a conflict, that the merge request cannot merge until its conflicts with its",
|
|
195
1627
|
"target branch are resolved; for a failed job, which jobs failed in its pipeline, and",
|
|
196
|
-
"whether the pipeline is still running; for requested changes,
|
|
197
|
-
"changes; for a merge-blocked request, what is preventing the approved request from merging;",
|
|
1628
|
+
"whether the pipeline is still running; for requested changes, who asked for changes",
|
|
1629
|
+
"(or that a reviewer asked for changes if unnamed); for a merge-blocked request, what is preventing the approved request from merging;",
|
|
198
1630
|
"if its details offer Review blocking threads, explicitly tell the user to select the merge-blocked item in /forge-feedback and choose Review blocking threads;",
|
|
199
|
-
"for a ready-to-merge request,
|
|
1631
|
+
"for a ready-to-merge request, whether the user can merge it, select Set to auto-merge, or needs a maintainer to merge it, as stated in the event;",
|
|
200
1632
|
"for a merge, that it merged; for an approval, who",
|
|
201
1633
|
"approved it; for an outdated issue, which of its fields look wrong. Then list each",
|
|
202
1634
|
"<mr-detail> line, keeping what it says Forgekeeper did or proposes. Do not claim anything",
|
|
@@ -944,243 +2376,54 @@ async function subscribeToNotes(run, directory, request, events, signal, socket
|
|
|
944
2376
|
ws.close();
|
|
945
2377
|
if (rateLimit)
|
|
946
2378
|
reject(rateLimit);
|
|
947
|
-
else
|
|
948
|
-
resolve();
|
|
949
|
-
};
|
|
950
|
-
const heartbeat = () => {
|
|
951
|
-
clearTimeout(timer);
|
|
952
|
-
timer = setTimeout(finish, confirmed ? 45000 : 15000);
|
|
953
|
-
};
|
|
954
|
-
heartbeat();
|
|
955
|
-
signal.addEventListener("abort", finish, { once: true });
|
|
956
|
-
ws.onerror = finish;
|
|
957
|
-
ws.onclose = finish;
|
|
958
|
-
ws.onresponse = (status, headers) => {
|
|
959
|
-
if (status === 429)
|
|
960
|
-
rateLimit = new SubscriptionRateLimit(subscriptionRetryAt(headers) ?? Date.now() + 60000);
|
|
961
|
-
finish();
|
|
962
|
-
};
|
|
963
|
-
ws.onmessage = (data) => {
|
|
964
|
-
if (ended)
|
|
965
|
-
return;
|
|
966
|
-
try {
|
|
967
|
-
const message = JSON.parse(String(data));
|
|
968
|
-
if (confirmed)
|
|
969
|
-
heartbeat();
|
|
970
|
-
if (message.type === "welcome")
|
|
971
|
-
ws.send(JSON.stringify({ command: "subscribe", identifier }));
|
|
972
|
-
if (message.type === "disconnect")
|
|
973
|
-
finish();
|
|
974
|
-
if (message.identifier !== identifier)
|
|
975
|
-
return;
|
|
976
|
-
if (message.type === "reject_subscription")
|
|
977
|
-
finish();
|
|
978
|
-
if (message.type === "confirm_subscription" && !confirmed) {
|
|
979
|
-
confirmed = true;
|
|
980
|
-
heartbeat();
|
|
981
|
-
events.connected();
|
|
982
|
-
}
|
|
983
|
-
if (confirmed && message.message?.event === "updated")
|
|
984
|
-
events.changed();
|
|
985
|
-
} catch {
|
|
986
|
-
finish();
|
|
987
|
-
}
|
|
988
|
-
};
|
|
989
|
-
if (signal.aborted)
|
|
990
|
-
finish();
|
|
991
|
-
});
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
// packages/forgekeeper/src/adapters/gitlab/approval-status.ts
|
|
995
|
-
function autoMergeCandidate(request) {
|
|
996
|
-
if (request.state !== "opened" || request.draft || request.autoMergeEnabled === true || request.mergeTrainIndex != null)
|
|
997
|
-
return false;
|
|
998
|
-
if (!request.conflictsKnown || !approvalsComplete(request) || request.autoMergeEnabled !== false)
|
|
999
|
-
return;
|
|
1000
|
-
if (!approvalsSatisfied(request) || request.conflicts || request.changesRequested || request.duoReviewState === "REVIEW_STARTED")
|
|
1001
|
-
return false;
|
|
1002
|
-
if (mergeBlocker(request) || pipelineFails(request.pipeline) || request.pipeline?.status === "FAILED")
|
|
1003
|
-
return false;
|
|
1004
|
-
if (!request.threadsComplete || request.unresolvedThreads > 0 && request.discussionResolutionRequired !== false)
|
|
1005
|
-
return;
|
|
1006
|
-
if (!request.mergeStatus)
|
|
1007
|
-
return;
|
|
1008
|
-
return request.mergeStatus === "MERGEABLE" || request.mergeStatus === "CI_STILL_RUNNING" && pipelineRunning(request.pipeline);
|
|
1009
|
-
}
|
|
1010
|
-
function readyToMerge(request) {
|
|
1011
|
-
const candidate = autoMergeCandidate(request);
|
|
1012
|
-
return candidate === true ? request.autoMergeAvailable : candidate;
|
|
1013
|
-
}
|
|
1014
|
-
function gitlabMergeStatusBlocker(mergeStatus) {
|
|
1015
|
-
switch (mergeStatus) {
|
|
1016
|
-
case "NEED_REBASE":
|
|
1017
|
-
return "rebase";
|
|
1018
|
-
case "JIRA_ASSOCIATION_MISSING":
|
|
1019
|
-
return "jira";
|
|
1020
|
-
case "EXTERNAL_STATUS_CHECKS":
|
|
1021
|
-
return "status-checks";
|
|
1022
|
-
case "BLOCKED_STATUS":
|
|
1023
|
-
return "blocked";
|
|
1024
|
-
default:
|
|
1025
|
-
return;
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
function hasUnresolvedThreads(request) {
|
|
1029
|
-
return request.mergeStatus === "DISCUSSIONS_NOT_RESOLVED" || request.discussionResolutionRequired === true && request.unresolvedThreads > 0;
|
|
1030
|
-
}
|
|
1031
|
-
function autoMergeDetail(request) {
|
|
1032
|
-
if (hasUnresolvedThreads(request))
|
|
1033
|
-
return "Auto-merge: set (blocked by unresolved threads)";
|
|
1034
|
-
if (gitlabMergeStatusBlocker(request.mergeStatus) && request.mergeStatus) {
|
|
1035
|
-
return `Auto-merge: set (blocked: ${humanize(request.mergeStatus)})`;
|
|
1036
|
-
}
|
|
1037
|
-
return "Auto-merge: set";
|
|
1038
|
-
}
|
|
1039
|
-
function manualBlockerIndicator(blocker) {
|
|
1040
|
-
switch (blocker) {
|
|
1041
|
-
case "rebase":
|
|
1042
|
-
return { text: "needs rebase", tone: "warning", optional: true };
|
|
1043
|
-
case "jira":
|
|
1044
|
-
return { text: "missing Jira issue", tone: "warning", optional: true };
|
|
1045
|
-
case "status-checks":
|
|
1046
|
-
return { text: "status checks pending", tone: "warning", optional: true };
|
|
1047
|
-
case "blocked":
|
|
1048
|
-
return { text: "merge blocked", tone: "warning", optional: true };
|
|
1049
|
-
default:
|
|
1050
|
-
return;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
function needsApproval(request) {
|
|
1054
|
-
return (request.missingRules?.length ?? 0) > 0 || (request.approvalsLeft ?? 0) > 0 || request.mergeStatus === "NOT_APPROVED";
|
|
1055
|
-
}
|
|
1056
|
-
function approvalsSatisfied(request) {
|
|
1057
|
-
if (needsApproval(request))
|
|
1058
|
-
return false;
|
|
1059
|
-
return request.approvalRequirementsSatisfied ?? (request.approved && request.awaitingReviewers.length === 0);
|
|
1060
|
-
}
|
|
1061
|
-
function mergeBlocker(request) {
|
|
1062
|
-
if (hasUnresolvedThreads(request))
|
|
1063
|
-
return "threads";
|
|
1064
|
-
return gitlabMergeStatusBlocker(request.mergeStatus);
|
|
1065
|
-
}
|
|
1066
|
-
function canProceedToMerge(request) {
|
|
1067
|
-
return !request.conflicts && request.pipeline?.status !== "FAILED";
|
|
1068
|
-
}
|
|
1069
|
-
function hasAutoMergeReadyApprovals(request) {
|
|
1070
|
-
return Boolean(request.autoMergeEnabled) && !needsApproval(request) && (request.approvalRequirementsSatisfied === true || request.mergeStatus === "MERGEABLE");
|
|
1071
|
-
}
|
|
1072
|
-
function approvalCount(request) {
|
|
1073
|
-
const left = request.approvalsLeft ?? 0;
|
|
1074
|
-
if (left <= 0 || request.approvalRequirementsSatisfied === true)
|
|
1075
|
-
return;
|
|
1076
|
-
const given = approversOf(request).filter((approver) => !approver.bot).length;
|
|
1077
|
-
return {
|
|
1078
|
-
text: given ? `${given} approval${given === 1 ? "" : "s"} \xB7 ${left} more needed` : `${left} approval${left === 1 ? "" : "s"} needed`,
|
|
1079
|
-
compact: given ? `${given} \u2713 +${left}` : `+${left}`,
|
|
1080
|
-
tone: "muted",
|
|
1081
|
-
optional: true
|
|
1082
|
-
};
|
|
1083
|
-
}
|
|
1084
|
-
function waitingOn(request) {
|
|
1085
|
-
const awaiting = request.awaitingReviewers.length ? { text: awaitingText(request.awaitingReviewers), tone: "muted" } : undefined;
|
|
1086
|
-
if (awaiting && !approvalsSatisfied(request))
|
|
1087
|
-
return awaiting;
|
|
1088
|
-
if (request.draft || request.changesRequested === true)
|
|
1089
|
-
return awaiting;
|
|
1090
|
-
const statusBlocker = gitlabMergeStatusBlocker(request.mergeStatus);
|
|
1091
|
-
if (canProceedToMerge(request)) {
|
|
1092
|
-
if (request.mergeTrainIndex != null)
|
|
1093
|
-
return { text: `merge train #${request.mergeTrainIndex + 1}`, tone: "muted", optional: true };
|
|
1094
|
-
if (hasAutoMergeReadyApprovals(request)) {
|
|
1095
|
-
if (hasUnresolvedThreads(request) || statusBlocker)
|
|
1096
|
-
return {
|
|
1097
|
-
text: "auto-merge blocked",
|
|
1098
|
-
compact: "auto-merge \u26D4",
|
|
1099
|
-
tone: "warning",
|
|
1100
|
-
optional: true
|
|
1101
|
-
};
|
|
1102
|
-
return awaiting ?? { text: "auto-merge set", tone: "success", optional: true };
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
if (request.approved || request.approvalRequirementsSatisfied === true) {
|
|
1106
|
-
if (canProceedToMerge(request) && !needsApproval(request)) {
|
|
1107
|
-
if (hasUnresolvedThreads(request))
|
|
1108
|
-
return { text: "merge blocked", tone: "warning", optional: true };
|
|
1109
|
-
return manualBlockerIndicator(statusBlocker) ?? awaiting;
|
|
1110
|
-
}
|
|
1111
|
-
return awaiting;
|
|
1112
|
-
}
|
|
1113
|
-
const missingRules = request.missingRules ?? [];
|
|
1114
|
-
const rule = missingRules.find((rule) => rule.type === "CODE_OWNER" || rule.type === "REGULAR");
|
|
1115
|
-
if (rule)
|
|
1116
|
-
return {
|
|
1117
|
-
text: rule.type === "CODE_OWNER" ? "needs a code owner" : "needs an approver",
|
|
1118
|
-
tone: "warning",
|
|
1119
|
-
optional: true
|
|
2379
|
+
else
|
|
2380
|
+
resolve();
|
|
1120
2381
|
};
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
2382
|
+
const heartbeat = () => {
|
|
2383
|
+
clearTimeout(timer);
|
|
2384
|
+
timer = setTimeout(finish, confirmed ? 45000 : 15000);
|
|
2385
|
+
};
|
|
2386
|
+
heartbeat();
|
|
2387
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
2388
|
+
ws.onerror = finish;
|
|
2389
|
+
ws.onclose = finish;
|
|
2390
|
+
ws.onresponse = (status, headers) => {
|
|
2391
|
+
if (status === 429)
|
|
2392
|
+
rateLimit = new SubscriptionRateLimit(subscriptionRetryAt(headers) ?? Date.now() + 60000);
|
|
2393
|
+
finish();
|
|
2394
|
+
};
|
|
2395
|
+
ws.onmessage = (data) => {
|
|
2396
|
+
if (ended)
|
|
2397
|
+
return;
|
|
2398
|
+
try {
|
|
2399
|
+
const message = JSON.parse(String(data));
|
|
2400
|
+
if (confirmed)
|
|
2401
|
+
heartbeat();
|
|
2402
|
+
if (message.type === "welcome")
|
|
2403
|
+
ws.send(JSON.stringify({ command: "subscribe", identifier }));
|
|
2404
|
+
if (message.type === "disconnect")
|
|
2405
|
+
finish();
|
|
2406
|
+
if (message.identifier !== identifier)
|
|
2407
|
+
return;
|
|
2408
|
+
if (message.type === "reject_subscription")
|
|
2409
|
+
finish();
|
|
2410
|
+
if (message.type === "confirm_subscription" && !confirmed) {
|
|
2411
|
+
confirmed = true;
|
|
2412
|
+
heartbeat();
|
|
2413
|
+
events.connected();
|
|
2414
|
+
}
|
|
2415
|
+
if (confirmed && message.message?.event === "updated")
|
|
2416
|
+
events.changed();
|
|
2417
|
+
} catch {
|
|
2418
|
+
finish();
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
if (signal.aborted)
|
|
2422
|
+
finish();
|
|
2423
|
+
});
|
|
1134
2424
|
}
|
|
1135
2425
|
|
|
1136
2426
|
// packages/forgekeeper/src/adapters/gitlab/adapter.ts
|
|
1137
|
-
var DISCUSSIONS = "pageInfo { hasNextPage endCursor } nodes { resolvable resolved }";
|
|
1138
|
-
var PAGE_SIZE4 = 100;
|
|
1139
|
-
var MAX_DISCUSSION_PAGES = 50;
|
|
1140
|
-
var FIRST_FAILED_JOBS = 10;
|
|
1141
|
-
var FAILED_JOBS = "pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }";
|
|
1142
|
-
var RECHECKING = new Set(["CHECKING", "UNCHECKED", "PREPARING"]);
|
|
1143
|
-
var CONFLICT_RECHECK = "CANNOT_BE_MERGED_RECHECK";
|
|
1144
|
-
var REVIEWER_FIELDS = (includeApprovedAt) => `pageInfo { hasNextPage endCursor } nodes { id type username bot mergeRequestInteraction { reviewState approved${includeApprovedAt ? " approvedAt" : ""} } }`;
|
|
1145
|
-
var APPROVED_BY_FIELDS = "pageInfo { hasNextPage endCursor } nodes { id username bot }";
|
|
1146
|
-
var mergeRequestFields = (includeApprovedAt, includeExtendedStatus) => `
|
|
1147
|
-
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
1148
|
-
autoMergeEnabled
|
|
1149
|
-
${includeExtendedStatus ? `
|
|
1150
|
-
approvalsRequired approvalsLeft mergeTrainCar { index }
|
|
1151
|
-
approvalState { rules { name type approvalsRequired approved eligibleApprovers { username type bot } } }
|
|
1152
|
-
` : ""}
|
|
1153
|
-
approvedBy(first: ${PAGE_SIZE4}) { ${APPROVED_BY_FIELDS} }
|
|
1154
|
-
sourceProject { fullPath }
|
|
1155
|
-
targetProject { fullPath }
|
|
1156
|
-
author { id }
|
|
1157
|
-
headPipeline {
|
|
1158
|
-
id status path detailedStatus { label }
|
|
1159
|
-
jobs(statuses: [FAILED], retried: false, first: ${FIRST_FAILED_JOBS}) { ${FAILED_JOBS} }
|
|
1160
|
-
}
|
|
1161
|
-
reviewers(first: ${PAGE_SIZE4}) { ${REVIEWER_FIELDS(includeApprovedAt)} }
|
|
1162
|
-
discussions(first: ${PAGE_SIZE4}) { ${DISCUSSIONS} }
|
|
1163
|
-
`;
|
|
1164
|
-
function mergeRequestsQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
1165
|
-
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
1166
|
-
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
1167
|
-
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) {
|
|
1168
|
-
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${fields} } }
|
|
1169
|
-
}`).join(`
|
|
1170
|
-
`);
|
|
1171
|
-
return query(`query($branch: String!, ${variables}) {
|
|
1172
|
-
${projects}
|
|
1173
|
-
}`);
|
|
1174
|
-
}
|
|
1175
|
-
function mergeRequestQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
1176
|
-
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
1177
|
-
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
1178
|
-
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) { mergeRequest(iid: $iid) { ${fields} } }`).join(`
|
|
1179
|
-
`);
|
|
1180
|
-
return query(`query($iid: String!, ${variables}) {
|
|
1181
|
-
${projects}
|
|
1182
|
-
}`);
|
|
1183
|
-
}
|
|
1184
2427
|
function mergeRequestNumbersQuery(projectCount) {
|
|
1185
2428
|
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
1186
2429
|
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) {
|
|
@@ -1249,55 +2492,12 @@ function workItemStatesQuery(count) {
|
|
|
1249
2492
|
}
|
|
1250
2493
|
}`);
|
|
1251
2494
|
}
|
|
1252
|
-
var DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
1253
|
-
project(fullPath: $project) {
|
|
1254
|
-
mergeRequest(iid: $iid) { discussions(first: ${PAGE_SIZE4}, after: $after) { ${DISCUSSIONS} } }
|
|
1255
|
-
}
|
|
1256
|
-
}`);
|
|
1257
|
-
var reviewersQuery = (includeApprovedAt) => query(`query($project: ID!, $iid: String!, $after: String) {
|
|
1258
|
-
project(fullPath: $project) {
|
|
1259
|
-
mergeRequest(iid: $iid) { reviewers(first: ${PAGE_SIZE4}, after: $after) { ${REVIEWER_FIELDS(includeApprovedAt)} } }
|
|
1260
|
-
}
|
|
1261
|
-
}`);
|
|
1262
|
-
var APPROVED_BY_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
1263
|
-
project(fullPath: $project) {
|
|
1264
|
-
mergeRequest(iid: $iid) { approvedBy(first: ${PAGE_SIZE4}, after: $after) { ${APPROVED_BY_FIELDS} } }
|
|
1265
|
-
}
|
|
1266
|
-
}`);
|
|
1267
2495
|
var MARK_READY_MUTATION = query(`mutation($project: ID!, $iid: String!) {
|
|
1268
2496
|
mergeRequestSetDraft(input: { projectPath: $project, iid: $iid, draft: false }) {
|
|
1269
2497
|
mergeRequest { draft }
|
|
1270
2498
|
errors
|
|
1271
2499
|
}
|
|
1272
2500
|
}`);
|
|
1273
|
-
var UNRESOLVED_DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
1274
|
-
project(fullPath: $project) {
|
|
1275
|
-
mergeRequest(iid: $iid) {
|
|
1276
|
-
state
|
|
1277
|
-
discussions(first: ${PAGE_SIZE4}, after: $after) {
|
|
1278
|
-
pageInfo { hasNextPage endCursor }
|
|
1279
|
-
nodes {
|
|
1280
|
-
id resolvable resolved
|
|
1281
|
-
notes(first: 1) { nodes { id } }
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
}`);
|
|
1287
|
-
var DISCUSSION_BY_NOTE = query(`
|
|
1288
|
-
query($note: NoteID!, $after: String) {
|
|
1289
|
-
note(id: $note) {
|
|
1290
|
-
discussion {
|
|
1291
|
-
id resolvable resolved
|
|
1292
|
-
noteable { ... on MergeRequest { webUrl } }
|
|
1293
|
-
notes(first: 20, after: $after) {
|
|
1294
|
-
pageInfo { hasNextPage endCursor }
|
|
1295
|
-
nodes { id url body createdAt system position { newPath newLine oldPath oldLine } author { id username bot } }
|
|
1296
|
-
}
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
`);
|
|
1301
2501
|
var RESOLVE_DISCUSSION_MUTATION = query(`mutation($id: DiscussionID!) {
|
|
1302
2502
|
discussionToggleResolve(input: { id: $id, resolve: true }) {
|
|
1303
2503
|
discussion { id resolved }
|
|
@@ -1306,20 +2506,6 @@ var RESOLVE_DISCUSSION_MUTATION = query(`mutation($id: DiscussionID!) {
|
|
|
1306
2506
|
}`);
|
|
1307
2507
|
var unsupportedApprovedAtHosts = new Set;
|
|
1308
2508
|
var unsupportedExtendedStatusHosts = new Set;
|
|
1309
|
-
var isMissingExtendedStatus = (error) => /(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState).*?(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*?(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState)|Field ['"]index['"] doesn't exist on type ['"]MergeTrainCar['"]/i.test(error instanceof Error ? error.message : String(error));
|
|
1310
|
-
var isMissingApprovedAt = (error) => /approvedAt.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*approvedAt/i.test(error instanceof Error ? error.message : String(error));
|
|
1311
|
-
function classifyError(message, code) {
|
|
1312
|
-
const text = message.trim().replace(/^glab:\s*/, "") || `glab exited with code ${code}`;
|
|
1313
|
-
if (/ENOENT|command not found/i.test(text))
|
|
1314
|
-
return new ForgeError("missing-glab", "glab is not installed");
|
|
1315
|
-
if (/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(text)) {
|
|
1316
|
-
return new ForgeError("auth", "GitLab authentication failed. Run `glab auth status`.");
|
|
1317
|
-
}
|
|
1318
|
-
if (/\b429\b|rate limit|too many requests/i.test(text))
|
|
1319
|
-
return new ForgeError("rate-limit", "GitLab rate limit reached");
|
|
1320
|
-
return new ForgeError("request", text.split(`
|
|
1321
|
-
`)[0]);
|
|
1322
|
-
}
|
|
1323
2509
|
var isResponse = (body) => typeof body === "object" && body !== null && (!("errors" in body) || Array.isArray(body.errors)) && (!("data" in body) || typeof body.data === "object");
|
|
1324
2510
|
function glabGraphQL(run, cwd) {
|
|
1325
2511
|
return async (host, query, variables) => {
|
|
@@ -1331,45 +2517,37 @@ function glabGraphQL(run, cwd) {
|
|
|
1331
2517
|
try {
|
|
1332
2518
|
body = JSON.parse(result.stdout);
|
|
1333
2519
|
} catch {
|
|
1334
|
-
throw
|
|
2520
|
+
throw classifyGitLabError(result.stderr, result.code);
|
|
1335
2521
|
}
|
|
1336
2522
|
if (!isResponse(body))
|
|
1337
|
-
throw
|
|
2523
|
+
throw classifyGitLabError(result.stderr || "Unexpected GitLab response", result.code);
|
|
1338
2524
|
if (body.errors?.length)
|
|
1339
|
-
throw
|
|
2525
|
+
throw classifyGitLabError(String(body.errors[0]?.message ?? ""), result.code);
|
|
1340
2526
|
if (result.code !== 0)
|
|
1341
|
-
throw
|
|
2527
|
+
throw classifyGitLabError(result.stderr, result.code);
|
|
1342
2528
|
if (!body.data)
|
|
1343
|
-
throw
|
|
2529
|
+
throw classifyGitLabError("GitLab returned no data", result.code);
|
|
1344
2530
|
return body.data;
|
|
1345
2531
|
};
|
|
1346
2532
|
}
|
|
1347
|
-
var countUnresolved = (page) => page.nodes.filter((discussion) => discussion.resolvable && !discussion.resolved).length;
|
|
1348
2533
|
var gitlabTraits = {
|
|
1349
2534
|
kind: "gitlab",
|
|
1350
2535
|
noun: "MR",
|
|
1351
2536
|
fullNoun: "merge request",
|
|
1352
2537
|
ci: "pipeline",
|
|
1353
|
-
recognizes:
|
|
2538
|
+
recognizes: isGitLabHost,
|
|
1354
2539
|
open: (run, directory) => new GitLabForge(glabGraphQL(run, directory), unsupportedApprovedAtHosts, unsupportedExtendedStatusHosts),
|
|
1355
2540
|
owns: ownedBy("gitlab"),
|
|
1356
|
-
parseUrl:
|
|
2541
|
+
parseUrl: parseGitLabUrl,
|
|
1357
2542
|
parseIssueUrl: (url) => parseWebUrl("gitlab", url, /^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),
|
|
1358
2543
|
reference: (iid) => `!${iid}`,
|
|
1359
2544
|
issueReference: (iid) => `#${iid}`,
|
|
1360
2545
|
titleReferences: (title) => prefixReferences(title, "!"),
|
|
1361
2546
|
indicators: () => [],
|
|
1362
2547
|
reviewIndicators,
|
|
1363
|
-
approvalsSatisfied,
|
|
1364
|
-
mergeBlocker,
|
|
1365
2548
|
readyToMerge,
|
|
2549
|
+
readyToMergeState,
|
|
1366
2550
|
hasRequestedChanges: (request) => request.changesRequested,
|
|
1367
|
-
approvalStatus: (request) => ({
|
|
1368
|
-
approvalRequirementsSatisfied: request.approvalRequirementsSatisfied === null ? "unknown" : request.approvalRequirementsSatisfied,
|
|
1369
|
-
hasHumanApprovals: approvalsComplete(request) ? request.hasApprovals : "unknown",
|
|
1370
|
-
...request.mergeStatus ? { mergeStatus: request.mergeStatus } : {},
|
|
1371
|
-
...request.autoMergeEnabled === undefined ? {} : { autoMergeEnabled: request.autoMergeEnabled }
|
|
1372
|
-
}),
|
|
1373
2551
|
details(request) {
|
|
1374
2552
|
const requirements = request.approvalRequirementsSatisfied === null ? "unknown" : yesNo(request.approvalRequirementsSatisfied);
|
|
1375
2553
|
const lines = [
|
|
@@ -1440,158 +2618,27 @@ var gitlabTraits = {
|
|
|
1440
2618
|
return ref ? fetchLinkedNote(glabGraphQL(run, directory), ref.host, url) : undefined;
|
|
1441
2619
|
}
|
|
1442
2620
|
}
|
|
1443
|
-
};
|
|
1444
|
-
var
|
|
1445
|
-
function
|
|
1446
|
-
if (
|
|
1447
|
-
return
|
|
1448
|
-
return
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
...job.stage?.name ? { stage: job.stage.name } : {}
|
|
1461
|
-
}
|
|
1462
|
-
] : []);
|
|
1463
|
-
}
|
|
1464
|
-
function duoState(state) {
|
|
1465
|
-
if (state === "REVIEW_STARTED")
|
|
1466
|
-
return "running";
|
|
1467
|
-
return DUO_FEEDBACK.has(state) ? "feedback" : "settled";
|
|
1468
|
-
}
|
|
1469
|
-
function normalizeApprovers(reviewers, approvedBy) {
|
|
1470
|
-
const byId = new Map;
|
|
1471
|
-
const byUsername = new Map;
|
|
1472
|
-
for (const reviewer of reviewers) {
|
|
1473
|
-
if (reviewer.id)
|
|
1474
|
-
byId.set(reviewer.id, reviewer);
|
|
1475
|
-
if (reviewer.username)
|
|
1476
|
-
byUsername.set(reviewer.username.toLowerCase(), reviewer);
|
|
1477
|
-
}
|
|
1478
|
-
const isDuo = (reviewer, username, bot) => reviewer?.type === "DUO_CODE_REVIEW_BOT" || bot === true && username?.toLowerCase() === "gitlabduo";
|
|
1479
|
-
const inactiveReview = (reviewer) => {
|
|
1480
|
-
const state = reviewer?.mergeRequestInteraction?.reviewState;
|
|
1481
|
-
return !!state && state !== "APPROVED";
|
|
1482
|
-
};
|
|
1483
|
-
const found = [];
|
|
1484
|
-
const add = (entry) => {
|
|
1485
|
-
const lower = entry.username.toLowerCase();
|
|
1486
|
-
const index = found.findIndex((existing) => entry.id && existing.id ? existing.id === entry.id : existing.username.toLowerCase() === lower && (!entry.id || !existing.id));
|
|
1487
|
-
if (index < 0) {
|
|
1488
|
-
found.push(entry);
|
|
1489
|
-
return;
|
|
1490
|
-
}
|
|
1491
|
-
const existing = found[index];
|
|
1492
|
-
found[index] = {
|
|
1493
|
-
...existing,
|
|
1494
|
-
...entry,
|
|
1495
|
-
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
1496
|
-
...existing.bot || entry.bot ? { bot: true } : {},
|
|
1497
|
-
...existing.automated || entry.automated ? { automated: true } : {},
|
|
1498
|
-
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
1499
|
-
};
|
|
1500
|
-
};
|
|
1501
|
-
for (const reviewer of reviewers) {
|
|
1502
|
-
const interaction = reviewer.mergeRequestInteraction;
|
|
1503
|
-
const approving = interaction?.reviewState === "APPROVED" || !interaction?.reviewState && interaction?.approved === true;
|
|
1504
|
-
if (!approving)
|
|
1505
|
-
continue;
|
|
1506
|
-
const duo = isDuo(reviewer, reviewer.username, reviewer.bot);
|
|
1507
|
-
const username = reviewer.username ?? (duo ? "GitLabDuo" : undefined);
|
|
1508
|
-
if (!username)
|
|
1509
|
-
continue;
|
|
1510
|
-
const bot = reviewer.bot === true || duo;
|
|
1511
|
-
add({
|
|
1512
|
-
...reviewer.id ? { id: reviewer.id } : {},
|
|
1513
|
-
username,
|
|
1514
|
-
...bot ? { bot: true } : {},
|
|
1515
|
-
...duo ? { automated: true } : {},
|
|
1516
|
-
...interaction?.approvedAt ? { reviewID: interaction.approvedAt } : {}
|
|
1517
|
-
});
|
|
1518
|
-
}
|
|
1519
|
-
for (const approver of approvedBy) {
|
|
1520
|
-
const matched = (approver.id ? byId.get(approver.id) : undefined) ?? (approver.username ? byUsername.get(approver.username.toLowerCase()) : undefined);
|
|
1521
|
-
if (inactiveReview(matched))
|
|
1522
|
-
continue;
|
|
1523
|
-
const duo = isDuo(matched, approver.username ?? matched?.username, approver.bot ?? matched?.bot);
|
|
1524
|
-
const username = approver.username ?? matched?.username ?? (duo ? "GitLabDuo" : undefined);
|
|
1525
|
-
if (!username)
|
|
1526
|
-
continue;
|
|
1527
|
-
const bot = approver.bot === true || matched?.bot === true || duo;
|
|
1528
|
-
add({
|
|
1529
|
-
...approver.id || matched?.id ? { id: approver.id ?? matched?.id ?? undefined } : {},
|
|
1530
|
-
username,
|
|
1531
|
-
...bot ? { bot: true } : {},
|
|
1532
|
-
...duo ? { automated: true } : {}
|
|
1533
|
-
});
|
|
1534
|
-
}
|
|
1535
|
-
return found;
|
|
1536
|
-
}
|
|
1537
|
-
|
|
1538
|
-
class GitLabForge {
|
|
1539
|
-
unsupportedApprovedAt;
|
|
1540
|
-
unsupportedExtendedStatus;
|
|
1541
|
-
traits = gitlabTraits;
|
|
1542
|
-
graphql;
|
|
1543
|
-
constructor(graphql, unsupportedApprovedAt = new Set, unsupportedExtendedStatus = new Set) {
|
|
1544
|
-
this.unsupportedApprovedAt = unsupportedApprovedAt;
|
|
1545
|
-
this.unsupportedExtendedStatus = unsupportedExtendedStatus;
|
|
1546
|
-
this.graphql = typed(graphql);
|
|
1547
|
-
}
|
|
1548
|
-
async queryWithApprovedAt(host, build, variables) {
|
|
1549
|
-
if (this.unsupportedApprovedAt.has(host)) {
|
|
1550
|
-
return this.graphql(host, build(false), variables);
|
|
1551
|
-
}
|
|
1552
|
-
try {
|
|
1553
|
-
return await this.graphql(host, build(true), variables);
|
|
1554
|
-
} catch (error) {
|
|
1555
|
-
if (!isMissingApprovedAt(error))
|
|
1556
|
-
throw error;
|
|
1557
|
-
this.unsupportedApprovedAt.add(host);
|
|
1558
|
-
return this.graphql(host, build(false), variables);
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
async queryStatus(host, build, variables) {
|
|
1562
|
-
const run = (extended) => this.queryWithApprovedAt(host, (approvedAt) => build(approvedAt, extended), variables);
|
|
1563
|
-
if (this.unsupportedExtendedStatus.has(host))
|
|
1564
|
-
return run(false);
|
|
1565
|
-
try {
|
|
1566
|
-
return await run(true);
|
|
1567
|
-
} catch (error) {
|
|
1568
|
-
if (!isMissingExtendedStatus(error))
|
|
1569
|
-
throw error;
|
|
1570
|
-
this.unsupportedExtendedStatus.add(host);
|
|
1571
|
-
return run(false);
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
async findByBranch(repository) {
|
|
1575
|
-
const { source, targets, sourceBranch } = repository;
|
|
1576
|
-
const variables = { branch: sourceBranch };
|
|
1577
|
-
targets.forEach((target, index) => variables[`p${index}`] = target.path);
|
|
1578
|
-
const data = await this.queryStatus(source.host, (approvedAt, extended) => mergeRequestsQuery(targets.length, approvedAt, extended), variables);
|
|
1579
|
-
const sourcePath = source.path.toLowerCase();
|
|
1580
|
-
const seen = new Set;
|
|
1581
|
-
const nodes = [];
|
|
1582
|
-
targets.forEach((_, index) => {
|
|
1583
|
-
for (const node of data[`p${index}`]?.mergeRequests?.nodes ?? []) {
|
|
1584
|
-
if (node.sourceProject?.fullPath.toLowerCase() !== sourcePath)
|
|
1585
|
-
continue;
|
|
1586
|
-
const key = `${node.targetProject.fullPath}!${node.iid}`;
|
|
1587
|
-
if (seen.has(key))
|
|
1588
|
-
continue;
|
|
1589
|
-
seen.add(key);
|
|
1590
|
-
nodes.push(node);
|
|
1591
|
-
}
|
|
2621
|
+
};
|
|
2622
|
+
var DUO_FEEDBACK2 = new Set(["REVIEWED", "REQUESTED_CHANGES"]);
|
|
2623
|
+
function duoState(state) {
|
|
2624
|
+
if (state === "REVIEW_STARTED")
|
|
2625
|
+
return "running";
|
|
2626
|
+
return DUO_FEEDBACK2.has(state) ? "feedback" : "settled";
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
class GitLabForge {
|
|
2630
|
+
traits = gitlabTraits;
|
|
2631
|
+
graphql;
|
|
2632
|
+
source;
|
|
2633
|
+
constructor(graphql, unsupportedApprovedAt = new Set, unsupportedExtendedStatus = new Set) {
|
|
2634
|
+
this.graphql = typed(graphql);
|
|
2635
|
+
this.source = createGitLabSource(graphql, {
|
|
2636
|
+
unsupportedApprovedAt,
|
|
2637
|
+
unsupportedExtendedStatus
|
|
1592
2638
|
});
|
|
1593
|
-
|
|
1594
|
-
|
|
2639
|
+
}
|
|
2640
|
+
findByBranch(repository) {
|
|
2641
|
+
return this.source.fetchByBranch(repository.source, repository.targets, repository.sourceBranch);
|
|
1595
2642
|
}
|
|
1596
2643
|
async findNumberByBranch(repository) {
|
|
1597
2644
|
const { source, targets, sourceBranch } = repository;
|
|
@@ -1728,78 +2775,11 @@ class GitLabForge {
|
|
|
1728
2775
|
if (!result?.mergeRequest || result.mergeRequest.draft !== false)
|
|
1729
2776
|
throw new ForgeError("request", "Could not mark the GitLab merge request as ready");
|
|
1730
2777
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
const data = await this.graphql(ref.host, UNRESOLVED_DISCUSSIONS_QUERY, {
|
|
1734
|
-
project: ref.project,
|
|
1735
|
-
iid: ref.iid,
|
|
1736
|
-
...after ? { after } : {}
|
|
1737
|
-
});
|
|
1738
|
-
return data.project?.mergeRequest?.discussions;
|
|
1739
|
-
});
|
|
1740
|
-
const discussions = [];
|
|
1741
|
-
const candidates = list.nodes.filter(({ id, resolvable, resolved }) => id && resolvable && !resolved);
|
|
1742
|
-
for (const node of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
1743
|
-
const noteID = node.notes?.nodes[0]?.id?.match(/^gid:\/\/gitlab\/\w+\/(\d+)$/)?.[1];
|
|
1744
|
-
const anchor = noteID ? `gid://gitlab/Note/${noteID}` : undefined;
|
|
1745
|
-
const thread = await this.discussion(ref, { id: node.id, anchor }).catch(() => {
|
|
1746
|
-
return;
|
|
1747
|
-
});
|
|
1748
|
-
if (thread !== "resolved")
|
|
1749
|
-
discussions.push(thread ?? { id: node.id, notes: [], incomplete: true });
|
|
1750
|
-
}
|
|
1751
|
-
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
2778
|
+
unresolvedDiscussions(ref) {
|
|
2779
|
+
return this.source.unresolvedDiscussions(ref);
|
|
1752
2780
|
}
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
return;
|
|
1756
|
-
let resolved = false;
|
|
1757
|
-
let owned = false;
|
|
1758
|
-
const replies = await discussionPages(10, async (after) => {
|
|
1759
|
-
const data = await this.graphql(ref.host, DISCUSSION_BY_NOTE, {
|
|
1760
|
-
note: anchor,
|
|
1761
|
-
...after ? { after } : {}
|
|
1762
|
-
});
|
|
1763
|
-
const thread = data.note?.discussion;
|
|
1764
|
-
const owner = thread?.noteable?.webUrl && gitlabTraits.parseUrl(thread.noteable.webUrl);
|
|
1765
|
-
owned = Boolean(thread?.id === id && owner && owner.host === ref.host && owner.project === ref.project && owner.iid === ref.iid);
|
|
1766
|
-
if (!owned || !thread)
|
|
1767
|
-
return;
|
|
1768
|
-
resolved = thread.resolved;
|
|
1769
|
-
return resolved || !thread.resolvable ? undefined : thread.notes;
|
|
1770
|
-
});
|
|
1771
|
-
if (!owned)
|
|
1772
|
-
return;
|
|
1773
|
-
if (resolved)
|
|
1774
|
-
return "resolved";
|
|
1775
|
-
const notes = [];
|
|
1776
|
-
let incomplete = !replies.complete;
|
|
1777
|
-
for (const note of replies.nodes) {
|
|
1778
|
-
if (note.system)
|
|
1779
|
-
continue;
|
|
1780
|
-
if (!note.id || !note.author?.username || typeof note.body !== "string") {
|
|
1781
|
-
incomplete = true;
|
|
1782
|
-
continue;
|
|
1783
|
-
}
|
|
1784
|
-
notes.push({
|
|
1785
|
-
id: note.id.slice(note.id.lastIndexOf("/") + 1),
|
|
1786
|
-
url: note.url ?? undefined,
|
|
1787
|
-
authorID: note.author.id,
|
|
1788
|
-
username: note.author.username,
|
|
1789
|
-
bot: note.author.bot === true,
|
|
1790
|
-
body: note.body,
|
|
1791
|
-
createdAt: note.createdAt ?? undefined,
|
|
1792
|
-
path: note.position?.newPath ?? note.position?.oldPath ?? undefined,
|
|
1793
|
-
line: note.position?.newLine ?? note.position?.oldLine ?? undefined
|
|
1794
|
-
});
|
|
1795
|
-
}
|
|
1796
|
-
return {
|
|
1797
|
-
id,
|
|
1798
|
-
anchor,
|
|
1799
|
-
notes,
|
|
1800
|
-
url: notes.find((note) => note.url)?.url,
|
|
1801
|
-
incomplete: incomplete || notes.length === 0
|
|
1802
|
-
};
|
|
2781
|
+
discussion(ref, thread) {
|
|
2782
|
+
return this.source.discussion(ref, thread);
|
|
1803
2783
|
}
|
|
1804
2784
|
async resolveDiscussion(ref, discussionID, options) {
|
|
1805
2785
|
await options?.beforeMutate?.();
|
|
@@ -1809,211 +2789,15 @@ class GitLabForge {
|
|
|
1809
2789
|
const result = data.discussionToggleResolve;
|
|
1810
2790
|
if (result?.errors?.length)
|
|
1811
2791
|
throw new ForgeError("request", result.errors[0]);
|
|
1812
|
-
if (!result?.discussion || result.discussion.resolved !== true)
|
|
1813
|
-
throw new ForgeError("request", "Could not resolve the GitLab discussion");
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
return;
|
|
1818
|
-
const host = projects[0].host;
|
|
1819
|
-
const variables = { iid };
|
|
1820
|
-
projects.forEach((project, index) => variables[`p${index}`] = project.path);
|
|
1821
|
-
const data = await this.queryStatus(host, (approvedAt, extended) => mergeRequestQuery(projects.length, approvedAt, extended), variables);
|
|
1822
|
-
for (let index = 0;index < projects.length; index++) {
|
|
1823
|
-
const node = data[`p${index}`]?.mergeRequest;
|
|
1824
|
-
if (node)
|
|
1825
|
-
return this.normalize(host, node);
|
|
1826
|
-
}
|
|
1827
|
-
return;
|
|
1828
|
-
}
|
|
1829
|
-
async discussionRequirement(host, node) {
|
|
1830
|
-
if (node.detailedMergeStatus === "DISCUSSIONS_NOT_RESOLVED")
|
|
1831
|
-
return true;
|
|
1832
|
-
const data = await this.graphql(host, query(`query($project: ID!) { project(fullPath: $project) { onlyAllowMergeIfAllDiscussionsAreResolved } }`), { project: node.targetProject.fullPath }).catch(() => {
|
|
1833
|
-
return;
|
|
1834
|
-
});
|
|
1835
|
-
return data?.project?.onlyAllowMergeIfAllDiscussionsAreResolved ?? undefined;
|
|
1836
|
-
}
|
|
1837
|
-
async unresolvedThreads(host, node) {
|
|
1838
|
-
let count = countUnresolved(node.discussions);
|
|
1839
|
-
let page = node.discussions.pageInfo;
|
|
1840
|
-
let pages = 1;
|
|
1841
|
-
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
1842
|
-
const data = await this.graphql(host, DISCUSSIONS_QUERY, {
|
|
1843
|
-
project: node.targetProject.fullPath,
|
|
1844
|
-
iid: node.iid,
|
|
1845
|
-
after: page.endCursor
|
|
1846
|
-
});
|
|
1847
|
-
const next = data.project?.mergeRequest?.discussions;
|
|
1848
|
-
if (!next)
|
|
1849
|
-
break;
|
|
1850
|
-
count += countUnresolved(next);
|
|
1851
|
-
page = next.pageInfo;
|
|
1852
|
-
pages++;
|
|
1853
|
-
}
|
|
1854
|
-
return { count, complete: !page.hasNextPage };
|
|
1855
|
-
}
|
|
1856
|
-
async allReviewers(host, node) {
|
|
1857
|
-
if (!node.reviewers?.pageInfo)
|
|
1858
|
-
return { nodes: [...node.reviewers?.nodes ?? []], complete: false };
|
|
1859
|
-
const nodes = [...node.reviewers.nodes];
|
|
1860
|
-
let page = node.reviewers.pageInfo;
|
|
1861
|
-
let pages = 1;
|
|
1862
|
-
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
1863
|
-
const data = await this.queryWithApprovedAt(host, (includeApprovedAt) => reviewersQuery(includeApprovedAt), {
|
|
1864
|
-
project: node.targetProject.fullPath,
|
|
1865
|
-
iid: node.iid,
|
|
1866
|
-
after: page.endCursor
|
|
1867
|
-
});
|
|
1868
|
-
const next = data.project?.mergeRequest?.reviewers;
|
|
1869
|
-
if (!next?.pageInfo)
|
|
1870
|
-
return { nodes, complete: false };
|
|
1871
|
-
nodes.push(...next.nodes);
|
|
1872
|
-
page = next.pageInfo;
|
|
1873
|
-
pages++;
|
|
1874
|
-
}
|
|
1875
|
-
return { nodes, complete: !page.hasNextPage };
|
|
1876
|
-
}
|
|
1877
|
-
async allApprovedBy(host, node) {
|
|
1878
|
-
if (!node.approvedBy?.pageInfo)
|
|
1879
|
-
return { nodes: [...node.approvedBy?.nodes ?? []], complete: false };
|
|
1880
|
-
const nodes = [...node.approvedBy.nodes];
|
|
1881
|
-
let page = node.approvedBy.pageInfo;
|
|
1882
|
-
let pages = 1;
|
|
1883
|
-
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
1884
|
-
const data = await this.graphql(host, APPROVED_BY_QUERY, {
|
|
1885
|
-
project: node.targetProject.fullPath,
|
|
1886
|
-
iid: node.iid,
|
|
1887
|
-
after: page.endCursor
|
|
1888
|
-
});
|
|
1889
|
-
const next = data.project?.mergeRequest?.approvedBy;
|
|
1890
|
-
if (!next?.pageInfo)
|
|
1891
|
-
return { nodes, complete: false };
|
|
1892
|
-
nodes.push(...next.nodes);
|
|
1893
|
-
page = next.pageInfo;
|
|
1894
|
-
pages++;
|
|
1895
|
-
}
|
|
1896
|
-
return { nodes, complete: !page.hasNextPage };
|
|
1897
|
-
}
|
|
1898
|
-
async normalize(host, node) {
|
|
1899
|
-
const [threads, reviewersPage, approvedByPage] = await Promise.all([
|
|
1900
|
-
this.unresolvedThreads(host, node),
|
|
1901
|
-
this.allReviewers(host, node),
|
|
1902
|
-
this.allApprovedBy(host, node)
|
|
1903
|
-
]);
|
|
1904
|
-
const pipeline = node.headPipeline;
|
|
1905
|
-
const discussionResolutionRequired = threads.count > 0 ? await this.discussionRequirement(host, node) : undefined;
|
|
1906
|
-
const hasApprovals = approvedByPage.nodes.some((approver) => approver.bot !== true);
|
|
1907
|
-
const unapproved = reviewersPage.nodes.filter((reviewer) => reviewer.bot !== true && reviewer.username && reviewer.mergeRequestInteraction?.approved !== true);
|
|
1908
|
-
const awaitingReviewers = unapproved.filter((reviewer) => reviewer.mergeRequestInteraction?.reviewState !== "REQUESTED_CHANGES").map((reviewer) => reviewer.username);
|
|
1909
|
-
const approvers = normalizeApprovers(reviewersPage.nodes, approvedByPage.nodes);
|
|
1910
|
-
const approvedNames = new Set([...approvedByPage.nodes, ...approvers].flatMap(({ username }) => username ? [username.toLowerCase()] : []));
|
|
1911
|
-
const missingRules = (node.approvalState?.rules ?? []).flatMap((rule) => {
|
|
1912
|
-
if (rule.approvalsRequired == null || rule.approvalsRequired <= 0 || rule.approved !== false)
|
|
1913
|
-
return [];
|
|
1914
|
-
const eligible = (rule.eligibleApprovers ?? []).filter(({ username, bot }) => !bot && !approvedNames.has(username.toLowerCase()));
|
|
1915
|
-
const eligibleNames = new Set(eligible.map(({ username }) => username.toLowerCase()));
|
|
1916
|
-
const humans = eligible.filter(({ type }) => type === "HUMAN");
|
|
1917
|
-
const humanNames = new Set(humans.map(({ username }) => username.toLowerCase()));
|
|
1918
|
-
const eligibleReviewers = unapproved.map((reviewer) => reviewer.username).filter((username) => eligibleNames.has(username.toLowerCase())).sort((a, b) => Number(humanNames.has(b.toLowerCase())) - Number(humanNames.has(a.toLowerCase())));
|
|
1919
|
-
const candidates = humans.length ? humans : eligible;
|
|
1920
|
-
return [
|
|
1921
|
-
{
|
|
1922
|
-
name: rule.name ?? "Unnamed approval rule",
|
|
1923
|
-
type: rule.type ?? undefined,
|
|
1924
|
-
required: rule.approvalsRequired,
|
|
1925
|
-
eligibleReviewers,
|
|
1926
|
-
eligible: candidates.slice(0, 2).map(({ username }) => username),
|
|
1927
|
-
eligibleCount: candidates.length
|
|
1928
|
-
}
|
|
1929
|
-
];
|
|
1930
|
-
});
|
|
1931
|
-
const request = {
|
|
1932
|
-
forge: "gitlab",
|
|
1933
|
-
iid: node.iid,
|
|
1934
|
-
title: node.title,
|
|
1935
|
-
url: node.webUrl,
|
|
1936
|
-
state: node.state.toLowerCase(),
|
|
1937
|
-
draft: node.draft,
|
|
1938
|
-
conflicts: node.conflicts || node.mergeStatusEnum === CONFLICT_RECHECK,
|
|
1939
|
-
conflictsKnown: node.mergeStatusEnum !== CONFLICT_RECHECK && !RECHECKING.has(node.detailedMergeStatus ?? ""),
|
|
1940
|
-
approved: node.approved === true && hasApprovals && unapproved.length === 0,
|
|
1941
|
-
hasApprovals,
|
|
1942
|
-
approvalRequirementsSatisfied: node.approved,
|
|
1943
|
-
discussionResolutionRequired,
|
|
1944
|
-
approvalsRequired: node.approvalsRequired ?? undefined,
|
|
1945
|
-
approvalsLeft: node.approvalsLeft ?? undefined,
|
|
1946
|
-
missingRules,
|
|
1947
|
-
autoMergeEnabled: node.autoMergeEnabled,
|
|
1948
|
-
mergeTrainIndex: node.mergeTrainCar?.index,
|
|
1949
|
-
awaitingReviewers,
|
|
1950
|
-
reviewersComplete: reviewersPage.complete,
|
|
1951
|
-
changesRequested: (() => {
|
|
1952
|
-
if (reviewersPage.nodes.some((reviewer) => reviewer.mergeRequestInteraction?.reviewState === "REQUESTED_CHANGES")) {
|
|
1953
|
-
return true;
|
|
1954
|
-
}
|
|
1955
|
-
if (reviewersPage.complete && reviewersPage.nodes.every((reviewer) => reviewer.mergeRequestInteraction?.reviewState)) {
|
|
1956
|
-
return false;
|
|
1957
|
-
}
|
|
1958
|
-
return;
|
|
1959
|
-
})(),
|
|
1960
|
-
approvalsComplete: reviewersPage.complete && approvedByPage.complete,
|
|
1961
|
-
reviewerIDs: reviewersPage.nodes.flatMap((reviewer) => reviewer.id ?? []),
|
|
1962
|
-
approvers,
|
|
1963
|
-
mergeStatus: node.detailedMergeStatus ?? undefined,
|
|
1964
|
-
targetProject: node.targetProject.fullPath,
|
|
1965
|
-
targetBranch: node.targetBranch,
|
|
1966
|
-
...node.sourceProject ? { sourceProject: node.sourceProject.fullPath } : {},
|
|
1967
|
-
sourceBranch: node.sourceBranch,
|
|
1968
|
-
headSha: node.diffHeadSha ?? undefined,
|
|
1969
|
-
...node.author?.id ? { authorID: node.author.id } : {},
|
|
1970
|
-
updatedAt: node.updatedAt ?? undefined,
|
|
1971
|
-
pipeline: pipeline ? {
|
|
1972
|
-
status: pipeline.status,
|
|
1973
|
-
label: pipeline.detailedStatus?.label ?? pipeline.status.toLowerCase().replace(/_/g, " "),
|
|
1974
|
-
url: pipeline.path ? `https://${host}${pipeline.path}` : undefined,
|
|
1975
|
-
...failedJobs(host, pipeline)
|
|
1976
|
-
} : undefined,
|
|
1977
|
-
unresolvedThreads: threads.count,
|
|
1978
|
-
threadsComplete: threads.complete,
|
|
1979
|
-
duoReviewState: reviewersPage.nodes.find((reviewer) => reviewer.type === "DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState ?? undefined
|
|
1980
|
-
};
|
|
1981
|
-
if (autoMergeCandidate(request) === true && request.headSha) {
|
|
1982
|
-
const data = await this.graphql(host, query(`query($project: ID!, $iid: String!) {
|
|
1983
|
-
project(fullPath: $project) { mergeRequest(iid: $iid) {
|
|
1984
|
-
diffHeadSha autoMergeEnabled detailedMergeStatus userPermissions { canMerge }
|
|
1985
|
-
availableAutoMergeStrategies
|
|
1986
|
-
} }
|
|
1987
|
-
}`), { project: request.targetProject, iid: request.iid }).catch(() => {
|
|
1988
|
-
return;
|
|
1989
|
-
});
|
|
1990
|
-
const live = data?.project?.mergeRequest;
|
|
1991
|
-
if (live?.diffHeadSha === request.headSha && live.autoMergeEnabled === false && live.detailedMergeStatus === request.mergeStatus) {
|
|
1992
|
-
if (live.userPermissions?.canMerge === false)
|
|
1993
|
-
request.autoMergeAvailable = false;
|
|
1994
|
-
else if (live.userPermissions?.canMerge === true && Array.isArray(live.availableAutoMergeStrategies))
|
|
1995
|
-
request.autoMergeAvailable = live.availableAutoMergeStrategies.length > 0;
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
return request;
|
|
2792
|
+
if (!result?.discussion || result.discussion.resolved !== true)
|
|
2793
|
+
throw new ForgeError("request", "Could not resolve the GitLab discussion");
|
|
2794
|
+
}
|
|
2795
|
+
findByNumber(projects, iid) {
|
|
2796
|
+
return this.source.fetchByProjects(projects, iid);
|
|
1999
2797
|
}
|
|
2000
2798
|
}
|
|
2001
2799
|
|
|
2002
2800
|
// packages/forgekeeper/src/adapters/github/adapter.ts
|
|
2003
|
-
var COPILOT_AUTHOR = "copilot-pull-request-reviewer[bot]";
|
|
2004
|
-
var fields = `number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
2005
|
-
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
2006
|
-
author { ... on User { id } ... on Bot { id } }
|
|
2007
|
-
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
2008
|
-
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
2009
|
-
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
2010
|
-
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
2011
|
-
copilotReviews: reviews(last:1, author:"${COPILOT_AUTHOR}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } author { __typename login ... on Bot { id } ... on User { id } } } }
|
|
2012
|
-
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
2013
|
-
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
2014
|
-
pageInfo { hasNextPage endCursor }
|
|
2015
|
-
} } } } }`;
|
|
2016
|
-
var MAX_PAGES = 50;
|
|
2017
2801
|
function ghGraphQL(run, cwd) {
|
|
2018
2802
|
return async (host, query, variables) => {
|
|
2019
2803
|
const args = ["api", "graphql", "--hostname", host, "-f", `query=${query}`];
|
|
@@ -2024,111 +2808,18 @@ function ghGraphQL(run, cwd) {
|
|
|
2024
2808
|
try {
|
|
2025
2809
|
body = JSON.parse(result.stdout);
|
|
2026
2810
|
} catch {
|
|
2027
|
-
throw
|
|
2811
|
+
throw classifyGitHubError(result.stderr, result.code);
|
|
2028
2812
|
}
|
|
2029
2813
|
const errors = (body.errors ?? []).filter((error) => error.type !== "NOT_FOUND");
|
|
2030
2814
|
if (!body.data || errors.length || result.code !== 0 && !body.errors?.length) {
|
|
2031
|
-
throw
|
|
2815
|
+
throw classifyGitHubError(errors[0]?.message ?? result.stderr, result.code);
|
|
2032
2816
|
}
|
|
2033
2817
|
return body.data;
|
|
2034
2818
|
};
|
|
2035
2819
|
}
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
return new ForgeError("missing-gh", "gh is not installed");
|
|
2040
|
-
if (/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(text))
|
|
2041
|
-
return new ForgeError("auth", "GitHub authentication failed. Run `gh auth status`.");
|
|
2042
|
-
if (/429|rate limit|too many requests/i.test(text))
|
|
2043
|
-
return new ForgeError("rate-limit", "GitHub rate limit reached");
|
|
2044
|
-
return new ForgeError("request", text.split(`
|
|
2045
|
-
`)[0]);
|
|
2046
|
-
}
|
|
2047
|
-
var FAILED = ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"];
|
|
2048
|
-
var CONCLUSIONS = [
|
|
2049
|
-
"SUCCESS",
|
|
2050
|
-
"NEUTRAL",
|
|
2051
|
-
"SKIPPED",
|
|
2052
|
-
"FAILURE",
|
|
2053
|
-
"TIMED_OUT",
|
|
2054
|
-
"CANCELLED",
|
|
2055
|
-
"ACTION_REQUIRED",
|
|
2056
|
-
"STARTUP_FAILURE",
|
|
2057
|
-
"STALE"
|
|
2058
|
-
];
|
|
2059
|
-
var STATES = ["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED"];
|
|
2060
|
-
var checkKey = (node) => node.__typename === "CheckRun" && node.name && node.checkSuite?.app?.id && node.checkSuite.workflowRun?.workflow?.id && JSON.stringify([node.checkSuite.app.id, node.checkSuite.workflowRun?.workflow?.id, node.name]);
|
|
2061
|
-
var checkTime = (node) => Date.parse(node.checkSuite?.createdAt ?? "");
|
|
2062
|
-
var newerCheck = (node, previous) => checkTime(node) > checkTime(previous);
|
|
2063
|
-
function checks(nodes, complete, url, id) {
|
|
2064
|
-
const latest = new Map;
|
|
2065
|
-
for (const node of nodes) {
|
|
2066
|
-
const time = checkTime(node);
|
|
2067
|
-
const key = checkKey(node);
|
|
2068
|
-
if (!key || !Number.isFinite(time))
|
|
2069
|
-
continue;
|
|
2070
|
-
const previous = latest.get(key);
|
|
2071
|
-
if (!previous || newerCheck(node, previous))
|
|
2072
|
-
latest.set(key, node);
|
|
2073
|
-
}
|
|
2074
|
-
nodes = nodes.filter((node) => {
|
|
2075
|
-
const key = checkKey(node);
|
|
2076
|
-
const replacement = key && latest.get(key);
|
|
2077
|
-
return !replacement || !newerCheck(replacement, node);
|
|
2078
|
-
});
|
|
2079
|
-
const count = (value) => `${value} check${value === 1 ? "" : "s"}`;
|
|
2080
|
-
const cancelled = nodes.filter((node) => node.conclusion === "CANCELLED").length;
|
|
2081
|
-
const stale = nodes.filter((node) => node.conclusion === "STALE").length;
|
|
2082
|
-
const stopped = [
|
|
2083
|
-
...cancelled ? [`${count(cancelled)} cancelled`] : [],
|
|
2084
|
-
...stale ? [`${count(stale)} stale`] : []
|
|
2085
|
-
];
|
|
2086
|
-
const failing = nodes.filter((node) => FAILED.includes(node.conclusion ?? node.state ?? ""));
|
|
2087
|
-
const failed = failing.length;
|
|
2088
|
-
const run = id ? {
|
|
2089
|
-
id,
|
|
2090
|
-
failedJobs: failing.flatMap((node) => {
|
|
2091
|
-
const name = node.name ?? node.context;
|
|
2092
|
-
const link = node.detailsUrl ?? node.targetUrl;
|
|
2093
|
-
return name ? [{ ...node.id ? { id: node.id } : {}, name, ...link ? { url: link } : {} }] : [];
|
|
2094
|
-
}),
|
|
2095
|
-
failedJobsComplete: complete
|
|
2096
|
-
} : {};
|
|
2097
|
-
const pending = nodes.filter((node) => node.status ? node.status !== "COMPLETED" : ["PENDING", "EXPECTED"].includes(node.state ?? "")).length;
|
|
2098
|
-
const unknown = nodes.some((node) => node.status === "COMPLETED" ? !CONCLUSIONS.includes(node.conclusion ?? "") : !node.status && !STATES.includes(node.state ?? ""));
|
|
2099
|
-
if (failed)
|
|
2100
|
-
return {
|
|
2101
|
-
status: "FAILED",
|
|
2102
|
-
label: [
|
|
2103
|
-
`${count(failed)} failed`,
|
|
2104
|
-
...stopped,
|
|
2105
|
-
...pending ? [`${count(pending)} pending`] : []
|
|
2106
|
-
].join(", ") + (complete ? "" : " (partial)"),
|
|
2107
|
-
url,
|
|
2108
|
-
...run,
|
|
2109
|
-
running: pending > 0
|
|
2110
|
-
};
|
|
2111
|
-
if (pending || !complete || unknown)
|
|
2112
|
-
return {
|
|
2113
|
-
status: "PENDING",
|
|
2114
|
-
label: [...stopped, pending ? `${count(pending)} pending` : "unknown"].join(", ") + (complete ? "" : " (partial)"),
|
|
2115
|
-
url,
|
|
2116
|
-
...run
|
|
2117
|
-
};
|
|
2118
|
-
if (cancelled || stale)
|
|
2119
|
-
return { status: "CANCELLED", label: stopped.join(", "), url, ...run };
|
|
2120
|
-
const label = [
|
|
2121
|
-
["SUCCESS", "passed"],
|
|
2122
|
-
["SKIPPED", "skipped"],
|
|
2123
|
-
["NEUTRAL", "neutral"]
|
|
2124
|
-
].flatMap(([result, text]) => {
|
|
2125
|
-
const total = nodes.filter((node) => (node.conclusion ?? node.state) === result).length;
|
|
2126
|
-
return total ? [`${count(total)} ${text}`] : [];
|
|
2127
|
-
}).join(", ");
|
|
2128
|
-
return { status: "SUCCESS", label: label || "0 checks", url, ...run };
|
|
2129
|
-
}
|
|
2130
|
-
function parseGitHubUrl(url, pattern) {
|
|
2131
|
-
const ref = parseWebUrl("github", url, pattern);
|
|
2820
|
+
var unsupportedAutoMergeHosts = new Set;
|
|
2821
|
+
function parseGitHubIssueUrl(url) {
|
|
2822
|
+
const ref = parseWebUrl("github", url, /^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/);
|
|
2132
2823
|
return ref && !gitlabTraits.recognizes(ref.host) ? ref : undefined;
|
|
2133
2824
|
}
|
|
2134
2825
|
var githubTraits = {
|
|
@@ -2137,17 +2828,14 @@ var githubTraits = {
|
|
|
2137
2828
|
fullNoun: "pull request",
|
|
2138
2829
|
ci: "checks",
|
|
2139
2830
|
recognizes: () => false,
|
|
2140
|
-
open: (run, directory) => new GitHubForge(ghGraphQL(run, directory)),
|
|
2831
|
+
open: (run, directory) => new GitHubForge(ghGraphQL(run, directory), unsupportedAutoMergeHosts),
|
|
2141
2832
|
owns: ownedBy("github"),
|
|
2142
|
-
parseUrl:
|
|
2143
|
-
parseIssueUrl:
|
|
2833
|
+
parseUrl: parseGitHubUrl,
|
|
2834
|
+
parseIssueUrl: parseGitHubIssueUrl,
|
|
2144
2835
|
reference: (iid) => `#${iid}`,
|
|
2145
2836
|
issueReference: (iid) => `#${iid}`,
|
|
2146
2837
|
titleReferences: (title) => prefixReferences(title, "#"),
|
|
2147
2838
|
hasRequestedChanges: (request) => request.changesRequested === true || request.reviewDecision === "CHANGES_REQUESTED" ? true : request.changesRequested,
|
|
2148
|
-
approvalStatus: (request) => ({
|
|
2149
|
-
reviewDecision: request.reviewDecision ?? "unknown"
|
|
2150
|
-
}),
|
|
2151
2839
|
indicators: (request) => githubTraits.hasRequestedChanges(request) === true ? [{ text: "changes requested", tone: "warning", essential: true }] : [],
|
|
2152
2840
|
details: (request) => [
|
|
2153
2841
|
`Review decision: ${request.reviewDecision ? humanize(request.reviewDecision) : "not reported"}`
|
|
@@ -2195,177 +2883,17 @@ function copilotStatus(review) {
|
|
|
2195
2883
|
return;
|
|
2196
2884
|
return { state: feedback ? "feedback" : "settled", label, completed };
|
|
2197
2885
|
}
|
|
2198
|
-
var isCopilotReviewer = (login) => /^copilot-pull-request-reviewer(\[bot\])?$/i.test(login ?? "");
|
|
2199
|
-
var isCopilotBot = (reviewer) => reviewer?.__typename === "Bot" && isCopilotReviewer(reviewer.login);
|
|
2200
|
-
function copilotReview(node) {
|
|
2201
|
-
const requested = node.reviewRequests.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
2202
|
-
const latest = node.copilotReviews?.nodes?.find((review) => review);
|
|
2203
|
-
if (!requested && !latest)
|
|
2204
|
-
return;
|
|
2205
|
-
return {
|
|
2206
|
-
requested,
|
|
2207
|
-
reviewID: latest?.id,
|
|
2208
|
-
comments: latest?.comments.totalCount ?? 0,
|
|
2209
|
-
...latest?.state === "DISMISSED" ? { dismissed: true } : {}
|
|
2210
|
-
};
|
|
2211
|
-
}
|
|
2212
|
-
function botUsername(login, typename) {
|
|
2213
|
-
return typename === "Bot" && !login.endsWith("[bot]") ? `${login}[bot]` : login;
|
|
2214
|
-
}
|
|
2215
|
-
function pendingReviewer(reviewers) {
|
|
2216
|
-
const pendingIDs = new Set;
|
|
2217
|
-
const pendingWithoutID = new Set;
|
|
2218
|
-
const pendingTypedLogins = new Set;
|
|
2219
|
-
const typedLoginKey = (typename, login) => `${typename ?? "Unknown"}:${botUsername(login, typename).toLowerCase()}`;
|
|
2220
|
-
for (const request of reviewers.nodes) {
|
|
2221
|
-
const reviewer = request.requestedReviewer;
|
|
2222
|
-
if (reviewer?.id)
|
|
2223
|
-
pendingIDs.add(reviewer.id);
|
|
2224
|
-
if (reviewer?.login) {
|
|
2225
|
-
const key = typedLoginKey(reviewer.__typename, reviewer.login);
|
|
2226
|
-
pendingTypedLogins.add(key);
|
|
2227
|
-
if (!reviewer.id)
|
|
2228
|
-
pendingWithoutID.add(key);
|
|
2229
|
-
}
|
|
2230
|
-
}
|
|
2231
|
-
return (id, typename, login) => {
|
|
2232
|
-
const key = typedLoginKey(typename, login);
|
|
2233
|
-
if (id)
|
|
2234
|
-
return pendingIDs.has(id) || pendingWithoutID.has(key);
|
|
2235
|
-
return pendingTypedLogins.has(key);
|
|
2236
|
-
};
|
|
2237
|
-
}
|
|
2238
|
-
function normalizeApprovers2(node, reviewers, opinionated) {
|
|
2239
|
-
const isPending = pendingReviewer(reviewers);
|
|
2240
|
-
const found = new Map;
|
|
2241
|
-
const add = (entry) => {
|
|
2242
|
-
const key = `${entry.bot ? "bot" : "user"}:${entry.username.toLowerCase()}`;
|
|
2243
|
-
const existing = found.get(key);
|
|
2244
|
-
if (!existing) {
|
|
2245
|
-
found.set(key, entry);
|
|
2246
|
-
return;
|
|
2247
|
-
}
|
|
2248
|
-
found.set(key, {
|
|
2249
|
-
...existing,
|
|
2250
|
-
...entry,
|
|
2251
|
-
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
2252
|
-
...existing.bot || entry.bot ? { bot: true } : {},
|
|
2253
|
-
...existing.automated || entry.automated ? { automated: true } : {},
|
|
2254
|
-
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
2255
|
-
});
|
|
2256
|
-
};
|
|
2257
|
-
for (const review of opinionated) {
|
|
2258
|
-
if (review?.state !== "APPROVED" || !review.author?.login)
|
|
2259
|
-
continue;
|
|
2260
|
-
const { id, login, __typename } = review.author;
|
|
2261
|
-
if (isPending(id, __typename, login))
|
|
2262
|
-
continue;
|
|
2263
|
-
const bot = __typename === "Bot";
|
|
2264
|
-
const automated = bot && isCopilotReviewer(login);
|
|
2265
|
-
const username = automated ? COPILOT_AUTHOR : botUsername(login, __typename);
|
|
2266
|
-
add({
|
|
2267
|
-
...id ? { id } : {},
|
|
2268
|
-
username,
|
|
2269
|
-
...bot ? { bot: true } : {},
|
|
2270
|
-
...automated ? { automated: true } : {},
|
|
2271
|
-
...review.id ? { reviewID: review.id } : {}
|
|
2272
|
-
});
|
|
2273
|
-
}
|
|
2274
|
-
const latestCopilot = node.copilotReviews?.nodes?.find((review) => review);
|
|
2275
|
-
const copilotPending = reviewers.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
2276
|
-
if (latestCopilot?.state === "APPROVED" && isCopilotBot(latestCopilot.author) && !copilotPending) {
|
|
2277
|
-
add({
|
|
2278
|
-
...latestCopilot.author?.id ? { id: latestCopilot.author.id } : {},
|
|
2279
|
-
username: COPILOT_AUTHOR,
|
|
2280
|
-
bot: true,
|
|
2281
|
-
automated: true,
|
|
2282
|
-
...latestCopilot.id ? { reviewID: latestCopilot.id } : {}
|
|
2283
|
-
});
|
|
2284
|
-
}
|
|
2285
|
-
return [...found.values()];
|
|
2286
|
-
}
|
|
2287
|
-
function changeRequests(reviewers, opinionated) {
|
|
2288
|
-
if (!reviewers.pageInfo || reviewers.pageInfo.hasNextPage)
|
|
2289
|
-
return {};
|
|
2290
|
-
const pending = pendingReviewer(reviewers);
|
|
2291
|
-
const ids = [];
|
|
2292
|
-
let complete = opinionated.complete;
|
|
2293
|
-
for (const review of opinionated.nodes) {
|
|
2294
|
-
if (review?.state !== "CHANGES_REQUESTED")
|
|
2295
|
-
continue;
|
|
2296
|
-
const author = review.author;
|
|
2297
|
-
if (!author?.login || !review.id) {
|
|
2298
|
-
complete = false;
|
|
2299
|
-
continue;
|
|
2300
|
-
}
|
|
2301
|
-
if (!pending(author.id, author.__typename, author.login))
|
|
2302
|
-
ids.push(review.id);
|
|
2303
|
-
}
|
|
2304
|
-
if (ids.length)
|
|
2305
|
-
return { changesRequested: true, changeReviewIDs: ids };
|
|
2306
|
-
return complete ? { changesRequested: false } : {};
|
|
2307
|
-
}
|
|
2308
2886
|
|
|
2309
2887
|
class GitHubForge {
|
|
2310
|
-
traits = githubTraits;
|
|
2311
|
-
graphql;
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
for (let page = 0;page < MAX_PAGES; page++) {
|
|
2320
|
-
const response = await this.graphql(host, query(`query($owner:String!,$repo:String!,$branch:String!,$after:String) {
|
|
2321
|
-
repository(owner:$owner,name:$repo) {
|
|
2322
|
-
ref(qualifiedName:$branch) {
|
|
2323
|
-
branchProtectionRule { requiresConversationResolution }
|
|
2324
|
-
rules(first:50,after:$after) {
|
|
2325
|
-
nodes { type repositoryRuleset { enforcement } parameters { ... on PullRequestParameters { requiredReviewThreadResolution } } }
|
|
2326
|
-
pageInfo { hasNextPage endCursor }
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
}
|
|
2330
|
-
}`), { owner, repo, branch: `refs/heads/${node.baseRefName}`, ...after ? { after } : {} }).catch(() => {
|
|
2331
|
-
return;
|
|
2332
|
-
});
|
|
2333
|
-
const ref = response?.repository?.ref;
|
|
2334
|
-
if (ref?.branchProtectionRule?.requiresConversationResolution)
|
|
2335
|
-
return true;
|
|
2336
|
-
const rules = ref?.rules;
|
|
2337
|
-
if (!rules?.pageInfo)
|
|
2338
|
-
return;
|
|
2339
|
-
for (const rule of rules.nodes) {
|
|
2340
|
-
if (rule.type !== "PULL_REQUEST")
|
|
2341
|
-
continue;
|
|
2342
|
-
const required = rule.parameters?.requiredReviewThreadResolution;
|
|
2343
|
-
const enforcement = rule.repositoryRuleset?.enforcement;
|
|
2344
|
-
if (enforcement === "ACTIVE" && required === true)
|
|
2345
|
-
return true;
|
|
2346
|
-
if (!enforcement || required === undefined)
|
|
2347
|
-
unknown = true;
|
|
2348
|
-
}
|
|
2349
|
-
if (!rules.pageInfo.hasNextPage)
|
|
2350
|
-
return unknown ? undefined : false;
|
|
2351
|
-
const cursor = rules.pageInfo.endCursor;
|
|
2352
|
-
if (!cursor || cursor === after)
|
|
2353
|
-
return;
|
|
2354
|
-
after = cursor;
|
|
2355
|
-
}
|
|
2356
|
-
return;
|
|
2357
|
-
}
|
|
2358
|
-
async findByNumber(projects, number) {
|
|
2359
|
-
for (const project of projects) {
|
|
2360
|
-
const [owner, repo] = project.path.split("/");
|
|
2361
|
-
const data = await this.graphql(project.host, query(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
2362
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${fields} } }
|
|
2363
|
-
}`), { owner, repo, number: Number(number) });
|
|
2364
|
-
const node = data.repository?.pullRequest;
|
|
2365
|
-
if (node)
|
|
2366
|
-
return this.normalize(project.host, node);
|
|
2367
|
-
}
|
|
2368
|
-
return;
|
|
2888
|
+
traits = githubTraits;
|
|
2889
|
+
graphql;
|
|
2890
|
+
source;
|
|
2891
|
+
constructor(graphql, unsupportedAutoMerge = new Set) {
|
|
2892
|
+
this.graphql = typed(graphql);
|
|
2893
|
+
this.source = createGitHubSource(graphql, { unsupportedAutoMerge });
|
|
2894
|
+
}
|
|
2895
|
+
findByNumber(projects, number) {
|
|
2896
|
+
return this.source.fetchByProjects(projects, number);
|
|
2369
2897
|
}
|
|
2370
2898
|
async findNumberByBranch(repository) {
|
|
2371
2899
|
let newest;
|
|
@@ -2520,87 +3048,11 @@ class GitHubForge {
|
|
|
2520
3048
|
if (!updated || updated.isDraft)
|
|
2521
3049
|
throw new ForgeError("request", "Could not mark the GitHub pull request as ready");
|
|
2522
3050
|
}
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
const number = Number(ref.iid);
|
|
2526
|
-
if (!owner || !repo || !Number.isInteger(number) || number < 1)
|
|
2527
|
-
return;
|
|
2528
|
-
const list = await discussionPages(MAX_PAGES, async (after) => {
|
|
2529
|
-
const data = await this.graphql(ref.host, query(`query($owner:String!,$repo:String!,$number:Int!${after ? ",$after:String!" : ""}) {
|
|
2530
|
-
repository(owner:$owner,name:$repo) {
|
|
2531
|
-
pullRequest(number:$number) {
|
|
2532
|
-
reviewThreads(first:100${after ? ",after:$after" : ""}) {
|
|
2533
|
-
nodes { id isResolved }
|
|
2534
|
-
pageInfo { hasNextPage endCursor }
|
|
2535
|
-
}
|
|
2536
|
-
}
|
|
2537
|
-
}
|
|
2538
|
-
}`), { owner, repo, number, ...after ? { after } : {} });
|
|
2539
|
-
return data.repository?.pullRequest?.reviewThreads;
|
|
2540
|
-
});
|
|
2541
|
-
const discussions = [];
|
|
2542
|
-
const candidates = list.nodes.filter(({ id, isResolved }) => id && !isResolved);
|
|
2543
|
-
for (const { id } of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
2544
|
-
const thread = await this.discussion(ref, { id }).catch(() => {
|
|
2545
|
-
return;
|
|
2546
|
-
});
|
|
2547
|
-
if (thread !== "resolved")
|
|
2548
|
-
discussions.push(thread ?? { id, notes: [], incomplete: true });
|
|
2549
|
-
}
|
|
2550
|
-
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
3051
|
+
unresolvedDiscussions(ref) {
|
|
3052
|
+
return this.source.unresolvedDiscussions(ref);
|
|
2551
3053
|
}
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
const replies = await discussionPages(10, async (after) => {
|
|
2555
|
-
const data = await this.graphql(ref.host, query(`
|
|
2556
|
-
query($id:ID!,$after:String) {
|
|
2557
|
-
node(id:$id) { ... on PullRequestReviewThread {
|
|
2558
|
-
id isResolved path line pullRequest { url }
|
|
2559
|
-
comments(first:20,after:$after) {
|
|
2560
|
-
pageInfo { hasNextPage endCursor }
|
|
2561
|
-
nodes { id url body createdAt isMinimized author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
2562
|
-
}
|
|
2563
|
-
} }
|
|
2564
|
-
}`), { id, ...after ? { after } : {} });
|
|
2565
|
-
const candidate = data.node;
|
|
2566
|
-
const owner = candidate?.pullRequest && githubTraits.parseUrl(candidate.pullRequest.url);
|
|
2567
|
-
if (!candidate || candidate.id !== id || !owner || owner.host !== ref.host || owner.project.toLowerCase() !== ref.project.toLowerCase() || owner.iid !== ref.iid) {
|
|
2568
|
-
thread = undefined;
|
|
2569
|
-
return;
|
|
2570
|
-
}
|
|
2571
|
-
thread = candidate;
|
|
2572
|
-
return thread.isResolved ? undefined : thread.comments;
|
|
2573
|
-
});
|
|
2574
|
-
if (!thread)
|
|
2575
|
-
return;
|
|
2576
|
-
if (thread.isResolved)
|
|
2577
|
-
return "resolved";
|
|
2578
|
-
const notes = [];
|
|
2579
|
-
let incomplete = !replies.complete;
|
|
2580
|
-
for (const comment of replies.nodes) {
|
|
2581
|
-
const author = comment.author;
|
|
2582
|
-
if (!comment.id || comment.isMinimized || !author?.login || typeof comment.body !== "string") {
|
|
2583
|
-
incomplete = true;
|
|
2584
|
-
continue;
|
|
2585
|
-
}
|
|
2586
|
-
notes.push({
|
|
2587
|
-
id: comment.id,
|
|
2588
|
-
url: comment.url,
|
|
2589
|
-
authorID: author.id,
|
|
2590
|
-
username: botUsername(author.login, author.__typename),
|
|
2591
|
-
bot: author.__typename === "Bot" || author.login.endsWith("[bot]"),
|
|
2592
|
-
body: comment.body,
|
|
2593
|
-
createdAt: comment.createdAt,
|
|
2594
|
-
path: thread.path ?? undefined,
|
|
2595
|
-
line: thread.line ?? undefined
|
|
2596
|
-
});
|
|
2597
|
-
}
|
|
2598
|
-
return {
|
|
2599
|
-
id,
|
|
2600
|
-
notes,
|
|
2601
|
-
url: notes.find((note) => note.url)?.url,
|
|
2602
|
-
incomplete: incomplete || notes.length === 0
|
|
2603
|
-
};
|
|
3054
|
+
discussion(ref, thread) {
|
|
3055
|
+
return this.source.discussion(ref, thread);
|
|
2604
3056
|
}
|
|
2605
3057
|
async resolveDiscussion(ref, discussionID, options) {
|
|
2606
3058
|
await options?.beforeMutate?.();
|
|
@@ -2611,175 +3063,8 @@ class GitHubForge {
|
|
|
2611
3063
|
if (!thread || !thread.isResolved)
|
|
2612
3064
|
throw new ForgeError("request", "Could not resolve the GitHub review thread");
|
|
2613
3065
|
}
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
for (const target of repository.targets) {
|
|
2617
|
-
const [owner, repo] = target.path.split("/");
|
|
2618
|
-
let after;
|
|
2619
|
-
let complete = false;
|
|
2620
|
-
for (let page = 0;page < MAX_PAGES; page++) {
|
|
2621
|
-
const data = await this.graphql(target.host, query(`query($owner:String!,$repo:String!,$branch:String!${after ? ",$after:String!" : ""}) {
|
|
2622
|
-
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${after ? ",after:$after" : ""}) {
|
|
2623
|
-
nodes { ${fields} } pageInfo { hasNextPage endCursor }
|
|
2624
|
-
} } }`), { owner, repo, branch: repository.sourceBranch, ...after ? { after } : {} });
|
|
2625
|
-
const pulls = data.repository?.pullRequests;
|
|
2626
|
-
if (!pulls)
|
|
2627
|
-
throw new ForgeError("request", "GitHub repository unavailable");
|
|
2628
|
-
for (const node of pulls.nodes) {
|
|
2629
|
-
if (node.headRepository?.nameWithOwner.toLowerCase() !== repository.source.path.toLowerCase())
|
|
2630
|
-
continue;
|
|
2631
|
-
if (!found.has(node.url))
|
|
2632
|
-
found.set(node.url, await this.normalize(target.host, node));
|
|
2633
|
-
}
|
|
2634
|
-
if (!pulls.pageInfo?.hasNextPage) {
|
|
2635
|
-
complete = true;
|
|
2636
|
-
break;
|
|
2637
|
-
}
|
|
2638
|
-
after = pulls.pageInfo.endCursor;
|
|
2639
|
-
if (!after)
|
|
2640
|
-
break;
|
|
2641
|
-
}
|
|
2642
|
-
if (!complete)
|
|
2643
|
-
throw new ForgeError("request", "GitHub PR discovery exceeded its pagination limit");
|
|
2644
|
-
}
|
|
2645
|
-
return [...found.values()].sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
2646
|
-
}
|
|
2647
|
-
async threads(host, node) {
|
|
2648
|
-
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
2649
|
-
const threads = [...node.reviewThreads.nodes];
|
|
2650
|
-
let page = node.reviewThreads.pageInfo;
|
|
2651
|
-
for (let count = 1;page?.hasNextPage && page.endCursor && count < MAX_PAGES; count++) {
|
|
2652
|
-
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
2653
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
2654
|
-
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
2655
|
-
} } }`), { owner, repo, number: node.number, after: page.endCursor });
|
|
2656
|
-
const next = data.repository?.pullRequest?.reviewThreads;
|
|
2657
|
-
if (!next)
|
|
2658
|
-
break;
|
|
2659
|
-
threads.push(...next.nodes);
|
|
2660
|
-
page = next.pageInfo;
|
|
2661
|
-
}
|
|
2662
|
-
return {
|
|
2663
|
-
unresolved: threads.filter((thread) => !thread.isResolved).length,
|
|
2664
|
-
complete: !page?.hasNextPage
|
|
2665
|
-
};
|
|
2666
|
-
}
|
|
2667
|
-
async contexts(host, node) {
|
|
2668
|
-
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
2669
|
-
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
|
|
2670
|
-
const contexts = [...rollup?.nodes ?? []];
|
|
2671
|
-
let cursor = rollup?.pageInfo;
|
|
2672
|
-
for (let count = 1;cursor?.hasNextPage && cursor.endCursor && count < MAX_PAGES; count++) {
|
|
2673
|
-
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
2674
|
-
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
2675
|
-
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
2676
|
-
} } } } }`), { owner, repo, oid: node.headRefOid, after: cursor.endCursor });
|
|
2677
|
-
const next = data.repository?.object?.statusCheckRollup?.contexts;
|
|
2678
|
-
if (!next)
|
|
2679
|
-
break;
|
|
2680
|
-
contexts.push(...next.nodes);
|
|
2681
|
-
cursor = next.pageInfo;
|
|
2682
|
-
}
|
|
2683
|
-
return { nodes: contexts, complete: !cursor?.hasNextPage };
|
|
2684
|
-
}
|
|
2685
|
-
async reviewers(host, node) {
|
|
2686
|
-
const nodes = [...node.reviewRequests.nodes];
|
|
2687
|
-
let reviewerPage = node.reviewRequests.pageInfo;
|
|
2688
|
-
for (let count = 1;reviewerPage?.hasNextPage && count < MAX_PAGES; count++) {
|
|
2689
|
-
if (!reviewerPage.endCursor)
|
|
2690
|
-
throw new ForgeError("request", "GitHub reviewer pagination cursor missing");
|
|
2691
|
-
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
2692
|
-
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
2693
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
2694
|
-
reviewRequests(first:100,after:$after) {
|
|
2695
|
-
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
2696
|
-
pageInfo { hasNextPage endCursor }
|
|
2697
|
-
}
|
|
2698
|
-
} }
|
|
2699
|
-
}`), { owner, repo, number: node.number, after: reviewerPage.endCursor });
|
|
2700
|
-
const next = data.repository?.pullRequest?.reviewRequests;
|
|
2701
|
-
if (!next)
|
|
2702
|
-
throw new ForgeError("request", "GitHub reviewers unavailable");
|
|
2703
|
-
nodes.push(...next.nodes);
|
|
2704
|
-
reviewerPage = next.pageInfo;
|
|
2705
|
-
}
|
|
2706
|
-
if (reviewerPage?.hasNextPage)
|
|
2707
|
-
throw new ForgeError("request", "GitHub reviewers exceeded the pagination limit");
|
|
2708
|
-
return { nodes, pageInfo: reviewerPage };
|
|
2709
|
-
}
|
|
2710
|
-
async opinionatedReviews(host, node) {
|
|
2711
|
-
if (!node.latestOpinionatedReviews?.pageInfo)
|
|
2712
|
-
return { nodes: [...node.latestOpinionatedReviews?.nodes ?? []], complete: false };
|
|
2713
|
-
const nodes = [...node.latestOpinionatedReviews.nodes];
|
|
2714
|
-
let page = node.latestOpinionatedReviews.pageInfo;
|
|
2715
|
-
for (let count = 1;page.hasNextPage && page.endCursor && count < MAX_PAGES; count++) {
|
|
2716
|
-
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
2717
|
-
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
2718
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
2719
|
-
latestOpinionatedReviews(first:100,after:$after) {
|
|
2720
|
-
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
2721
|
-
pageInfo { hasNextPage endCursor }
|
|
2722
|
-
}
|
|
2723
|
-
} }
|
|
2724
|
-
}`), { owner, repo, number: node.number, after: page.endCursor });
|
|
2725
|
-
const next = data.repository?.pullRequest?.latestOpinionatedReviews;
|
|
2726
|
-
if (!next?.pageInfo)
|
|
2727
|
-
return { nodes, complete: false };
|
|
2728
|
-
nodes.push(...next.nodes);
|
|
2729
|
-
page = next.pageInfo;
|
|
2730
|
-
}
|
|
2731
|
-
return { nodes, complete: !page.hasNextPage };
|
|
2732
|
-
}
|
|
2733
|
-
async normalize(host, node) {
|
|
2734
|
-
const reviewers = await this.reviewers(host, node);
|
|
2735
|
-
const [threads, contexts, opinionated] = await Promise.all([
|
|
2736
|
-
this.threads(host, node),
|
|
2737
|
-
this.contexts(host, node),
|
|
2738
|
-
this.opinionatedReviews(host, node)
|
|
2739
|
-
]);
|
|
2740
|
-
const changes = changeRequests(reviewers, opinionated);
|
|
2741
|
-
const awaitingReviewers = reviewers.nodes.flatMap((request) => {
|
|
2742
|
-
const reviewer = request.requestedReviewer;
|
|
2743
|
-
if (reviewer?.__typename === "Bot")
|
|
2744
|
-
return [];
|
|
2745
|
-
const name = reviewer?.login || reviewer?.name;
|
|
2746
|
-
return name ? [name] : [];
|
|
2747
|
-
});
|
|
2748
|
-
return {
|
|
2749
|
-
forge: "github",
|
|
2750
|
-
iid: String(node.number),
|
|
2751
|
-
title: node.title,
|
|
2752
|
-
url: node.url,
|
|
2753
|
-
state: node.state === "OPEN" ? "opened" : node.state.toLowerCase(),
|
|
2754
|
-
draft: node.isDraft,
|
|
2755
|
-
conflicts: node.mergeable === "CONFLICTING",
|
|
2756
|
-
conflictsKnown: node.mergeable !== "UNKNOWN",
|
|
2757
|
-
approved: node.reviewDecision === "APPROVED" && awaitingReviewers.length === 0 && changes.changesRequested !== true,
|
|
2758
|
-
reviewDecision: node.reviewDecision ?? undefined,
|
|
2759
|
-
...changes,
|
|
2760
|
-
copilotReview: copilotReview({ ...node, reviewRequests: reviewers }),
|
|
2761
|
-
awaitingReviewers,
|
|
2762
|
-
reviewersComplete: !!reviewers.pageInfo && !reviewers.pageInfo.hasNextPage,
|
|
2763
|
-
approvalsComplete: !!reviewers.pageInfo && !reviewers.pageInfo.hasNextPage && opinionated.complete,
|
|
2764
|
-
reviewerIDs: [
|
|
2765
|
-
...new Set([
|
|
2766
|
-
...reviewers.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" ? request.requestedReviewer.id ?? [] : []),
|
|
2767
|
-
...[...node.latestReviews?.nodes ?? [], ...opinionated.nodes].flatMap((review) => !review?.author?.__typename || review.author.__typename === "User" ? review?.author?.id ?? [] : [])
|
|
2768
|
-
])
|
|
2769
|
-
],
|
|
2770
|
-
approvers: normalizeApprovers2(node, reviewers, opinionated.nodes),
|
|
2771
|
-
targetProject: node.baseRepository.nameWithOwner,
|
|
2772
|
-
targetBranch: node.baseRefName,
|
|
2773
|
-
...node.headRepository ? { sourceProject: node.headRepository.nameWithOwner } : {},
|
|
2774
|
-
sourceBranch: node.headRefName,
|
|
2775
|
-
headSha: node.headRefOid,
|
|
2776
|
-
...node.author?.id ? { authorID: node.author.id } : {},
|
|
2777
|
-
updatedAt: node.updatedAt,
|
|
2778
|
-
pipeline: contexts.nodes.length || !contexts.complete ? checks(contexts.nodes, contexts.complete, `${node.url}/checks`, node.headRefOid) : undefined,
|
|
2779
|
-
unresolvedThreads: threads.unresolved,
|
|
2780
|
-
discussionResolutionRequired: threads.unresolved > 0 ? await this.discussionRequirement(host, node) : undefined,
|
|
2781
|
-
threadsComplete: threads.complete
|
|
2782
|
-
};
|
|
3066
|
+
findByBranch(repository) {
|
|
3067
|
+
return this.source.fetchByBranch(repository.source, repository.targets, repository.sourceBranch);
|
|
2783
3068
|
}
|
|
2784
3069
|
}
|
|
2785
3070
|
|
|
@@ -2788,32 +3073,6 @@ var registry = { gitlab: gitlabTraits, github: githubTraits };
|
|
|
2788
3073
|
var kinds = Object.keys(registry);
|
|
2789
3074
|
var traitsOf = (request) => registry[request.forge];
|
|
2790
3075
|
var reference = (request) => traitsOf(request).reference(request.iid);
|
|
2791
|
-
function discussionBlocker(request) {
|
|
2792
|
-
if (request.discussionResolutionRequired === false)
|
|
2793
|
-
return "none";
|
|
2794
|
-
if (request.unresolvedThreads > 0)
|
|
2795
|
-
return request.discussionResolutionRequired === true ? "threads" : undefined;
|
|
2796
|
-
return request.threadsComplete ? "none" : undefined;
|
|
2797
|
-
}
|
|
2798
|
-
function mergeBlockedState(request) {
|
|
2799
|
-
if (request.state !== "opened" || request.draft)
|
|
2800
|
-
return "none";
|
|
2801
|
-
if (!approvalsComplete(request) || !request.conflictsKnown)
|
|
2802
|
-
return;
|
|
2803
|
-
const forgeTraits = traitsOf(request);
|
|
2804
|
-
if (forgeTraits.automatedReview?.status(request)?.state === "running")
|
|
2805
|
-
return;
|
|
2806
|
-
const satisfied = forgeTraits.approvalsSatisfied ? forgeTraits.approvalsSatisfied(request) : request.approved && request.awaitingReviewers.length === 0;
|
|
2807
|
-
if (!satisfied || request.conflicts || changesRequestedState(request) === true)
|
|
2808
|
-
return "none";
|
|
2809
|
-
if (pipelineFails(request.pipeline) || request.pipeline?.status === "FAILED")
|
|
2810
|
-
return "none";
|
|
2811
|
-
return forgeTraits.mergeBlocker?.(request) ?? discussionBlocker(request);
|
|
2812
|
-
}
|
|
2813
|
-
function mergeBlockedReason(request) {
|
|
2814
|
-
const state = mergeBlockedState(request);
|
|
2815
|
-
return state === "none" ? undefined : state;
|
|
2816
|
-
}
|
|
2817
3076
|
function sharedForge(forges) {
|
|
2818
3077
|
const unique = new Set;
|
|
2819
3078
|
for (const forge of forges) {
|
|
@@ -2983,36 +3242,6 @@ function snapshotForge(snapshot, fallback) {
|
|
|
2983
3242
|
function hasThreadReviewItem(items, url) {
|
|
2984
3243
|
return items.some((item) => item.url === url && canReviewBlockingThreads(item));
|
|
2985
3244
|
}
|
|
2986
|
-
function mergeNextStep(request, options = {}) {
|
|
2987
|
-
if (mergeBlockedReason(request) === "threads") {
|
|
2988
|
-
const offerAutoMergeAfterThreads = request.forge === "gitlab" && request.autoMergeEnabled === false && request.mergeTrainIndex == null;
|
|
2989
|
-
const base = offerAutoMergeAfterThreads ? "Resolve the blocking threads, then select Set to auto-merge in GitLab when available." : "Resolve the blocking threads.";
|
|
2990
|
-
const shortcut = options.canReviewThreads ? " In /forge-feedback, select the merge-blocked item and choose Review blocking threads." : "";
|
|
2991
|
-
return {
|
|
2992
|
-
text: offerAutoMergeAfterThreads ? "resolve threads \u2192 Set to auto-merge" : "resolve threads",
|
|
2993
|
-
compact: offerAutoMergeAfterThreads ? "threads \u2192 auto-merge" : "resolve threads",
|
|
2994
|
-
tone: "warning",
|
|
2995
|
-
essential: true,
|
|
2996
|
-
detail: `${base}${shortcut}`
|
|
2997
|
-
};
|
|
2998
|
-
}
|
|
2999
|
-
if (traitsOf(request).readyToMerge?.(request) === true) {
|
|
3000
|
-
return {
|
|
3001
|
-
text: "Set to auto-merge",
|
|
3002
|
-
tone: "warning",
|
|
3003
|
-
essential: true,
|
|
3004
|
-
url: request.url,
|
|
3005
|
-
detail: "Open the merge request in GitLab and select Set to auto-merge."
|
|
3006
|
-
};
|
|
3007
|
-
}
|
|
3008
|
-
return;
|
|
3009
|
-
}
|
|
3010
|
-
function newestRequestsFirst(requests) {
|
|
3011
|
-
return requests.map((request) => {
|
|
3012
|
-
const updatedAt = Date.parse(request.updatedAt ?? "");
|
|
3013
|
-
return { request, updatedAt: Number.isNaN(updatedAt) ? Number.MIN_SAFE_INTEGER : updatedAt };
|
|
3014
|
-
}).sort((a, b) => b.updatedAt - a.updatedAt).map(({ request }) => request);
|
|
3015
|
-
}
|
|
3016
3245
|
var RUNNING = new Set([
|
|
3017
3246
|
"CREATED",
|
|
3018
3247
|
"WAITING_FOR_RESOURCE",
|
|
@@ -3083,7 +3312,10 @@ function targetsSummary(requests) {
|
|
|
3083
3312
|
const blockers = open.map(mergeBlockedReason);
|
|
3084
3313
|
const threadBlocked = blockers.filter((reason) => reason === "threads").length;
|
|
3085
3314
|
const blocked = blockers.filter((reason) => reason && reason !== "threads").length;
|
|
3086
|
-
const
|
|
3315
|
+
const readyStates = open.map((request) => traitsOf(request).readyToMergeState?.(request)).filter((state) => state !== undefined && state !== "none");
|
|
3316
|
+
const mergeReady = readyStates.filter((state) => state === "merge").length;
|
|
3317
|
+
const maintainerReady = readyStates.filter((state) => state === "maintainer-merge").length;
|
|
3318
|
+
const autoMergeReady = readyStates.filter((state) => state === "auto-merge").length;
|
|
3087
3319
|
if (threadBlocked)
|
|
3088
3320
|
segments.push({
|
|
3089
3321
|
text: `${threadBlocked} ${threadBlocked === 1 ? "needs" : "need"} threads resolved`,
|
|
@@ -3091,9 +3323,21 @@ function targetsSummary(requests) {
|
|
|
3091
3323
|
tone: "warning",
|
|
3092
3324
|
essential: true
|
|
3093
3325
|
});
|
|
3094
|
-
if (
|
|
3326
|
+
if (mergeReady)
|
|
3327
|
+
segments.push({
|
|
3328
|
+
text: `${mergeReady} ready to merge`,
|
|
3329
|
+
tone: "warning",
|
|
3330
|
+
essential: true
|
|
3331
|
+
});
|
|
3332
|
+
if (maintainerReady)
|
|
3333
|
+
segments.push({
|
|
3334
|
+
text: `${maintainerReady} ${maintainerReady === 1 ? "needs" : "need"} maintainer merge`,
|
|
3335
|
+
tone: "warning",
|
|
3336
|
+
essential: true
|
|
3337
|
+
});
|
|
3338
|
+
if (autoMergeReady)
|
|
3095
3339
|
segments.push({
|
|
3096
|
-
text: `${
|
|
3340
|
+
text: `${autoMergeReady} ${autoMergeReady === 1 ? "needs" : "need"} auto-merge`,
|
|
3097
3341
|
tone: "warning",
|
|
3098
3342
|
essential: true
|
|
3099
3343
|
});
|
|
@@ -3708,9 +3952,6 @@ function connectStatus(rpc, options) {
|
|
|
3708
3952
|
}
|
|
3709
3953
|
var clientID = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
3710
3954
|
|
|
3711
|
-
// packages/forgekeeper/src/approval-watch.ts
|
|
3712
|
-
var APPROVAL_RETENTION = 30 * 24 * 60 * 60000;
|
|
3713
|
-
|
|
3714
3955
|
// packages/forgekeeper/src/review-preparation.ts
|
|
3715
3956
|
var PREPARE_PREFIX = `${MESSAGE_PREFIX}prepare_`;
|
|
3716
3957
|
var APPROVAL_STATUS_TOOL = "forgekeeper_approval_status";
|