opencode-forgekeeper 6.2.1 → 6.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/gui-experimental.cjs +173 -172
- package/dist/index.js +3376 -3195
- package/dist/tui.js +1471 -1337
- 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,241 @@ 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 readyToMerge(request) {
|
|
142
|
+
const candidate = autoMergeCandidate(request);
|
|
143
|
+
return candidate === true ? request.autoMergeAvailable : candidate;
|
|
144
|
+
}
|
|
145
|
+
function requestReadyToMerge(request) {
|
|
146
|
+
return request.forge === "gitlab" ? readyToMerge(request) : undefined;
|
|
147
|
+
}
|
|
148
|
+
function gitlabMergeStatusBlocker(mergeStatus) {
|
|
149
|
+
switch (mergeStatus) {
|
|
150
|
+
case "NEED_REBASE":
|
|
151
|
+
return "rebase";
|
|
152
|
+
case "JIRA_ASSOCIATION_MISSING":
|
|
153
|
+
return "jira";
|
|
154
|
+
case "EXTERNAL_STATUS_CHECKS":
|
|
155
|
+
return "status-checks";
|
|
156
|
+
case "BLOCKED_STATUS":
|
|
157
|
+
return "blocked";
|
|
158
|
+
default:
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function hasUnresolvedThreads(request) {
|
|
163
|
+
return request.mergeStatus === "DISCUSSIONS_NOT_RESOLVED" || request.discussionResolutionRequired === true && request.unresolvedThreads > 0;
|
|
164
|
+
}
|
|
165
|
+
function autoMergeDetail(request) {
|
|
166
|
+
if (hasUnresolvedThreads(request))
|
|
167
|
+
return "Auto-merge: set (blocked by unresolved threads)";
|
|
168
|
+
if (gitlabMergeStatusBlocker(request.mergeStatus) && request.mergeStatus) {
|
|
169
|
+
return `Auto-merge: set (blocked: ${humanize(request.mergeStatus)})`;
|
|
170
|
+
}
|
|
171
|
+
return "Auto-merge: set";
|
|
172
|
+
}
|
|
173
|
+
function manualBlockerIndicator(blocker) {
|
|
174
|
+
switch (blocker) {
|
|
175
|
+
case "rebase":
|
|
176
|
+
return { text: "needs rebase", tone: "warning", optional: true };
|
|
177
|
+
case "jira":
|
|
178
|
+
return { text: "missing Jira issue", tone: "warning", optional: true };
|
|
179
|
+
case "status-checks":
|
|
180
|
+
return { text: "status checks pending", tone: "warning", optional: true };
|
|
181
|
+
case "blocked":
|
|
182
|
+
return { text: "merge blocked", tone: "warning", optional: true };
|
|
183
|
+
default:
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function needsApproval(request) {
|
|
188
|
+
return (request.missingRules?.length ?? 0) > 0 || (request.approvalsLeft ?? 0) > 0 || request.mergeStatus === "NOT_APPROVED";
|
|
189
|
+
}
|
|
190
|
+
function approvalsSatisfied(request) {
|
|
191
|
+
if (needsApproval(request))
|
|
192
|
+
return false;
|
|
193
|
+
return request.approvalRequirementsSatisfied ?? (request.approved && request.awaitingReviewers.length === 0);
|
|
194
|
+
}
|
|
195
|
+
function requestApprovalsSatisfied(request) {
|
|
196
|
+
if (request.forge === "gitlab")
|
|
197
|
+
return approvalsSatisfied(request);
|
|
198
|
+
return request.approved && request.awaitingReviewers.length === 0;
|
|
199
|
+
}
|
|
200
|
+
function mergeBlocker(request) {
|
|
201
|
+
if (hasUnresolvedThreads(request))
|
|
202
|
+
return "threads";
|
|
203
|
+
return gitlabMergeStatusBlocker(request.mergeStatus);
|
|
204
|
+
}
|
|
205
|
+
function canProceedToMerge(request) {
|
|
206
|
+
return !request.conflicts && request.pipeline?.status !== "FAILED";
|
|
207
|
+
}
|
|
208
|
+
function hasAutoMergeReadyApprovals(request) {
|
|
209
|
+
return Boolean(request.autoMergeEnabled) && !needsApproval(request) && (request.approvalRequirementsSatisfied === true || request.mergeStatus === "MERGEABLE");
|
|
210
|
+
}
|
|
211
|
+
function approvalCount(request) {
|
|
212
|
+
const left = request.approvalsLeft ?? 0;
|
|
213
|
+
if (left <= 0 || request.approvalRequirementsSatisfied === true)
|
|
214
|
+
return;
|
|
215
|
+
const given = approversOf(request).filter((approver) => !approver.bot).length;
|
|
216
|
+
return {
|
|
217
|
+
text: given ? `${given} approval${given === 1 ? "" : "s"} \xB7 ${left} more needed` : `${left} approval${left === 1 ? "" : "s"} needed`,
|
|
218
|
+
compact: given ? `${given} \u2713 +${left}` : `+${left}`,
|
|
219
|
+
tone: "muted",
|
|
220
|
+
optional: true
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function waitingOn(request) {
|
|
224
|
+
const awaiting = request.awaitingReviewers.length ? { text: awaitingText(request.awaitingReviewers), tone: "muted" } : undefined;
|
|
225
|
+
if (awaiting && !approvalsSatisfied(request))
|
|
226
|
+
return awaiting;
|
|
227
|
+
if (request.draft || request.changesRequested === true)
|
|
228
|
+
return awaiting;
|
|
229
|
+
const statusBlocker = gitlabMergeStatusBlocker(request.mergeStatus);
|
|
230
|
+
if (canProceedToMerge(request)) {
|
|
231
|
+
if (request.mergeTrainIndex != null)
|
|
232
|
+
return { text: `merge train #${request.mergeTrainIndex + 1}`, tone: "muted", optional: true };
|
|
233
|
+
if (hasAutoMergeReadyApprovals(request)) {
|
|
234
|
+
if (hasUnresolvedThreads(request) || statusBlocker)
|
|
235
|
+
return {
|
|
236
|
+
text: "auto-merge blocked",
|
|
237
|
+
compact: "auto-merge \u26D4",
|
|
238
|
+
tone: "warning",
|
|
239
|
+
optional: true
|
|
240
|
+
};
|
|
241
|
+
return awaiting ?? { text: "auto-merge set", tone: "success", optional: true };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (request.approved || request.approvalRequirementsSatisfied === true) {
|
|
245
|
+
if (canProceedToMerge(request) && !needsApproval(request)) {
|
|
246
|
+
if (hasUnresolvedThreads(request))
|
|
247
|
+
return { text: "merge blocked", tone: "warning", optional: true };
|
|
248
|
+
return manualBlockerIndicator(statusBlocker) ?? awaiting;
|
|
249
|
+
}
|
|
250
|
+
return awaiting;
|
|
251
|
+
}
|
|
252
|
+
const missingRules = request.missingRules ?? [];
|
|
253
|
+
const rule = missingRules.find((item) => item.type === "CODE_OWNER" || item.type === "REGULAR");
|
|
254
|
+
if (rule)
|
|
255
|
+
return {
|
|
256
|
+
text: rule.type === "CODE_OWNER" ? "needs a code owner" : "needs an approver",
|
|
257
|
+
tone: "warning",
|
|
258
|
+
optional: true
|
|
259
|
+
};
|
|
260
|
+
if (request.reviewersComplete && needsApproval(request))
|
|
261
|
+
return { text: "needs a reviewer", tone: "muted", optional: true };
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
function reviewIndicators(request) {
|
|
265
|
+
const count = approvalCount(request);
|
|
266
|
+
const next = waitingOn(request);
|
|
267
|
+
return [
|
|
268
|
+
...count ? [count] : [],
|
|
269
|
+
...request.changesRequested === true ? [{ text: "changes requested", tone: "warning", essential: true }] : [],
|
|
270
|
+
...request.approved && !request.awaitingReviewers.length ? [{ text: "approved", tone: "success" }] : [],
|
|
271
|
+
...next ? [next] : []
|
|
272
|
+
];
|
|
273
|
+
}
|
|
274
|
+
function discussionBlocker(request) {
|
|
275
|
+
if (request.discussionResolutionRequired === false)
|
|
276
|
+
return "none";
|
|
277
|
+
if (request.unresolvedThreads > 0)
|
|
278
|
+
return request.discussionResolutionRequired === true ? "threads" : undefined;
|
|
279
|
+
return request.threadsComplete ? "none" : undefined;
|
|
280
|
+
}
|
|
281
|
+
function mergeBlockedState(request) {
|
|
282
|
+
if (request.state !== "opened" || request.draft)
|
|
283
|
+
return "none";
|
|
284
|
+
if (!approvalsComplete(request) || !request.conflictsKnown)
|
|
285
|
+
return;
|
|
286
|
+
if (isAutomatedReviewRunning(request))
|
|
287
|
+
return;
|
|
288
|
+
const satisfied = requestApprovalsSatisfied(request);
|
|
289
|
+
if (!satisfied || request.conflicts || changesRequestedState(request) === true)
|
|
290
|
+
return "none";
|
|
291
|
+
if (pipelineFails(request.pipeline) || request.pipeline?.status === "FAILED")
|
|
292
|
+
return "none";
|
|
293
|
+
const forgeBlocker = request.forge === "gitlab" ? mergeBlocker(request) : undefined;
|
|
294
|
+
return forgeBlocker ?? discussionBlocker(request);
|
|
295
|
+
}
|
|
296
|
+
function mergeBlockedReason(request) {
|
|
297
|
+
const state = mergeBlockedState(request);
|
|
298
|
+
return state === "none" ? undefined : state;
|
|
299
|
+
}
|
|
300
|
+
function mergeNextStep(request, options = {}) {
|
|
301
|
+
if (mergeBlockedReason(request) === "threads") {
|
|
302
|
+
const offerAutoMergeAfterThreads = request.forge === "gitlab" && request.autoMergeEnabled === false && request.mergeTrainIndex == null;
|
|
303
|
+
const base = offerAutoMergeAfterThreads ? "Resolve the blocking threads, then select Set to auto-merge in GitLab when available." : "Resolve the blocking threads.";
|
|
304
|
+
const shortcut = options.canReviewThreads ? " In /forge-feedback, select the merge-blocked item and choose Review blocking threads." : "";
|
|
305
|
+
return {
|
|
306
|
+
text: offerAutoMergeAfterThreads ? "resolve threads \u2192 Set to auto-merge" : "resolve threads",
|
|
307
|
+
compact: offerAutoMergeAfterThreads ? "threads \u2192 auto-merge" : "resolve threads",
|
|
308
|
+
tone: "warning",
|
|
309
|
+
essential: true,
|
|
310
|
+
detail: `${base}${shortcut}`
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
if (requestReadyToMerge(request) === true) {
|
|
314
|
+
return {
|
|
315
|
+
text: "Set to auto-merge",
|
|
316
|
+
tone: "warning",
|
|
317
|
+
essential: true,
|
|
318
|
+
url: request.url,
|
|
319
|
+
detail: "Open the merge request in GitLab and select Set to auto-merge."
|
|
320
|
+
};
|
|
101
321
|
}
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
function newestRequestsFirst(requests) {
|
|
325
|
+
return requests.map((request) => {
|
|
326
|
+
const updatedAt = Date.parse(request.updatedAt ?? "");
|
|
327
|
+
return { request, updatedAt: Number.isNaN(updatedAt) ? Number.MIN_SAFE_INTEGER : updatedAt };
|
|
328
|
+
}).sort((a, b) => b.updatedAt - a.updatedAt).map(({ request }) => request);
|
|
102
329
|
}
|
|
103
330
|
|
|
104
|
-
// packages/
|
|
331
|
+
// packages/_merge-readiness/src/evaluate.ts
|
|
332
|
+
var DUO_FEEDBACK = new Set(["REVIEWED", "REQUESTED_CHANGES"]);
|
|
333
|
+
// packages/_merge-readiness/src/sources.ts
|
|
334
|
+
var query = (text) => text;
|
|
335
|
+
var typed = (transport) => async (host, doc, variables) => await transport(host, doc, variables);
|
|
336
|
+
var MAX_DISCUSSION_PAGES = 50;
|
|
105
337
|
var MAX_REVIEW_THREADS = 30;
|
|
106
338
|
async function discussionPages(limit, read) {
|
|
107
339
|
const nodes = [];
|
|
@@ -125,32 +357,1141 @@ async function discussionPages(limit, read) {
|
|
|
125
357
|
}
|
|
126
358
|
return { nodes, complete: false };
|
|
127
359
|
}
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
360
|
+
var GITLAB_DISCUSSIONS = "pageInfo { hasNextPage endCursor } nodes { resolvable resolved }";
|
|
361
|
+
var GITLAB_PAGE_SIZE = 100;
|
|
362
|
+
var FIRST_FAILED_JOBS = 10;
|
|
363
|
+
var FAILED_JOBS = "pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }";
|
|
364
|
+
var RECHECKING = new Set(["CHECKING", "UNCHECKED", "PREPARING"]);
|
|
365
|
+
var CONFLICT_RECHECK = "CANNOT_BE_MERGED_RECHECK";
|
|
366
|
+
var REVIEWER_FIELDS = (includeApprovedAt) => `pageInfo { hasNextPage endCursor } nodes { id type username bot mergeRequestInteraction { reviewState approved${includeApprovedAt ? " approvedAt" : ""} } }`;
|
|
367
|
+
var APPROVED_BY_FIELDS = "pageInfo { hasNextPage endCursor } nodes { id username bot }";
|
|
368
|
+
var mergeRequestFields = (includeApprovedAt, includeExtendedStatus) => `
|
|
369
|
+
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
370
|
+
autoMergeEnabled
|
|
371
|
+
${includeExtendedStatus ? `
|
|
372
|
+
approvalsRequired approvalsLeft mergeTrainCar { index }
|
|
373
|
+
approvalState { rules { name type approvalsRequired approved eligibleApprovers { username type bot } } }
|
|
374
|
+
` : ""}
|
|
375
|
+
approvedBy(first: ${GITLAB_PAGE_SIZE}) { ${APPROVED_BY_FIELDS} }
|
|
376
|
+
sourceProject { fullPath }
|
|
377
|
+
targetProject { fullPath }
|
|
378
|
+
author { id username }
|
|
379
|
+
headPipeline {
|
|
380
|
+
id status path detailedStatus { label }
|
|
381
|
+
jobs(statuses: [FAILED], retried: false, first: ${FIRST_FAILED_JOBS}) { ${FAILED_JOBS} }
|
|
382
|
+
}
|
|
383
|
+
reviewers(first: ${GITLAB_PAGE_SIZE}) { ${REVIEWER_FIELDS(includeApprovedAt)} }
|
|
384
|
+
discussions(first: ${GITLAB_PAGE_SIZE}) { ${GITLAB_DISCUSSIONS} }
|
|
385
|
+
`;
|
|
386
|
+
function mergeRequestsQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
387
|
+
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
388
|
+
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
389
|
+
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) {
|
|
390
|
+
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${fields} } }
|
|
391
|
+
}`).join(`
|
|
392
|
+
`);
|
|
393
|
+
return query(`query($branch: String!, ${variables}) {
|
|
394
|
+
${projects}
|
|
395
|
+
}`);
|
|
396
|
+
}
|
|
397
|
+
function mergeRequestQuery(projectCount, includeApprovedAt = true, includeExtendedStatus = true) {
|
|
398
|
+
const fields = mergeRequestFields(includeApprovedAt, includeExtendedStatus);
|
|
399
|
+
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
400
|
+
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) { mergeRequest(iid: $iid) { ${fields} } }`).join(`
|
|
401
|
+
`);
|
|
402
|
+
return query(`query($iid: String!, ${variables}) {
|
|
403
|
+
${projects}
|
|
404
|
+
}`);
|
|
405
|
+
}
|
|
406
|
+
var DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
407
|
+
project(fullPath: $project) {
|
|
408
|
+
mergeRequest(iid: $iid) { discussions(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${GITLAB_DISCUSSIONS} } }
|
|
409
|
+
}
|
|
410
|
+
}`);
|
|
411
|
+
var reviewersQuery = (includeApprovedAt) => query(`query($project: ID!, $iid: String!, $after: String) {
|
|
412
|
+
project(fullPath: $project) {
|
|
413
|
+
mergeRequest(iid: $iid) { reviewers(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${REVIEWER_FIELDS(includeApprovedAt)} } }
|
|
414
|
+
}
|
|
415
|
+
}`);
|
|
416
|
+
var APPROVED_BY_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
417
|
+
project(fullPath: $project) {
|
|
418
|
+
mergeRequest(iid: $iid) { approvedBy(first: ${GITLAB_PAGE_SIZE}, after: $after) { ${APPROVED_BY_FIELDS} } }
|
|
419
|
+
}
|
|
420
|
+
}`);
|
|
421
|
+
var UNRESOLVED_DISCUSSIONS_QUERY = query(`query($project: ID!, $iid: String!, $after: String) {
|
|
422
|
+
project(fullPath: $project) {
|
|
423
|
+
mergeRequest(iid: $iid) {
|
|
424
|
+
state
|
|
425
|
+
discussions(first: ${GITLAB_PAGE_SIZE}, after: $after) {
|
|
426
|
+
pageInfo { hasNextPage endCursor }
|
|
427
|
+
nodes {
|
|
428
|
+
id resolvable resolved
|
|
429
|
+
notes(first: 1) { nodes { id } }
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}`);
|
|
435
|
+
var DISCUSSION_BY_NOTE = query(`
|
|
436
|
+
query($note: NoteID!, $after: String) {
|
|
437
|
+
note(id: $note) {
|
|
438
|
+
discussion {
|
|
439
|
+
id resolvable resolved
|
|
440
|
+
noteable { ... on MergeRequest { webUrl } }
|
|
441
|
+
notes(first: 20, after: $after) {
|
|
442
|
+
pageInfo { hasNextPage endCursor }
|
|
443
|
+
nodes { id url body createdAt system position { newPath newLine oldPath oldLine } author { id username bot } }
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
`);
|
|
449
|
+
var GITLAB_VIEWER_QUERY = query("query { currentUser { id username } }");
|
|
450
|
+
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));
|
|
451
|
+
var isMissingApprovedAt = (error) => /approvedAt.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*approvedAt/i.test(error instanceof Error ? error.message : String(error));
|
|
452
|
+
function classifyGitLabError(message, code) {
|
|
453
|
+
const text = message.trim().replace(/^glab:\s*/, "") || `glab exited with code ${code}`;
|
|
454
|
+
if (/ENOENT|command not found/i.test(text))
|
|
455
|
+
return new ForgeError("missing-glab", "glab is not installed");
|
|
456
|
+
if (/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(text)) {
|
|
457
|
+
return new ForgeError("auth", "GitLab authentication failed. Run `glab auth status`.");
|
|
458
|
+
}
|
|
459
|
+
if (/\b429\b|rate limit|too many requests/i.test(text))
|
|
460
|
+
return new ForgeError("rate-limit", "GitLab rate limit reached");
|
|
461
|
+
return new ForgeError("request", text.split(`
|
|
462
|
+
`)[0]);
|
|
463
|
+
}
|
|
464
|
+
var countUnresolved = (page) => page.nodes.filter((discussion) => discussion.resolvable && !discussion.resolved).length;
|
|
465
|
+
function requiredFailures(host, nodes) {
|
|
466
|
+
return nodes.flatMap((job) => !job.allowFailure && job.name ? [
|
|
467
|
+
{
|
|
468
|
+
...job.id ? { id: job.id } : {},
|
|
469
|
+
name: job.name,
|
|
470
|
+
...job.webPath ? { url: `https://${host}${job.webPath}` } : {},
|
|
471
|
+
...job.stage?.name ? { stage: job.stage.name } : {}
|
|
472
|
+
}
|
|
473
|
+
] : []);
|
|
474
|
+
}
|
|
475
|
+
function gitlabFailedJobs(host, pipeline) {
|
|
476
|
+
if (!pipeline.id || !pipeline.jobs)
|
|
477
|
+
return {};
|
|
478
|
+
return {
|
|
479
|
+
id: pipeline.id,
|
|
480
|
+
failedJobs: requiredFailures(host, pipeline.jobs.nodes),
|
|
481
|
+
failedJobsComplete: !pipeline.jobs.pageInfo?.hasNextPage
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function normalizeGitLabApprovers(reviewers, approvedBy) {
|
|
485
|
+
const byId = new Map;
|
|
486
|
+
const byUsername = new Map;
|
|
487
|
+
for (const reviewer of reviewers) {
|
|
488
|
+
if (reviewer.id)
|
|
489
|
+
byId.set(reviewer.id, reviewer);
|
|
490
|
+
if (reviewer.username)
|
|
491
|
+
byUsername.set(reviewer.username.toLowerCase(), reviewer);
|
|
492
|
+
}
|
|
493
|
+
const isDuo = (reviewer, username, bot) => reviewer?.type === "DUO_CODE_REVIEW_BOT" || bot === true && username?.toLowerCase() === "gitlabduo";
|
|
494
|
+
const inactiveReview = (reviewer) => {
|
|
495
|
+
const state = reviewer?.mergeRequestInteraction?.reviewState;
|
|
496
|
+
return !!state && state !== "APPROVED";
|
|
497
|
+
};
|
|
498
|
+
const found = [];
|
|
499
|
+
const add = (entry) => {
|
|
500
|
+
const lower = entry.username.toLowerCase();
|
|
501
|
+
const index = found.findIndex((existing) => entry.id && existing.id ? existing.id === entry.id : existing.username.toLowerCase() === lower && (!entry.id || !existing.id));
|
|
502
|
+
if (index < 0) {
|
|
503
|
+
found.push(entry);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const existing = found[index];
|
|
507
|
+
found[index] = {
|
|
508
|
+
...existing,
|
|
509
|
+
...entry,
|
|
510
|
+
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
511
|
+
...existing.bot || entry.bot ? { bot: true } : {},
|
|
512
|
+
...existing.automated || entry.automated ? { automated: true } : {},
|
|
513
|
+
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
514
|
+
};
|
|
515
|
+
};
|
|
516
|
+
for (const reviewer of reviewers) {
|
|
517
|
+
const interaction = reviewer.mergeRequestInteraction;
|
|
518
|
+
const approving = interaction?.reviewState === "APPROVED" || !interaction?.reviewState && interaction?.approved === true;
|
|
519
|
+
if (!approving)
|
|
520
|
+
continue;
|
|
521
|
+
const duo = isDuo(reviewer, reviewer.username, reviewer.bot);
|
|
522
|
+
const username = reviewer.username ?? (duo ? "GitLabDuo" : undefined);
|
|
523
|
+
if (!username)
|
|
524
|
+
continue;
|
|
525
|
+
const bot = reviewer.bot === true || duo;
|
|
526
|
+
add({
|
|
527
|
+
...reviewer.id ? { id: reviewer.id } : {},
|
|
528
|
+
username,
|
|
529
|
+
...bot ? { bot: true } : {},
|
|
530
|
+
...duo ? { automated: true } : {},
|
|
531
|
+
...interaction?.approvedAt ? { reviewID: interaction.approvedAt } : {}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
for (const approver of approvedBy) {
|
|
535
|
+
const matched = (approver.id ? byId.get(approver.id) : undefined) ?? (approver.username ? byUsername.get(approver.username.toLowerCase()) : undefined);
|
|
536
|
+
if (inactiveReview(matched))
|
|
537
|
+
continue;
|
|
538
|
+
const duo = isDuo(matched, approver.username ?? matched?.username, approver.bot ?? matched?.bot);
|
|
539
|
+
const username = approver.username ?? matched?.username ?? (duo ? "GitLabDuo" : undefined);
|
|
540
|
+
if (!username)
|
|
541
|
+
continue;
|
|
542
|
+
const bot = approver.bot === true || matched?.bot === true || duo;
|
|
543
|
+
add({
|
|
544
|
+
...approver.id || matched?.id ? { id: approver.id ?? matched?.id ?? undefined } : {},
|
|
545
|
+
username,
|
|
546
|
+
...bot ? { bot: true } : {},
|
|
547
|
+
...duo ? { automated: true } : {}
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
return found;
|
|
551
|
+
}
|
|
552
|
+
function createGitLabSource(transport, options = {}) {
|
|
553
|
+
const graphql = typed(transport);
|
|
554
|
+
const unsupportedApprovedAt = options.unsupportedApprovedAt ?? new Set;
|
|
555
|
+
const unsupportedExtendedStatus = options.unsupportedExtendedStatus ?? new Set;
|
|
556
|
+
async function queryWithApprovedAt(host, build, variables) {
|
|
557
|
+
if (unsupportedApprovedAt.has(host)) {
|
|
558
|
+
return graphql(host, build(false), variables);
|
|
559
|
+
}
|
|
560
|
+
try {
|
|
561
|
+
return await graphql(host, build(true), variables);
|
|
562
|
+
} catch (error) {
|
|
563
|
+
if (!isMissingApprovedAt(error))
|
|
564
|
+
throw error;
|
|
565
|
+
unsupportedApprovedAt.add(host);
|
|
566
|
+
return graphql(host, build(false), variables);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async function queryStatus(host, build, variables) {
|
|
570
|
+
const run = (extended) => queryWithApprovedAt(host, (approvedAt) => build(approvedAt, extended), variables);
|
|
571
|
+
if (unsupportedExtendedStatus.has(host))
|
|
572
|
+
return run(false);
|
|
573
|
+
try {
|
|
574
|
+
return await run(true);
|
|
575
|
+
} catch (error) {
|
|
576
|
+
if (!isMissingExtendedStatus(error))
|
|
577
|
+
throw error;
|
|
578
|
+
unsupportedExtendedStatus.add(host);
|
|
579
|
+
return run(false);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
async function discussionRequirement(host, node) {
|
|
583
|
+
if (node.detailedMergeStatus === "DISCUSSIONS_NOT_RESOLVED")
|
|
584
|
+
return true;
|
|
585
|
+
const data = await graphql(host, query(`query($project: ID!) { project(fullPath: $project) { onlyAllowMergeIfAllDiscussionsAreResolved } }`), { project: node.targetProject.fullPath }).catch(() => {
|
|
586
|
+
return;
|
|
587
|
+
});
|
|
588
|
+
return data?.project?.onlyAllowMergeIfAllDiscussionsAreResolved ?? undefined;
|
|
589
|
+
}
|
|
590
|
+
async function unresolvedThreads(host, node) {
|
|
591
|
+
let count = countUnresolved(node.discussions);
|
|
592
|
+
let page = node.discussions.pageInfo;
|
|
593
|
+
let pages = 1;
|
|
594
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
595
|
+
const data = await graphql(host, DISCUSSIONS_QUERY, {
|
|
596
|
+
project: node.targetProject.fullPath,
|
|
597
|
+
iid: node.iid,
|
|
598
|
+
after: page.endCursor
|
|
599
|
+
});
|
|
600
|
+
const next = data.project?.mergeRequest?.discussions;
|
|
601
|
+
if (!next)
|
|
602
|
+
break;
|
|
603
|
+
count += countUnresolved(next);
|
|
604
|
+
page = next.pageInfo;
|
|
605
|
+
pages++;
|
|
606
|
+
}
|
|
607
|
+
return { count, complete: !page.hasNextPage };
|
|
608
|
+
}
|
|
609
|
+
async function allReviewers(host, node) {
|
|
610
|
+
if (!node.reviewers?.pageInfo)
|
|
611
|
+
return { nodes: [...node.reviewers?.nodes ?? []], complete: false };
|
|
612
|
+
const nodes = [...node.reviewers.nodes];
|
|
613
|
+
let page = node.reviewers.pageInfo;
|
|
614
|
+
let pages = 1;
|
|
615
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
616
|
+
const data = await queryWithApprovedAt(host, (includeApprovedAt) => reviewersQuery(includeApprovedAt), {
|
|
617
|
+
project: node.targetProject.fullPath,
|
|
618
|
+
iid: node.iid,
|
|
619
|
+
after: page.endCursor
|
|
620
|
+
});
|
|
621
|
+
const next = data.project?.mergeRequest?.reviewers;
|
|
622
|
+
if (!next?.pageInfo)
|
|
623
|
+
return { nodes, complete: false };
|
|
624
|
+
nodes.push(...next.nodes);
|
|
625
|
+
page = next.pageInfo;
|
|
626
|
+
pages++;
|
|
627
|
+
}
|
|
628
|
+
return { nodes, complete: !page.hasNextPage };
|
|
629
|
+
}
|
|
630
|
+
async function allApprovedBy(host, node) {
|
|
631
|
+
if (!node.approvedBy?.pageInfo)
|
|
632
|
+
return { nodes: [...node.approvedBy?.nodes ?? []], complete: false };
|
|
633
|
+
const nodes = [...node.approvedBy.nodes];
|
|
634
|
+
let page = node.approvedBy.pageInfo;
|
|
635
|
+
let pages = 1;
|
|
636
|
+
while (page.hasNextPage && page.endCursor && pages < MAX_DISCUSSION_PAGES) {
|
|
637
|
+
const data = await graphql(host, APPROVED_BY_QUERY, {
|
|
638
|
+
project: node.targetProject.fullPath,
|
|
639
|
+
iid: node.iid,
|
|
640
|
+
after: page.endCursor
|
|
641
|
+
});
|
|
642
|
+
const next = data.project?.mergeRequest?.approvedBy;
|
|
643
|
+
if (!next?.pageInfo)
|
|
644
|
+
return { nodes, complete: false };
|
|
645
|
+
nodes.push(...next.nodes);
|
|
646
|
+
page = next.pageInfo;
|
|
647
|
+
pages++;
|
|
648
|
+
}
|
|
649
|
+
return { nodes, complete: !page.hasNextPage };
|
|
650
|
+
}
|
|
651
|
+
async function normalize(host, node) {
|
|
652
|
+
const [threads, reviewersPage, approvedByPage] = await Promise.all([
|
|
653
|
+
unresolvedThreads(host, node),
|
|
654
|
+
allReviewers(host, node),
|
|
655
|
+
allApprovedBy(host, node)
|
|
656
|
+
]);
|
|
657
|
+
const pipeline = node.headPipeline;
|
|
658
|
+
const discussionResolutionRequired = threads.count > 0 ? await discussionRequirement(host, node) : undefined;
|
|
659
|
+
const hasApprovals = approvedByPage.nodes.some((approver) => approver.bot !== true);
|
|
660
|
+
const unapproved = reviewersPage.nodes.filter((reviewer) => reviewer.bot !== true && reviewer.username && reviewer.mergeRequestInteraction?.approved !== true);
|
|
661
|
+
const pendingHumans = unapproved.filter((reviewer) => reviewer.mergeRequestInteraction?.reviewState !== "REQUESTED_CHANGES");
|
|
662
|
+
const awaitingReviewers = pendingHumans.map((reviewer) => reviewer.username);
|
|
663
|
+
const pendingHumanReviewers = pendingHumans.map((reviewer) => ({
|
|
664
|
+
...reviewer.id ? { id: reviewer.id } : {},
|
|
665
|
+
username: reviewer.username
|
|
666
|
+
}));
|
|
667
|
+
const approvers = normalizeGitLabApprovers(reviewersPage.nodes, approvedByPage.nodes);
|
|
668
|
+
const approvedNames = new Set([...approvedByPage.nodes, ...approvers].flatMap(({ username }) => username ? [username.toLowerCase()] : []));
|
|
669
|
+
const missingRules = (node.approvalState?.rules ?? []).flatMap((rule) => {
|
|
670
|
+
if (rule.approvalsRequired == null || rule.approvalsRequired <= 0 || rule.approved !== false)
|
|
671
|
+
return [];
|
|
672
|
+
const eligible = (rule.eligibleApprovers ?? []).filter(({ username, bot }) => !bot && !approvedNames.has(username.toLowerCase()));
|
|
673
|
+
const eligibleNames = new Set(eligible.map(({ username }) => username.toLowerCase()));
|
|
674
|
+
const humans = eligible.filter(({ type }) => type === "HUMAN");
|
|
675
|
+
const humanNames = new Set(humans.map(({ username }) => username.toLowerCase()));
|
|
676
|
+
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())));
|
|
677
|
+
const candidates = humans.length ? humans : eligible;
|
|
678
|
+
return [
|
|
679
|
+
{
|
|
680
|
+
name: rule.name ?? "Unnamed approval rule",
|
|
681
|
+
type: rule.type ?? undefined,
|
|
682
|
+
required: rule.approvalsRequired,
|
|
683
|
+
eligibleReviewers,
|
|
684
|
+
eligible: candidates.slice(0, 2).map(({ username }) => username),
|
|
685
|
+
eligibleCount: candidates.length
|
|
686
|
+
}
|
|
687
|
+
];
|
|
688
|
+
});
|
|
689
|
+
const request = {
|
|
690
|
+
forge: "gitlab",
|
|
691
|
+
iid: node.iid,
|
|
692
|
+
title: node.title,
|
|
693
|
+
url: node.webUrl,
|
|
694
|
+
state: node.state.toLowerCase(),
|
|
695
|
+
draft: node.draft,
|
|
696
|
+
conflicts: node.conflicts || node.mergeStatusEnum === CONFLICT_RECHECK,
|
|
697
|
+
conflictsKnown: node.mergeStatusEnum !== CONFLICT_RECHECK && !RECHECKING.has(node.detailedMergeStatus ?? ""),
|
|
698
|
+
approved: node.approved === true && hasApprovals && unapproved.length === 0,
|
|
699
|
+
hasApprovals,
|
|
700
|
+
approvalRequirementsSatisfied: node.approved,
|
|
701
|
+
discussionResolutionRequired,
|
|
702
|
+
approvalsRequired: node.approvalsRequired ?? undefined,
|
|
703
|
+
approvalsLeft: node.approvalsLeft ?? undefined,
|
|
704
|
+
missingRules,
|
|
705
|
+
autoMergeEnabled: node.autoMergeEnabled,
|
|
706
|
+
mergeTrainIndex: node.mergeTrainCar?.index,
|
|
707
|
+
awaitingReviewers,
|
|
708
|
+
pendingHumanReviewers,
|
|
709
|
+
reviewersComplete: reviewersPage.complete,
|
|
710
|
+
changesRequested: (() => {
|
|
711
|
+
if (reviewersPage.nodes.some((reviewer) => reviewer.mergeRequestInteraction?.reviewState === "REQUESTED_CHANGES")) {
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
if (reviewersPage.complete && reviewersPage.nodes.every((reviewer) => reviewer.mergeRequestInteraction?.reviewState)) {
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
return;
|
|
718
|
+
})(),
|
|
719
|
+
approvalsComplete: reviewersPage.complete && approvedByPage.complete,
|
|
720
|
+
reviewerIDs: reviewersPage.nodes.flatMap((reviewer) => reviewer.id ?? []),
|
|
721
|
+
approvers,
|
|
722
|
+
mergeStatus: node.detailedMergeStatus ?? undefined,
|
|
723
|
+
targetProject: node.targetProject.fullPath,
|
|
724
|
+
targetBranch: node.targetBranch,
|
|
725
|
+
...node.sourceProject ? { sourceProject: node.sourceProject.fullPath } : {},
|
|
726
|
+
sourceBranch: node.sourceBranch,
|
|
727
|
+
headSha: node.diffHeadSha ?? undefined,
|
|
728
|
+
...node.author?.id ? { authorID: node.author.id } : {},
|
|
729
|
+
...node.author?.username ? { authorUsername: node.author.username } : {},
|
|
730
|
+
updatedAt: node.updatedAt ?? undefined,
|
|
731
|
+
pipeline: pipeline ? {
|
|
732
|
+
status: pipeline.status,
|
|
733
|
+
label: pipeline.detailedStatus?.label ?? pipeline.status.toLowerCase().replace(/_/g, " "),
|
|
734
|
+
url: pipeline.path ? `https://${host}${pipeline.path}` : undefined,
|
|
735
|
+
...gitlabFailedJobs(host, pipeline)
|
|
736
|
+
} : undefined,
|
|
737
|
+
unresolvedThreads: threads.count,
|
|
738
|
+
threadsComplete: threads.complete,
|
|
739
|
+
duoReviewState: reviewersPage.nodes.find((reviewer) => reviewer.type === "DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState ?? undefined
|
|
740
|
+
};
|
|
741
|
+
if (autoMergeCandidate(request) === true && request.headSha) {
|
|
742
|
+
const data = await graphql(host, query(`query($project: ID!, $iid: String!) {
|
|
743
|
+
project(fullPath: $project) { mergeRequest(iid: $iid) {
|
|
744
|
+
diffHeadSha autoMergeEnabled detailedMergeStatus userPermissions { canMerge }
|
|
745
|
+
availableAutoMergeStrategies
|
|
746
|
+
} }
|
|
747
|
+
}`), { project: request.targetProject, iid: request.iid }).catch(() => {
|
|
748
|
+
return;
|
|
749
|
+
});
|
|
750
|
+
const live = data?.project?.mergeRequest;
|
|
751
|
+
if (live?.diffHeadSha === request.headSha && live.autoMergeEnabled === false && live.detailedMergeStatus === request.mergeStatus) {
|
|
752
|
+
if (typeof live.userPermissions?.canMerge === "boolean") {
|
|
753
|
+
request.canMerge = live.userPermissions.canMerge;
|
|
754
|
+
}
|
|
755
|
+
if (live.userPermissions?.canMerge === false)
|
|
756
|
+
request.autoMergeAvailable = false;
|
|
757
|
+
else if (live.userPermissions?.canMerge === true && Array.isArray(live.availableAutoMergeStrategies))
|
|
758
|
+
request.autoMergeAvailable = live.availableAutoMergeStrategies.length > 0;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
return request;
|
|
762
|
+
}
|
|
763
|
+
async function discussion(ref, { id, anchor }) {
|
|
764
|
+
if (!anchor)
|
|
765
|
+
return;
|
|
766
|
+
let resolved = false;
|
|
767
|
+
let owned = false;
|
|
768
|
+
const replies = await discussionPages(10, async (after) => {
|
|
769
|
+
const data = await graphql(ref.host, DISCUSSION_BY_NOTE, {
|
|
770
|
+
note: anchor,
|
|
771
|
+
...after ? { after } : {}
|
|
772
|
+
});
|
|
773
|
+
const thread = data.note?.discussion;
|
|
774
|
+
const owner = thread?.noteable?.webUrl && parseGitLabUrl(thread.noteable.webUrl);
|
|
775
|
+
owned = Boolean(thread?.id === id && owner && owner.host === ref.host && owner.project === ref.project && owner.iid === ref.iid);
|
|
776
|
+
if (!owned || !thread)
|
|
777
|
+
return;
|
|
778
|
+
resolved = thread.resolved;
|
|
779
|
+
return resolved || !thread.resolvable ? undefined : thread.notes;
|
|
780
|
+
});
|
|
781
|
+
if (!owned)
|
|
782
|
+
return;
|
|
783
|
+
if (resolved)
|
|
784
|
+
return "resolved";
|
|
785
|
+
const notes = [];
|
|
786
|
+
let incomplete = !replies.complete;
|
|
787
|
+
for (const note of replies.nodes) {
|
|
788
|
+
if (note.system)
|
|
789
|
+
continue;
|
|
790
|
+
if (!note.id || !note.author?.username || typeof note.body !== "string") {
|
|
791
|
+
incomplete = true;
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
notes.push({
|
|
795
|
+
id: note.id.slice(note.id.lastIndexOf("/") + 1),
|
|
796
|
+
url: note.url ?? undefined,
|
|
797
|
+
authorID: note.author.id,
|
|
798
|
+
username: note.author.username,
|
|
799
|
+
bot: note.author.bot === true,
|
|
800
|
+
body: note.body,
|
|
801
|
+
createdAt: note.createdAt ?? undefined,
|
|
802
|
+
path: note.position?.newPath ?? note.position?.oldPath ?? undefined,
|
|
803
|
+
line: note.position?.newLine ?? note.position?.oldLine ?? undefined
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
id,
|
|
808
|
+
anchor,
|
|
809
|
+
notes,
|
|
810
|
+
url: notes.find((note) => note.url)?.url,
|
|
811
|
+
incomplete: incomplete || notes.length === 0
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
async function unresolvedDiscussions(ref) {
|
|
815
|
+
const list = await discussionPages(MAX_DISCUSSION_PAGES, async (after) => {
|
|
816
|
+
const data = await graphql(ref.host, UNRESOLVED_DISCUSSIONS_QUERY, {
|
|
817
|
+
project: ref.project,
|
|
818
|
+
iid: ref.iid,
|
|
819
|
+
...after ? { after } : {}
|
|
820
|
+
});
|
|
821
|
+
return data.project?.mergeRequest?.discussions;
|
|
822
|
+
});
|
|
823
|
+
const discussions = [];
|
|
824
|
+
const candidates = list.nodes.filter(({ id, resolvable, resolved }) => id && resolvable && !resolved);
|
|
825
|
+
for (const node of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
826
|
+
const noteID = node.notes?.nodes[0]?.id?.match(/^gid:\/\/gitlab\/\w+\/(\d+)$/)?.[1];
|
|
827
|
+
const anchor = noteID ? `gid://gitlab/Note/${noteID}` : undefined;
|
|
828
|
+
const thread = await discussion(ref, { id: node.id, anchor }).catch(() => {
|
|
829
|
+
return;
|
|
830
|
+
});
|
|
831
|
+
if (thread !== "resolved")
|
|
832
|
+
discussions.push(thread ?? { id: node.id, notes: [], incomplete: true });
|
|
833
|
+
}
|
|
834
|
+
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
835
|
+
}
|
|
836
|
+
async function fetchByProjects(projects, iid) {
|
|
837
|
+
if (projects.length === 0)
|
|
838
|
+
return;
|
|
839
|
+
const host = projects[0].host;
|
|
840
|
+
const variables = { iid };
|
|
841
|
+
projects.forEach((project, index) => variables[`p${index}`] = project.path);
|
|
842
|
+
const data = await queryStatus(host, (approvedAt, extended) => mergeRequestQuery(projects.length, approvedAt, extended), variables);
|
|
843
|
+
for (let index = 0;index < projects.length; index++) {
|
|
844
|
+
const node = data[`p${index}`]?.mergeRequest;
|
|
845
|
+
if (node)
|
|
846
|
+
return normalize(host, node);
|
|
847
|
+
}
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
async function fetchByBranch(source, targets, sourceBranch) {
|
|
851
|
+
if (targets.length === 0)
|
|
852
|
+
return [];
|
|
853
|
+
const variables = { branch: sourceBranch };
|
|
854
|
+
targets.forEach((target, index) => variables[`p${index}`] = target.path);
|
|
855
|
+
const data = await queryStatus(source.host, (approvedAt, extended) => mergeRequestsQuery(targets.length, approvedAt, extended), variables);
|
|
856
|
+
const sourcePath = source.path.toLowerCase();
|
|
857
|
+
const seen = new Set;
|
|
858
|
+
const nodes = [];
|
|
859
|
+
targets.forEach((_, index) => {
|
|
860
|
+
for (const node of data[`p${index}`]?.mergeRequests?.nodes ?? []) {
|
|
861
|
+
if (node.sourceProject?.fullPath.toLowerCase() !== sourcePath)
|
|
862
|
+
continue;
|
|
863
|
+
const key = `${node.targetProject.fullPath}!${node.iid}`;
|
|
864
|
+
if (seen.has(key))
|
|
865
|
+
continue;
|
|
866
|
+
seen.add(key);
|
|
867
|
+
nodes.push(node);
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
const requests = await Promise.all(nodes.map((node) => normalize(source.host, node)));
|
|
871
|
+
return requests.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
872
|
+
}
|
|
873
|
+
async function viewer(host) {
|
|
874
|
+
const data = await graphql(host, GITLAB_VIEWER_QUERY, {});
|
|
875
|
+
const user = data.currentUser;
|
|
876
|
+
if (!user?.id && !user?.username)
|
|
877
|
+
return;
|
|
878
|
+
return {
|
|
879
|
+
...user.id ? { id: user.id } : {},
|
|
880
|
+
...user.username ? { username: user.username } : {}
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
return {
|
|
884
|
+
forge: "gitlab",
|
|
885
|
+
fetchRequest: (ref) => fetchByProjects([{ host: ref.host, path: ref.project }], ref.iid),
|
|
886
|
+
fetchByProjects,
|
|
887
|
+
fetchByBranch,
|
|
888
|
+
unresolvedDiscussions,
|
|
889
|
+
discussion,
|
|
890
|
+
viewer
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
var COPILOT_AUTHOR = "copilot-pull-request-reviewer[bot]";
|
|
894
|
+
var GITHUB_MAX_PAGES = 50;
|
|
895
|
+
var githubPullFields = (includeAutoMerge) => `number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
896
|
+
${includeAutoMerge ? "autoMergeRequest { enabledAt }" : ""}
|
|
897
|
+
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
898
|
+
author { login ... on User { id } ... on Bot { id } }
|
|
899
|
+
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
900
|
+
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
901
|
+
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
902
|
+
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
903
|
+
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 } } } }
|
|
904
|
+
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
905
|
+
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
906
|
+
pageInfo { hasNextPage endCursor }
|
|
907
|
+
} } } } }`;
|
|
908
|
+
var isMissingAutoMerge = (error) => /autoMergeRequest.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*autoMergeRequest/i.test(error instanceof Error ? error.message : String(error));
|
|
909
|
+
var GITHUB_VIEWER_QUERY = query("query { viewer { id login } }");
|
|
910
|
+
function classifyGitHubError(message, code) {
|
|
911
|
+
const text = message.trim() || `gh exited with code ${code}`;
|
|
912
|
+
if (/ENOENT|command not found/i.test(text))
|
|
913
|
+
return new ForgeError("missing-gh", "gh is not installed");
|
|
914
|
+
if (/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(text))
|
|
915
|
+
return new ForgeError("auth", "GitHub authentication failed. Run `gh auth status`.");
|
|
916
|
+
if (/429|rate limit|too many requests/i.test(text))
|
|
917
|
+
return new ForgeError("rate-limit", "GitHub rate limit reached");
|
|
918
|
+
return new ForgeError("request", text.split(`
|
|
919
|
+
`)[0]);
|
|
920
|
+
}
|
|
921
|
+
var FAILED_CHECKS = ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"];
|
|
922
|
+
var CHECK_CONCLUSIONS = [
|
|
923
|
+
"SUCCESS",
|
|
924
|
+
"NEUTRAL",
|
|
925
|
+
"SKIPPED",
|
|
926
|
+
"FAILURE",
|
|
927
|
+
"TIMED_OUT",
|
|
928
|
+
"CANCELLED",
|
|
929
|
+
"ACTION_REQUIRED",
|
|
930
|
+
"STARTUP_FAILURE",
|
|
931
|
+
"STALE"
|
|
932
|
+
];
|
|
933
|
+
var CHECK_STATES = ["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED"];
|
|
934
|
+
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]);
|
|
935
|
+
var checkTime = (node) => Date.parse(node.checkSuite?.createdAt ?? "");
|
|
936
|
+
var newerCheck = (node, previous) => checkTime(node) > checkTime(previous);
|
|
937
|
+
function checks(nodes, complete, url, id) {
|
|
938
|
+
const latest = new Map;
|
|
939
|
+
for (const node of nodes) {
|
|
940
|
+
const time = checkTime(node);
|
|
941
|
+
const key = checkKey(node);
|
|
942
|
+
if (!key || !Number.isFinite(time))
|
|
943
|
+
continue;
|
|
944
|
+
const previous = latest.get(key);
|
|
945
|
+
if (!previous || newerCheck(node, previous))
|
|
946
|
+
latest.set(key, node);
|
|
947
|
+
}
|
|
948
|
+
nodes = nodes.filter((node) => {
|
|
949
|
+
const key = checkKey(node);
|
|
950
|
+
const replacement = key && latest.get(key);
|
|
951
|
+
return !replacement || !newerCheck(replacement, node);
|
|
952
|
+
});
|
|
953
|
+
const count = (value) => `${value} check${value === 1 ? "" : "s"}`;
|
|
954
|
+
const cancelled = nodes.filter((node) => node.conclusion === "CANCELLED").length;
|
|
955
|
+
const stale = nodes.filter((node) => node.conclusion === "STALE").length;
|
|
956
|
+
const stopped = [
|
|
957
|
+
...cancelled ? [`${count(cancelled)} cancelled`] : [],
|
|
958
|
+
...stale ? [`${count(stale)} stale`] : []
|
|
959
|
+
];
|
|
960
|
+
const failing = nodes.filter((node) => FAILED_CHECKS.includes(node.conclusion ?? node.state ?? ""));
|
|
961
|
+
const failed = failing.length;
|
|
962
|
+
const run = id ? {
|
|
963
|
+
id,
|
|
964
|
+
failedJobs: failing.flatMap((node) => {
|
|
965
|
+
const name = node.name ?? node.context;
|
|
966
|
+
const link = node.detailsUrl ?? node.targetUrl;
|
|
967
|
+
return name ? [{ ...node.id ? { id: node.id } : {}, name, ...link ? { url: link } : {} }] : [];
|
|
968
|
+
}),
|
|
969
|
+
failedJobsComplete: complete
|
|
970
|
+
} : {};
|
|
971
|
+
const pending = nodes.filter((node) => node.status ? node.status !== "COMPLETED" : ["PENDING", "EXPECTED"].includes(node.state ?? "")).length;
|
|
972
|
+
const unknown = nodes.some((node) => node.status === "COMPLETED" ? !CHECK_CONCLUSIONS.includes(node.conclusion ?? "") : !node.status && !CHECK_STATES.includes(node.state ?? ""));
|
|
973
|
+
if (failed)
|
|
974
|
+
return {
|
|
975
|
+
status: "FAILED",
|
|
976
|
+
label: [
|
|
977
|
+
`${count(failed)} failed`,
|
|
978
|
+
...stopped,
|
|
979
|
+
...pending ? [`${count(pending)} pending`] : []
|
|
980
|
+
].join(", ") + (complete ? "" : " (partial)"),
|
|
981
|
+
url,
|
|
982
|
+
...run,
|
|
983
|
+
running: pending > 0
|
|
984
|
+
};
|
|
985
|
+
if (pending || !complete || unknown)
|
|
986
|
+
return {
|
|
987
|
+
status: "PENDING",
|
|
988
|
+
label: [...stopped, pending ? `${count(pending)} pending` : "unknown"].join(", ") + (complete ? "" : " (partial)"),
|
|
989
|
+
url,
|
|
990
|
+
...run
|
|
991
|
+
};
|
|
992
|
+
if (cancelled || stale)
|
|
993
|
+
return { status: "CANCELLED", label: stopped.join(", "), url, ...run };
|
|
994
|
+
const label = [
|
|
995
|
+
["SUCCESS", "passed"],
|
|
996
|
+
["SKIPPED", "skipped"],
|
|
997
|
+
["NEUTRAL", "neutral"]
|
|
998
|
+
].flatMap(([result, text]) => {
|
|
999
|
+
const total = nodes.filter((node) => (node.conclusion ?? node.state) === result).length;
|
|
1000
|
+
return total ? [`${count(total)} ${text}`] : [];
|
|
1001
|
+
}).join(", ");
|
|
1002
|
+
return { status: "SUCCESS", label: label || "0 checks", url, ...run };
|
|
1003
|
+
}
|
|
1004
|
+
var isCopilotReviewer = (login) => /^copilot-pull-request-reviewer(\[bot\])?$/i.test(login ?? "");
|
|
1005
|
+
var isCopilotBot = (reviewer) => reviewer?.__typename === "Bot" && isCopilotReviewer(reviewer.login);
|
|
1006
|
+
function botUsername(login, typename) {
|
|
1007
|
+
return typename === "Bot" && !login.endsWith("[bot]") ? `${login}[bot]` : login;
|
|
1008
|
+
}
|
|
1009
|
+
function copilotReview(node) {
|
|
1010
|
+
const requested = node.reviewRequests.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
1011
|
+
const latest = node.copilotReviews?.nodes?.find((review) => review);
|
|
1012
|
+
if (!requested && !latest)
|
|
1013
|
+
return;
|
|
1014
|
+
return {
|
|
1015
|
+
requested,
|
|
1016
|
+
reviewID: latest?.id,
|
|
1017
|
+
comments: latest?.comments.totalCount ?? 0,
|
|
1018
|
+
...latest?.state === "DISMISSED" ? { dismissed: true } : {}
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
function pendingReviewer(reviewers) {
|
|
1022
|
+
const pendingIDs = new Set;
|
|
1023
|
+
const pendingWithoutID = new Set;
|
|
1024
|
+
const pendingTypedLogins = new Set;
|
|
1025
|
+
const typedLoginKey = (typename, login) => `${typename ?? "Unknown"}:${botUsername(login, typename).toLowerCase()}`;
|
|
1026
|
+
for (const request of reviewers.nodes) {
|
|
1027
|
+
const reviewer = request.requestedReviewer;
|
|
1028
|
+
if (reviewer?.id)
|
|
1029
|
+
pendingIDs.add(reviewer.id);
|
|
1030
|
+
if (reviewer?.login) {
|
|
1031
|
+
const key = typedLoginKey(reviewer.__typename, reviewer.login);
|
|
1032
|
+
pendingTypedLogins.add(key);
|
|
1033
|
+
if (!reviewer.id)
|
|
1034
|
+
pendingWithoutID.add(key);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
return (id, typename, login) => {
|
|
1038
|
+
const key = typedLoginKey(typename, login);
|
|
1039
|
+
if (id)
|
|
1040
|
+
return pendingIDs.has(id) || pendingWithoutID.has(key);
|
|
1041
|
+
return pendingTypedLogins.has(key);
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function normalizeGitHubApprovers(node, reviewers, opinionated) {
|
|
1045
|
+
const isPending = pendingReviewer(reviewers);
|
|
1046
|
+
const found = new Map;
|
|
1047
|
+
const add = (entry) => {
|
|
1048
|
+
const key = `${entry.bot ? "bot" : "user"}:${entry.username.toLowerCase()}`;
|
|
1049
|
+
const existing = found.get(key);
|
|
1050
|
+
if (!existing) {
|
|
1051
|
+
found.set(key, entry);
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
found.set(key, {
|
|
1055
|
+
...existing,
|
|
1056
|
+
...entry,
|
|
1057
|
+
...existing.id || entry.id ? { id: entry.id ?? existing.id } : {},
|
|
1058
|
+
...existing.bot || entry.bot ? { bot: true } : {},
|
|
1059
|
+
...existing.automated || entry.automated ? { automated: true } : {},
|
|
1060
|
+
...existing.reviewID || entry.reviewID ? { reviewID: entry.reviewID ?? existing.reviewID } : {}
|
|
1061
|
+
});
|
|
1062
|
+
};
|
|
1063
|
+
for (const review of opinionated) {
|
|
1064
|
+
if (review?.state !== "APPROVED" || !review.author?.login)
|
|
1065
|
+
continue;
|
|
1066
|
+
const { id, login, __typename } = review.author;
|
|
1067
|
+
if (isPending(id, __typename, login))
|
|
1068
|
+
continue;
|
|
1069
|
+
const bot = __typename === "Bot";
|
|
1070
|
+
const automated = bot && isCopilotReviewer(login);
|
|
1071
|
+
const username = automated ? COPILOT_AUTHOR : botUsername(login, __typename);
|
|
1072
|
+
add({
|
|
1073
|
+
...id ? { id } : {},
|
|
1074
|
+
username,
|
|
1075
|
+
...bot ? { bot: true } : {},
|
|
1076
|
+
...automated ? { automated: true } : {},
|
|
1077
|
+
...review.id ? { reviewID: review.id } : {}
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
const latestCopilot = node.copilotReviews?.nodes?.find((review) => review);
|
|
1081
|
+
const copilotPending = reviewers.nodes.some((request) => isCopilotBot(request.requestedReviewer));
|
|
1082
|
+
if (latestCopilot?.state === "APPROVED" && isCopilotBot(latestCopilot.author) && !copilotPending) {
|
|
1083
|
+
add({
|
|
1084
|
+
...latestCopilot.author?.id ? { id: latestCopilot.author.id } : {},
|
|
1085
|
+
username: COPILOT_AUTHOR,
|
|
1086
|
+
bot: true,
|
|
1087
|
+
automated: true,
|
|
1088
|
+
...latestCopilot.id ? { reviewID: latestCopilot.id } : {}
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
return [...found.values()];
|
|
1092
|
+
}
|
|
1093
|
+
function changeRequests(reviewers, opinionated) {
|
|
1094
|
+
if (!reviewers.pageInfo || reviewers.pageInfo.hasNextPage)
|
|
1095
|
+
return {};
|
|
1096
|
+
const pending = pendingReviewer(reviewers);
|
|
1097
|
+
const ids = [];
|
|
1098
|
+
let complete = opinionated.complete;
|
|
1099
|
+
for (const review of opinionated.nodes) {
|
|
1100
|
+
if (review?.state !== "CHANGES_REQUESTED")
|
|
1101
|
+
continue;
|
|
1102
|
+
const author = review.author;
|
|
1103
|
+
if (!author?.login || !review.id) {
|
|
1104
|
+
complete = false;
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
if (!pending(author.id, author.__typename, author.login))
|
|
1108
|
+
ids.push(review.id);
|
|
1109
|
+
}
|
|
1110
|
+
if (ids.length)
|
|
1111
|
+
return { changesRequested: true, changeReviewIDs: ids };
|
|
1112
|
+
return complete ? { changesRequested: false } : {};
|
|
1113
|
+
}
|
|
1114
|
+
function createGitHubSource(transport, options = {}) {
|
|
1115
|
+
const graphql = typed(transport);
|
|
1116
|
+
const unsupportedAutoMerge = options.unsupportedAutoMerge ?? new Set;
|
|
1117
|
+
async function queryPull(host, build, variables) {
|
|
1118
|
+
if (unsupportedAutoMerge.has(host)) {
|
|
1119
|
+
return graphql(host, build(false), variables);
|
|
1120
|
+
}
|
|
1121
|
+
try {
|
|
1122
|
+
return await graphql(host, build(true), variables);
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
if (!isMissingAutoMerge(error))
|
|
1125
|
+
throw error;
|
|
1126
|
+
unsupportedAutoMerge.add(host);
|
|
1127
|
+
return graphql(host, build(false), variables);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
async function discussionRequirement(host, node) {
|
|
1131
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1132
|
+
let after;
|
|
1133
|
+
let unknown = false;
|
|
1134
|
+
for (let page = 0;page < GITHUB_MAX_PAGES; page++) {
|
|
1135
|
+
const response = await graphql(host, query(`query($owner:String!,$repo:String!,$branch:String!,$after:String) {
|
|
1136
|
+
repository(owner:$owner,name:$repo) {
|
|
1137
|
+
ref(qualifiedName:$branch) {
|
|
1138
|
+
branchProtectionRule { requiresConversationResolution }
|
|
1139
|
+
rules(first:50,after:$after) {
|
|
1140
|
+
nodes { type repositoryRuleset { enforcement } parameters { ... on PullRequestParameters { requiredReviewThreadResolution } } }
|
|
1141
|
+
pageInfo { hasNextPage endCursor }
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}`), { owner, repo, branch: `refs/heads/${node.baseRefName}`, ...after ? { after } : {} }).catch(() => {
|
|
1146
|
+
return;
|
|
1147
|
+
});
|
|
1148
|
+
const ref = response?.repository?.ref;
|
|
1149
|
+
if (ref?.branchProtectionRule?.requiresConversationResolution)
|
|
1150
|
+
return true;
|
|
1151
|
+
const rules = ref?.rules;
|
|
1152
|
+
if (!rules?.pageInfo)
|
|
1153
|
+
return;
|
|
1154
|
+
for (const rule of rules.nodes) {
|
|
1155
|
+
if (rule.type !== "PULL_REQUEST")
|
|
1156
|
+
continue;
|
|
1157
|
+
const required = rule.parameters?.requiredReviewThreadResolution;
|
|
1158
|
+
const enforcement = rule.repositoryRuleset?.enforcement;
|
|
1159
|
+
if (enforcement === "ACTIVE" && required === true)
|
|
1160
|
+
return true;
|
|
1161
|
+
if (!enforcement || required === undefined)
|
|
1162
|
+
unknown = true;
|
|
1163
|
+
}
|
|
1164
|
+
if (!rules.pageInfo.hasNextPage)
|
|
1165
|
+
return unknown ? undefined : false;
|
|
1166
|
+
const cursor = rules.pageInfo.endCursor;
|
|
1167
|
+
if (!cursor || cursor === after)
|
|
1168
|
+
return;
|
|
1169
|
+
after = cursor;
|
|
1170
|
+
}
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
async function threads(host, node) {
|
|
1174
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1175
|
+
const items = [...node.reviewThreads.nodes];
|
|
1176
|
+
let page = node.reviewThreads.pageInfo;
|
|
1177
|
+
for (let count = 1;page?.hasNextPage && page.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1178
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1179
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1180
|
+
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
1181
|
+
} } }`), { owner, repo, number: node.number, after: page.endCursor });
|
|
1182
|
+
const next = data.repository?.pullRequest?.reviewThreads;
|
|
1183
|
+
if (!next)
|
|
1184
|
+
break;
|
|
1185
|
+
items.push(...next.nodes);
|
|
1186
|
+
page = next.pageInfo;
|
|
1187
|
+
}
|
|
1188
|
+
return {
|
|
1189
|
+
unresolved: items.filter((thread) => !thread.isResolved).length,
|
|
1190
|
+
complete: !page?.hasNextPage
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
async function contexts(host, node) {
|
|
1194
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1195
|
+
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
|
|
1196
|
+
const items = [...rollup?.nodes ?? []];
|
|
1197
|
+
let cursor = rollup?.pageInfo;
|
|
1198
|
+
for (let count = 1;cursor?.hasNextPage && cursor.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1199
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
1200
|
+
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
1201
|
+
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 } }
|
|
1202
|
+
} } } } }`), { owner, repo, oid: node.headRefOid, after: cursor.endCursor });
|
|
1203
|
+
const next = data.repository?.object?.statusCheckRollup?.contexts;
|
|
1204
|
+
if (!next)
|
|
1205
|
+
break;
|
|
1206
|
+
items.push(...next.nodes);
|
|
1207
|
+
cursor = next.pageInfo;
|
|
1208
|
+
}
|
|
1209
|
+
return { nodes: items, complete: !cursor?.hasNextPage };
|
|
1210
|
+
}
|
|
1211
|
+
async function reviewers(host, node) {
|
|
1212
|
+
const nodes = [...node.reviewRequests.nodes];
|
|
1213
|
+
let reviewerPage = node.reviewRequests.pageInfo;
|
|
1214
|
+
for (let count = 1;reviewerPage?.hasNextPage && count < GITHUB_MAX_PAGES; count++) {
|
|
1215
|
+
if (!reviewerPage.endCursor) {
|
|
1216
|
+
return { nodes, pageInfo: { hasNextPage: true } };
|
|
1217
|
+
}
|
|
1218
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1219
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1220
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1221
|
+
reviewRequests(first:100,after:$after) {
|
|
1222
|
+
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
1223
|
+
pageInfo { hasNextPage endCursor }
|
|
1224
|
+
}
|
|
1225
|
+
} }
|
|
1226
|
+
}`), { owner, repo, number: node.number, after: reviewerPage.endCursor });
|
|
1227
|
+
const next = data.repository?.pullRequest?.reviewRequests;
|
|
1228
|
+
if (!next)
|
|
1229
|
+
return { nodes, pageInfo: { hasNextPage: true } };
|
|
1230
|
+
nodes.push(...next.nodes);
|
|
1231
|
+
reviewerPage = next.pageInfo;
|
|
1232
|
+
}
|
|
1233
|
+
return { nodes, pageInfo: reviewerPage };
|
|
1234
|
+
}
|
|
1235
|
+
async function opinionatedReviews(host, node) {
|
|
1236
|
+
if (!node.latestOpinionatedReviews?.pageInfo)
|
|
1237
|
+
return { nodes: [...node.latestOpinionatedReviews?.nodes ?? []], complete: false };
|
|
1238
|
+
const nodes = [...node.latestOpinionatedReviews.nodes];
|
|
1239
|
+
let page = node.latestOpinionatedReviews.pageInfo;
|
|
1240
|
+
for (let count = 1;page.hasNextPage && page.endCursor && count < GITHUB_MAX_PAGES; count++) {
|
|
1241
|
+
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
1242
|
+
const data = await graphql(host, query(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
1243
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
1244
|
+
latestOpinionatedReviews(first:100,after:$after) {
|
|
1245
|
+
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
1246
|
+
pageInfo { hasNextPage endCursor }
|
|
1247
|
+
}
|
|
1248
|
+
} }
|
|
1249
|
+
}`), { owner, repo, number: node.number, after: page.endCursor });
|
|
1250
|
+
const next = data.repository?.pullRequest?.latestOpinionatedReviews;
|
|
1251
|
+
if (!next?.pageInfo)
|
|
1252
|
+
return { nodes, complete: false };
|
|
1253
|
+
nodes.push(...next.nodes);
|
|
1254
|
+
page = next.pageInfo;
|
|
1255
|
+
}
|
|
1256
|
+
return { nodes, complete: !page.hasNextPage };
|
|
1257
|
+
}
|
|
1258
|
+
async function normalize(host, node) {
|
|
1259
|
+
const reviewerList = await reviewers(host, node);
|
|
1260
|
+
const [threadData, contextData, opinionated] = await Promise.all([
|
|
1261
|
+
threads(host, node),
|
|
1262
|
+
contexts(host, node),
|
|
1263
|
+
opinionatedReviews(host, node)
|
|
1264
|
+
]);
|
|
1265
|
+
const changes = changeRequests(reviewerList, opinionated);
|
|
1266
|
+
const awaitingReviewers = reviewerList.nodes.flatMap((request) => {
|
|
1267
|
+
const reviewer = request.requestedReviewer;
|
|
1268
|
+
if (reviewer?.__typename === "Bot")
|
|
1269
|
+
return [];
|
|
1270
|
+
const name = reviewer?.login || reviewer?.name;
|
|
1271
|
+
return name ? [name] : [];
|
|
1272
|
+
});
|
|
1273
|
+
const pendingHumanReviewers = reviewerList.nodes.flatMap((request) => {
|
|
1274
|
+
const reviewer = request.requestedReviewer;
|
|
1275
|
+
if (reviewer?.__typename !== "User" || !reviewer.login)
|
|
1276
|
+
return [];
|
|
1277
|
+
return [{ ...reviewer.id ? { id: reviewer.id } : {}, username: reviewer.login }];
|
|
1278
|
+
});
|
|
1279
|
+
return {
|
|
1280
|
+
forge: "github",
|
|
1281
|
+
iid: String(node.number),
|
|
1282
|
+
title: node.title,
|
|
1283
|
+
url: node.url,
|
|
1284
|
+
state: node.state === "OPEN" ? "opened" : node.state.toLowerCase(),
|
|
1285
|
+
draft: node.isDraft,
|
|
1286
|
+
conflicts: node.mergeable === "CONFLICTING",
|
|
1287
|
+
conflictsKnown: node.mergeable !== "UNKNOWN",
|
|
1288
|
+
approved: node.reviewDecision === "APPROVED" && awaitingReviewers.length === 0 && changes.changesRequested !== true,
|
|
1289
|
+
reviewDecision: node.reviewDecision ?? undefined,
|
|
1290
|
+
...node.autoMergeRequest === undefined ? {} : { autoMergeEnabled: node.autoMergeRequest !== null },
|
|
1291
|
+
...changes,
|
|
1292
|
+
copilotReview: copilotReview({ ...node, reviewRequests: reviewerList }),
|
|
1293
|
+
awaitingReviewers,
|
|
1294
|
+
pendingHumanReviewers,
|
|
1295
|
+
reviewersComplete: !!reviewerList.pageInfo && !reviewerList.pageInfo.hasNextPage,
|
|
1296
|
+
approvalsComplete: !!reviewerList.pageInfo && !reviewerList.pageInfo.hasNextPage && opinionated.complete,
|
|
1297
|
+
reviewerIDs: [
|
|
1298
|
+
...new Set([
|
|
1299
|
+
...reviewerList.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" ? request.requestedReviewer.id ?? [] : []),
|
|
1300
|
+
...[...node.latestReviews?.nodes ?? [], ...opinionated.nodes].flatMap((review) => !review?.author?.__typename || review.author.__typename === "User" ? review?.author?.id ?? [] : [])
|
|
1301
|
+
])
|
|
1302
|
+
],
|
|
1303
|
+
approvers: normalizeGitHubApprovers(node, reviewerList, opinionated.nodes),
|
|
1304
|
+
targetProject: node.baseRepository.nameWithOwner,
|
|
1305
|
+
targetBranch: node.baseRefName,
|
|
1306
|
+
...node.headRepository ? { sourceProject: node.headRepository.nameWithOwner } : {},
|
|
1307
|
+
sourceBranch: node.headRefName,
|
|
1308
|
+
headSha: node.headRefOid,
|
|
1309
|
+
...node.author?.id ? { authorID: node.author.id } : {},
|
|
1310
|
+
...node.author?.login ? { authorUsername: node.author.login } : {},
|
|
1311
|
+
updatedAt: node.updatedAt,
|
|
1312
|
+
pipeline: contextData.nodes.length || !contextData.complete ? checks(contextData.nodes, contextData.complete, `${node.url}/checks`, node.headRefOid) : undefined,
|
|
1313
|
+
unresolvedThreads: threadData.unresolved,
|
|
1314
|
+
discussionResolutionRequired: threadData.unresolved > 0 ? await discussionRequirement(host, node) : undefined,
|
|
1315
|
+
threadsComplete: threadData.complete
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
async function discussion(ref, { id }) {
|
|
1319
|
+
let thread;
|
|
1320
|
+
const replies = await discussionPages(10, async (after) => {
|
|
1321
|
+
const data = await graphql(ref.host, query(`
|
|
1322
|
+
query($id:ID!,$after:String) {
|
|
1323
|
+
node(id:$id) { ... on PullRequestReviewThread {
|
|
1324
|
+
id isResolved path line pullRequest { url }
|
|
1325
|
+
comments(first:20,after:$after) {
|
|
1326
|
+
pageInfo { hasNextPage endCursor }
|
|
1327
|
+
nodes { id url body createdAt isMinimized author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
1328
|
+
}
|
|
1329
|
+
} }
|
|
1330
|
+
}`), { id, ...after ? { after } : {} });
|
|
1331
|
+
const candidate = data.node;
|
|
1332
|
+
const owner = candidate?.pullRequest && parseGitHubUrl(candidate.pullRequest.url);
|
|
1333
|
+
if (!candidate || candidate.id !== id || !owner || owner.host !== ref.host || owner.project.toLowerCase() !== ref.project.toLowerCase() || owner.iid !== ref.iid) {
|
|
1334
|
+
thread = undefined;
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
thread = candidate;
|
|
1338
|
+
return thread.isResolved ? undefined : thread.comments;
|
|
1339
|
+
});
|
|
1340
|
+
if (!thread)
|
|
1341
|
+
return;
|
|
1342
|
+
if (thread.isResolved)
|
|
1343
|
+
return "resolved";
|
|
1344
|
+
const notes = [];
|
|
1345
|
+
let incomplete = !replies.complete;
|
|
1346
|
+
for (const comment of replies.nodes) {
|
|
1347
|
+
const author = comment.author;
|
|
1348
|
+
if (!comment.id || comment.isMinimized || !author?.login || typeof comment.body !== "string") {
|
|
1349
|
+
incomplete = true;
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1352
|
+
notes.push({
|
|
1353
|
+
id: comment.id,
|
|
1354
|
+
url: comment.url,
|
|
1355
|
+
authorID: author.id,
|
|
1356
|
+
username: botUsername(author.login, author.__typename),
|
|
1357
|
+
bot: author.__typename === "Bot" || author.login.endsWith("[bot]"),
|
|
1358
|
+
body: comment.body,
|
|
1359
|
+
createdAt: comment.createdAt,
|
|
1360
|
+
path: thread.path ?? undefined,
|
|
1361
|
+
line: thread.line ?? undefined
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
return {
|
|
1365
|
+
id,
|
|
1366
|
+
notes,
|
|
1367
|
+
url: notes.find((note) => note.url)?.url,
|
|
1368
|
+
incomplete: incomplete || notes.length === 0
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
async function unresolvedDiscussions(ref) {
|
|
1372
|
+
const [owner, repo] = ref.project.split("/");
|
|
1373
|
+
const number = Number(ref.iid);
|
|
1374
|
+
if (!owner || !repo || !Number.isInteger(number) || number < 1)
|
|
1375
|
+
return;
|
|
1376
|
+
const list = await discussionPages(GITHUB_MAX_PAGES, async (after) => {
|
|
1377
|
+
const data = await graphql(ref.host, query(`query($owner:String!,$repo:String!,$number:Int!${after ? ",$after:String!" : ""}) {
|
|
1378
|
+
repository(owner:$owner,name:$repo) {
|
|
1379
|
+
pullRequest(number:$number) {
|
|
1380
|
+
reviewThreads(first:100${after ? ",after:$after" : ""}) {
|
|
1381
|
+
nodes { id isResolved }
|
|
1382
|
+
pageInfo { hasNextPage endCursor }
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}`), { owner, repo, number, ...after ? { after } : {} });
|
|
1387
|
+
return data.repository?.pullRequest?.reviewThreads;
|
|
1388
|
+
});
|
|
1389
|
+
const discussions = [];
|
|
1390
|
+
const candidates = list.nodes.filter(({ id, isResolved }) => id && !isResolved);
|
|
1391
|
+
for (const { id } of candidates.slice(0, MAX_REVIEW_THREADS)) {
|
|
1392
|
+
const thread = await discussion(ref, { id }).catch(() => {
|
|
1393
|
+
return;
|
|
1394
|
+
});
|
|
1395
|
+
if (thread !== "resolved")
|
|
1396
|
+
discussions.push(thread ?? { id, notes: [], incomplete: true });
|
|
1397
|
+
}
|
|
1398
|
+
return { complete: list.complete && candidates.length <= MAX_REVIEW_THREADS, discussions };
|
|
1399
|
+
}
|
|
1400
|
+
async function fetchByProjects(projects, number) {
|
|
1401
|
+
for (const project of projects) {
|
|
1402
|
+
const [owner, repo] = project.path.split("/");
|
|
1403
|
+
const data = await queryPull(project.host, (includeAutoMerge) => query(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
1404
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${githubPullFields(includeAutoMerge)} } }
|
|
1405
|
+
}`), { owner, repo, number: Number(number) });
|
|
1406
|
+
const node = data.repository?.pullRequest;
|
|
1407
|
+
if (node)
|
|
1408
|
+
return normalize(project.host, node);
|
|
1409
|
+
}
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
async function fetchByBranch(source, targets, sourceBranch) {
|
|
1413
|
+
const found = new Map;
|
|
1414
|
+
for (const target of targets) {
|
|
1415
|
+
const [owner, repo] = target.path.split("/");
|
|
1416
|
+
let after;
|
|
1417
|
+
let complete = false;
|
|
1418
|
+
for (let page = 0;page < GITHUB_MAX_PAGES; page++) {
|
|
1419
|
+
const data = await queryPull(target.host, (includeAutoMerge) => query(`query($owner:String!,$repo:String!,$branch:String!${after ? ",$after:String!" : ""}) {
|
|
1420
|
+
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${after ? ",after:$after" : ""}) {
|
|
1421
|
+
nodes { ${githubPullFields(includeAutoMerge)} } pageInfo { hasNextPage endCursor }
|
|
1422
|
+
} } }`), { owner, repo, branch: sourceBranch, ...after ? { after } : {} });
|
|
1423
|
+
const pulls = data.repository?.pullRequests;
|
|
1424
|
+
if (!pulls)
|
|
1425
|
+
throw new ForgeError("request", "GitHub repository unavailable");
|
|
1426
|
+
for (const node of pulls.nodes) {
|
|
1427
|
+
if (node.headRepository?.nameWithOwner.toLowerCase() !== source.path.toLowerCase())
|
|
1428
|
+
continue;
|
|
1429
|
+
if (!found.has(node.url))
|
|
1430
|
+
found.set(node.url, await normalize(target.host, node));
|
|
1431
|
+
}
|
|
1432
|
+
if (!pulls.pageInfo?.hasNextPage) {
|
|
1433
|
+
complete = true;
|
|
1434
|
+
break;
|
|
1435
|
+
}
|
|
1436
|
+
after = pulls.pageInfo.endCursor;
|
|
1437
|
+
if (!after)
|
|
1438
|
+
break;
|
|
1439
|
+
}
|
|
1440
|
+
if (!complete)
|
|
1441
|
+
throw new ForgeError("request", "GitHub PR discovery exceeded its pagination limit");
|
|
1442
|
+
}
|
|
1443
|
+
return [...found.values()].sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
1444
|
+
}
|
|
1445
|
+
async function viewer(host) {
|
|
1446
|
+
const data = await graphql(host, GITHUB_VIEWER_QUERY, {});
|
|
1447
|
+
const user = data.viewer;
|
|
1448
|
+
if (!user?.id && !user?.login)
|
|
1449
|
+
return;
|
|
1450
|
+
return {
|
|
1451
|
+
...user.id ? { id: user.id } : {},
|
|
1452
|
+
...user.login ? { username: user.login } : {}
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
return {
|
|
1456
|
+
forge: "github",
|
|
1457
|
+
fetchRequest: (ref) => fetchByProjects([{ host: ref.host, path: ref.project }], ref.iid),
|
|
1458
|
+
fetchByProjects,
|
|
1459
|
+
fetchByBranch,
|
|
1460
|
+
unresolvedDiscussions,
|
|
1461
|
+
discussion,
|
|
1462
|
+
viewer
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
// packages/_merge-readiness/src/transports/http.ts
|
|
1466
|
+
var LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
1467
|
+
// packages/forgekeeper/src/forge.ts
|
|
1468
|
+
var ownedBy = (kind) => (request) => request.forge === kind;
|
|
1469
|
+
var titlePrefix = (title) => title?.match(/^\[[^\]]*\]/)?.[0] ?? "";
|
|
1470
|
+
function prefixReferences(title, sigil) {
|
|
1471
|
+
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)] : []);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// packages/forgekeeper/src/review-summary.ts
|
|
1475
|
+
var MESSAGE_PREFIX = "msg_forgekeeper_";
|
|
1476
|
+
var SUMMARY_PREFIX = `${MESSAGE_PREFIX}summary_`;
|
|
1477
|
+
var EXCERPT_RADIUS = 10;
|
|
1478
|
+
var MAX_EXCERPT_FILES = 10;
|
|
1479
|
+
var MAX_LINE = 300;
|
|
1480
|
+
var LINKED_NOTE_TOOL = "fetch_linked_review_note";
|
|
1481
|
+
var MAX_LINKED_NOTES = 5;
|
|
1482
|
+
var MAX_LINK_LENGTH = 300;
|
|
1483
|
+
function excerpt(content, line) {
|
|
1484
|
+
const lines = content.split(`
|
|
1485
|
+
`);
|
|
1486
|
+
if (line < 1 || line > lines.length)
|
|
1487
|
+
return;
|
|
1488
|
+
const start = Math.max(1, line - EXCERPT_RADIUS);
|
|
1489
|
+
const end = Math.min(lines.length, line + EXCERPT_RADIUS);
|
|
1490
|
+
return lines.slice(start - 1, end).map((text, index) => {
|
|
1491
|
+
const number = start + index;
|
|
1492
|
+
const shown = text.length > MAX_LINE ? `${text.slice(0, MAX_LINE)}\u2026` : text;
|
|
1493
|
+
return `${number === line ? ">" : " "}${number}: ${shown}`;
|
|
1494
|
+
}).join(`
|
|
154
1495
|
`);
|
|
155
1496
|
}
|
|
156
1497
|
var TOOL_RULES = [
|
|
@@ -969,218 +2310,29 @@ async function subscribeToNotes(run, directory, request, events, signal, socket
|
|
|
969
2310
|
heartbeat();
|
|
970
2311
|
if (message.type === "welcome")
|
|
971
2312
|
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
|
|
2313
|
+
if (message.type === "disconnect")
|
|
2314
|
+
finish();
|
|
2315
|
+
if (message.identifier !== identifier)
|
|
2316
|
+
return;
|
|
2317
|
+
if (message.type === "reject_subscription")
|
|
2318
|
+
finish();
|
|
2319
|
+
if (message.type === "confirm_subscription" && !confirmed) {
|
|
2320
|
+
confirmed = true;
|
|
2321
|
+
heartbeat();
|
|
2322
|
+
events.connected();
|
|
2323
|
+
}
|
|
2324
|
+
if (confirmed && message.message?.event === "updated")
|
|
2325
|
+
events.changed();
|
|
2326
|
+
} catch {
|
|
2327
|
+
finish();
|
|
2328
|
+
}
|
|
1120
2329
|
};
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
}
|
|
1125
|
-
function reviewIndicators(request) {
|
|
1126
|
-
const count = approvalCount(request);
|
|
1127
|
-
const next = waitingOn(request);
|
|
1128
|
-
return [
|
|
1129
|
-
...count ? [count] : [],
|
|
1130
|
-
...request.changesRequested === true ? [{ text: "changes requested", tone: "warning", essential: true }] : [],
|
|
1131
|
-
...request.approved && !request.awaitingReviewers.length ? [{ text: "approved", tone: "success" }] : [],
|
|
1132
|
-
...next ? [next] : []
|
|
1133
|
-
];
|
|
2330
|
+
if (signal.aborted)
|
|
2331
|
+
finish();
|
|
2332
|
+
});
|
|
1134
2333
|
}
|
|
1135
2334
|
|
|
1136
2335
|
// 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
2336
|
function mergeRequestNumbersQuery(projectCount) {
|
|
1185
2337
|
const variables = Array.from({ length: projectCount }, (_, index) => `$p${index}: ID!`).join(", ");
|
|
1186
2338
|
const projects = Array.from({ length: projectCount }, (_, index) => `p${index}: project(fullPath: $p${index}) {
|
|
@@ -1249,55 +2401,12 @@ function workItemStatesQuery(count) {
|
|
|
1249
2401
|
}
|
|
1250
2402
|
}`);
|
|
1251
2403
|
}
|
|
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
2404
|
var MARK_READY_MUTATION = query(`mutation($project: ID!, $iid: String!) {
|
|
1268
2405
|
mergeRequestSetDraft(input: { projectPath: $project, iid: $iid, draft: false }) {
|
|
1269
2406
|
mergeRequest { draft }
|
|
1270
2407
|
errors
|
|
1271
2408
|
}
|
|
1272
2409
|
}`);
|
|
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
2410
|
var RESOLVE_DISCUSSION_MUTATION = query(`mutation($id: DiscussionID!) {
|
|
1302
2411
|
discussionToggleResolve(input: { id: $id, resolve: true }) {
|
|
1303
2412
|
discussion { id resolved }
|
|
@@ -1306,20 +2415,6 @@ var RESOLVE_DISCUSSION_MUTATION = query(`mutation($id: DiscussionID!) {
|
|
|
1306
2415
|
}`);
|
|
1307
2416
|
var unsupportedApprovedAtHosts = new Set;
|
|
1308
2417
|
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
2418
|
var isResponse = (body) => typeof body === "object" && body !== null && (!("errors" in body) || Array.isArray(body.errors)) && (!("data" in body) || typeof body.data === "object");
|
|
1324
2419
|
function glabGraphQL(run, cwd) {
|
|
1325
2420
|
return async (host, query, variables) => {
|
|
@@ -1331,45 +2426,36 @@ function glabGraphQL(run, cwd) {
|
|
|
1331
2426
|
try {
|
|
1332
2427
|
body = JSON.parse(result.stdout);
|
|
1333
2428
|
} catch {
|
|
1334
|
-
throw
|
|
2429
|
+
throw classifyGitLabError(result.stderr, result.code);
|
|
1335
2430
|
}
|
|
1336
2431
|
if (!isResponse(body))
|
|
1337
|
-
throw
|
|
2432
|
+
throw classifyGitLabError(result.stderr || "Unexpected GitLab response", result.code);
|
|
1338
2433
|
if (body.errors?.length)
|
|
1339
|
-
throw
|
|
2434
|
+
throw classifyGitLabError(String(body.errors[0]?.message ?? ""), result.code);
|
|
1340
2435
|
if (result.code !== 0)
|
|
1341
|
-
throw
|
|
2436
|
+
throw classifyGitLabError(result.stderr, result.code);
|
|
1342
2437
|
if (!body.data)
|
|
1343
|
-
throw
|
|
2438
|
+
throw classifyGitLabError("GitLab returned no data", result.code);
|
|
1344
2439
|
return body.data;
|
|
1345
2440
|
};
|
|
1346
2441
|
}
|
|
1347
|
-
var countUnresolved = (page) => page.nodes.filter((discussion) => discussion.resolvable && !discussion.resolved).length;
|
|
1348
2442
|
var gitlabTraits = {
|
|
1349
2443
|
kind: "gitlab",
|
|
1350
2444
|
noun: "MR",
|
|
1351
2445
|
fullNoun: "merge request",
|
|
1352
2446
|
ci: "pipeline",
|
|
1353
|
-
recognizes:
|
|
2447
|
+
recognizes: isGitLabHost,
|
|
1354
2448
|
open: (run, directory) => new GitLabForge(glabGraphQL(run, directory), unsupportedApprovedAtHosts, unsupportedExtendedStatusHosts),
|
|
1355
2449
|
owns: ownedBy("gitlab"),
|
|
1356
|
-
parseUrl:
|
|
2450
|
+
parseUrl: parseGitLabUrl,
|
|
1357
2451
|
parseIssueUrl: (url) => parseWebUrl("gitlab", url, /^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),
|
|
1358
2452
|
reference: (iid) => `!${iid}`,
|
|
1359
2453
|
issueReference: (iid) => `#${iid}`,
|
|
1360
2454
|
titleReferences: (title) => prefixReferences(title, "!"),
|
|
1361
2455
|
indicators: () => [],
|
|
1362
2456
|
reviewIndicators,
|
|
1363
|
-
approvalsSatisfied,
|
|
1364
|
-
mergeBlocker,
|
|
1365
2457
|
readyToMerge,
|
|
1366
2458
|
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
2459
|
details(request) {
|
|
1374
2460
|
const requirements = request.approvalRequirementsSatisfied === null ? "unknown" : yesNo(request.approvalRequirementsSatisfied);
|
|
1375
2461
|
const lines = [
|
|
@@ -1440,158 +2526,27 @@ var gitlabTraits = {
|
|
|
1440
2526
|
return ref ? fetchLinkedNote(glabGraphQL(run, directory), ref.host, url) : undefined;
|
|
1441
2527
|
}
|
|
1442
2528
|
}
|
|
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
|
-
}
|
|
2529
|
+
};
|
|
2530
|
+
var DUO_FEEDBACK2 = new Set(["REVIEWED", "REQUESTED_CHANGES"]);
|
|
2531
|
+
function duoState(state) {
|
|
2532
|
+
if (state === "REVIEW_STARTED")
|
|
2533
|
+
return "running";
|
|
2534
|
+
return DUO_FEEDBACK2.has(state) ? "feedback" : "settled";
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
class GitLabForge {
|
|
2538
|
+
traits = gitlabTraits;
|
|
2539
|
+
graphql;
|
|
2540
|
+
source;
|
|
2541
|
+
constructor(graphql, unsupportedApprovedAt = new Set, unsupportedExtendedStatus = new Set) {
|
|
2542
|
+
this.graphql = typed(graphql);
|
|
2543
|
+
this.source = createGitLabSource(graphql, {
|
|
2544
|
+
unsupportedApprovedAt,
|
|
2545
|
+
unsupportedExtendedStatus
|
|
1592
2546
|
});
|
|
1593
|
-
|
|
1594
|
-
|
|
2547
|
+
}
|
|
2548
|
+
findByBranch(repository) {
|
|
2549
|
+
return this.source.fetchByBranch(repository.source, repository.targets, repository.sourceBranch);
|
|
1595
2550
|
}
|
|
1596
2551
|
async findNumberByBranch(repository) {
|
|
1597
2552
|
const { source, targets, sourceBranch } = repository;
|
|
@@ -1728,78 +2683,11 @@ class GitLabForge {
|
|
|
1728
2683
|
if (!result?.mergeRequest || result.mergeRequest.draft !== false)
|
|
1729
2684
|
throw new ForgeError("request", "Could not mark the GitLab merge request as ready");
|
|
1730
2685
|
}
|
|
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 };
|
|
2686
|
+
unresolvedDiscussions(ref) {
|
|
2687
|
+
return this.source.unresolvedDiscussions(ref);
|
|
1752
2688
|
}
|
|
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
|
-
};
|
|
2689
|
+
discussion(ref, thread) {
|
|
2690
|
+
return this.source.discussion(ref, thread);
|
|
1803
2691
|
}
|
|
1804
2692
|
async resolveDiscussion(ref, discussionID, options) {
|
|
1805
2693
|
await options?.beforeMutate?.();
|
|
@@ -1812,208 +2700,12 @@ class GitLabForge {
|
|
|
1812
2700
|
if (!result?.discussion || result.discussion.resolved !== true)
|
|
1813
2701
|
throw new ForgeError("request", "Could not resolve the GitLab discussion");
|
|
1814
2702
|
}
|
|
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;
|
|
2703
|
+
findByNumber(projects, iid) {
|
|
2704
|
+
return this.source.fetchByProjects(projects, iid);
|
|
1999
2705
|
}
|
|
2000
|
-
}
|
|
2001
|
-
|
|
2002
|
-
// 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;
|
|
2706
|
+
}
|
|
2707
|
+
|
|
2708
|
+
// packages/forgekeeper/src/adapters/github/adapter.ts
|
|
2017
2709
|
function ghGraphQL(run, cwd) {
|
|
2018
2710
|
return async (host, query, variables) => {
|
|
2019
2711
|
const args = ["api", "graphql", "--hostname", host, "-f", `query=${query}`];
|
|
@@ -2024,111 +2716,18 @@ function ghGraphQL(run, cwd) {
|
|
|
2024
2716
|
try {
|
|
2025
2717
|
body = JSON.parse(result.stdout);
|
|
2026
2718
|
} catch {
|
|
2027
|
-
throw
|
|
2719
|
+
throw classifyGitHubError(result.stderr, result.code);
|
|
2028
2720
|
}
|
|
2029
2721
|
const errors = (body.errors ?? []).filter((error) => error.type !== "NOT_FOUND");
|
|
2030
2722
|
if (!body.data || errors.length || result.code !== 0 && !body.errors?.length) {
|
|
2031
|
-
throw
|
|
2723
|
+
throw classifyGitHubError(errors[0]?.message ?? result.stderr, result.code);
|
|
2032
2724
|
}
|
|
2033
2725
|
return body.data;
|
|
2034
2726
|
};
|
|
2035
2727
|
}
|
|
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);
|
|
2728
|
+
var unsupportedAutoMergeHosts = new Set;
|
|
2729
|
+
function parseGitHubIssueUrl(url) {
|
|
2730
|
+
const ref = parseWebUrl("github", url, /^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/);
|
|
2132
2731
|
return ref && !gitlabTraits.recognizes(ref.host) ? ref : undefined;
|
|
2133
2732
|
}
|
|
2134
2733
|
var githubTraits = {
|
|
@@ -2137,17 +2736,14 @@ var githubTraits = {
|
|
|
2137
2736
|
fullNoun: "pull request",
|
|
2138
2737
|
ci: "checks",
|
|
2139
2738
|
recognizes: () => false,
|
|
2140
|
-
open: (run, directory) => new GitHubForge(ghGraphQL(run, directory)),
|
|
2739
|
+
open: (run, directory) => new GitHubForge(ghGraphQL(run, directory), unsupportedAutoMergeHosts),
|
|
2141
2740
|
owns: ownedBy("github"),
|
|
2142
|
-
parseUrl:
|
|
2143
|
-
parseIssueUrl:
|
|
2741
|
+
parseUrl: parseGitHubUrl,
|
|
2742
|
+
parseIssueUrl: parseGitHubIssueUrl,
|
|
2144
2743
|
reference: (iid) => `#${iid}`,
|
|
2145
2744
|
issueReference: (iid) => `#${iid}`,
|
|
2146
2745
|
titleReferences: (title) => prefixReferences(title, "#"),
|
|
2147
2746
|
hasRequestedChanges: (request) => request.changesRequested === true || request.reviewDecision === "CHANGES_REQUESTED" ? true : request.changesRequested,
|
|
2148
|
-
approvalStatus: (request) => ({
|
|
2149
|
-
reviewDecision: request.reviewDecision ?? "unknown"
|
|
2150
|
-
}),
|
|
2151
2747
|
indicators: (request) => githubTraits.hasRequestedChanges(request) === true ? [{ text: "changes requested", tone: "warning", essential: true }] : [],
|
|
2152
2748
|
details: (request) => [
|
|
2153
2749
|
`Review decision: ${request.reviewDecision ? humanize(request.reviewDecision) : "not reported"}`
|
|
@@ -2191,181 +2787,21 @@ function copilotStatus(review) {
|
|
|
2191
2787
|
const completed = review.reviewID ? { id: review.reviewID, feedback, label } : undefined;
|
|
2192
2788
|
if (review.requested)
|
|
2193
2789
|
return { state: "running", label: "reviewing", completed };
|
|
2194
|
-
if (!completed)
|
|
2195
|
-
return;
|
|
2196
|
-
return { state: feedback ? "feedback" : "settled", label, completed };
|
|
2197
|
-
}
|
|
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
|
-
|
|
2309
|
-
class GitHubForge {
|
|
2310
|
-
traits = githubTraits;
|
|
2311
|
-
graphql;
|
|
2312
|
-
constructor(graphql) {
|
|
2313
|
-
this.graphql = typed(graphql);
|
|
2314
|
-
}
|
|
2315
|
-
async discussionRequirement(host, node) {
|
|
2316
|
-
const [owner, repo] = node.baseRepository.nameWithOwner.split("/");
|
|
2317
|
-
let after;
|
|
2318
|
-
let unknown = false;
|
|
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
|
-
}
|
|
2790
|
+
if (!completed)
|
|
2368
2791
|
return;
|
|
2792
|
+
return { state: feedback ? "feedback" : "settled", label, completed };
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
class GitHubForge {
|
|
2796
|
+
traits = githubTraits;
|
|
2797
|
+
graphql;
|
|
2798
|
+
source;
|
|
2799
|
+
constructor(graphql, unsupportedAutoMerge = new Set) {
|
|
2800
|
+
this.graphql = typed(graphql);
|
|
2801
|
+
this.source = createGitHubSource(graphql, { unsupportedAutoMerge });
|
|
2802
|
+
}
|
|
2803
|
+
findByNumber(projects, number) {
|
|
2804
|
+
return this.source.fetchByProjects(projects, number);
|
|
2369
2805
|
}
|
|
2370
2806
|
async findNumberByBranch(repository) {
|
|
2371
2807
|
let newest;
|
|
@@ -2520,87 +2956,11 @@ class GitHubForge {
|
|
|
2520
2956
|
if (!updated || updated.isDraft)
|
|
2521
2957
|
throw new ForgeError("request", "Could not mark the GitHub pull request as ready");
|
|
2522
2958
|
}
|
|
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 };
|
|
2959
|
+
unresolvedDiscussions(ref) {
|
|
2960
|
+
return this.source.unresolvedDiscussions(ref);
|
|
2551
2961
|
}
|
|
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
|
-
};
|
|
2962
|
+
discussion(ref, thread) {
|
|
2963
|
+
return this.source.discussion(ref, thread);
|
|
2604
2964
|
}
|
|
2605
2965
|
async resolveDiscussion(ref, discussionID, options) {
|
|
2606
2966
|
await options?.beforeMutate?.();
|
|
@@ -2611,175 +2971,8 @@ class GitHubForge {
|
|
|
2611
2971
|
if (!thread || !thread.isResolved)
|
|
2612
2972
|
throw new ForgeError("request", "Could not resolve the GitHub review thread");
|
|
2613
2973
|
}
|
|
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
|
-
};
|
|
2974
|
+
findByBranch(repository) {
|
|
2975
|
+
return this.source.fetchByBranch(repository.source, repository.targets, repository.sourceBranch);
|
|
2783
2976
|
}
|
|
2784
2977
|
}
|
|
2785
2978
|
|
|
@@ -2788,32 +2981,6 @@ var registry = { gitlab: gitlabTraits, github: githubTraits };
|
|
|
2788
2981
|
var kinds = Object.keys(registry);
|
|
2789
2982
|
var traitsOf = (request) => registry[request.forge];
|
|
2790
2983
|
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
2984
|
function sharedForge(forges) {
|
|
2818
2985
|
const unique = new Set;
|
|
2819
2986
|
for (const forge of forges) {
|
|
@@ -2983,36 +3150,6 @@ function snapshotForge(snapshot, fallback) {
|
|
|
2983
3150
|
function hasThreadReviewItem(items, url) {
|
|
2984
3151
|
return items.some((item) => item.url === url && canReviewBlockingThreads(item));
|
|
2985
3152
|
}
|
|
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
3153
|
var RUNNING = new Set([
|
|
3017
3154
|
"CREATED",
|
|
3018
3155
|
"WAITING_FOR_RESOURCE",
|
|
@@ -3708,9 +3845,6 @@ function connectStatus(rpc, options) {
|
|
|
3708
3845
|
}
|
|
3709
3846
|
var clientID = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
3710
3847
|
|
|
3711
|
-
// packages/forgekeeper/src/approval-watch.ts
|
|
3712
|
-
var APPROVAL_RETENTION = 30 * 24 * 60 * 60000;
|
|
3713
|
-
|
|
3714
3848
|
// packages/forgekeeper/src/review-preparation.ts
|
|
3715
3849
|
var PREPARE_PREFIX = `${MESSAGE_PREFIX}prepare_`;
|
|
3716
3850
|
var APPROVAL_STATUS_TOOL = "forgekeeper_approval_status";
|