@niwa-labs/forge 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/package.json +30 -4
- package/src/actions.ts +389 -0
- package/src/cockpit/actions.ts +94 -0
- package/src/cockpit/index.tsx +19 -0
- package/src/cockpit/page.tsx +158 -0
- package/src/cockpit/pulls.ts +103 -0
- package/src/flow.ts +232 -0
- package/src/gitlab.ts +263 -0
- package/src/index.ts +765 -0
- package/src/merge.ts +309 -0
- package/src/normalize.ts +186 -0
- package/src/observe.ts +464 -0
- package/src/prs.ts +122 -0
- package/src/queries.ts +152 -0
- package/src/record-types.ts +353 -0
- package/src/records.ts +8 -0
- package/src/secrets.ts +40 -0
- package/src/servers.ts +121 -0
- package/src/targets.ts +82 -0
- package/src/workflows/push-reaction.ts +59 -0
- package/test/actions.test.ts +235 -0
- package/test/cockpit-actions.test.ts +55 -0
- package/test/cockpit-pulls.test.ts +58 -0
- package/test/fake-gitlab.ts +452 -0
- package/test/flow.test.ts +239 -0
- package/test/gitlab.test.ts +91 -0
- package/test/merge.test.ts +251 -0
- package/test/observe.test.ts +454 -0
- package/test/prs.test.ts +125 -0
- package/test/push-reaction.test.ts +92 -0
- package/test/queries.test.ts +144 -0
- package/test/script-surface.test.ts +185 -0
- package/test/support.ts +109 -0
- package/test/targets.test.ts +42 -0
- package/tsconfig.json +15 -0
package/src/merge.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merging a pull request: the one forge action that cannot be taken back.
|
|
3
|
+
*
|
|
4
|
+
* The merge is asked with the head the caller expects, so a head that moved is refused by the server
|
|
5
|
+
* and not merged blind. A merge the server takes for later (an automatic merge when the pipeline
|
|
6
|
+
* succeeds, a place in a merge train) is recorded as armed, with the server's id and the action that
|
|
7
|
+
* calls it off: niwa cannot hold back what the server already has, so it shows it instead.
|
|
8
|
+
*
|
|
9
|
+
* Before the request leaves, `forge.pr.merge.started` is written with the operation. A call that was
|
|
10
|
+
* cut off is checked against it: without it the request was never sent; with it, the pull request is
|
|
11
|
+
* read back from the server and says what happened.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { seq } from "@niwa-labs/core";
|
|
15
|
+
import type { ActionContext, CheckResult, JournalReader, RecordType } from "@niwa-labs/core";
|
|
16
|
+
|
|
17
|
+
import { forgePrMergeCancel } from "./actions.ts";
|
|
18
|
+
import type { MergeOutcome, PendingMerge } from "./actions.ts";
|
|
19
|
+
import { ForgeError } from "./gitlab.ts";
|
|
20
|
+
import type { GitLab } from "./gitlab.ts";
|
|
21
|
+
import { finalShaOf } from "./normalize.ts";
|
|
22
|
+
import type { GitLabMr } from "./normalize.ts";
|
|
23
|
+
import { mergeKey, CancelRefused, CancelStarted, MergeRefused, MergeArmed, MergeDisarmed, MergeStarted, MergeSettled } from "./record-types.ts";
|
|
24
|
+
import type { MergeMethod, MergeWhen, PrRef, Repo } from "./record-types.ts";
|
|
25
|
+
import { projectPath } from "./servers.ts";
|
|
26
|
+
|
|
27
|
+
/** The server's own name of a merge request: `<host>/<path>!<n>`. */
|
|
28
|
+
export function externalIdOf(pr: PrRef): string {
|
|
29
|
+
return `${pr.repo.host}/${pr.repo.path}!${String(pr.number)}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The statuses a server refuses a merge with: not mergeable, a head that moved, nothing to do. */
|
|
33
|
+
const REFUSALS = new Set([405, 406, 409, 422]);
|
|
34
|
+
|
|
35
|
+
/** These failures occur before transmission or explicitly reject the HTTP request. */
|
|
36
|
+
function definitelyRejected(error: unknown): error is ForgeError {
|
|
37
|
+
if (!(error instanceof ForgeError)) return false;
|
|
38
|
+
return ["unknown-secret", "unsafe-secret", "rate-limited"].includes(error.code)
|
|
39
|
+
|| (error.status !== undefined && error.status >= 400 && error.status < 500 && error.status !== 408);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The commit a merged pull request left on its base; the head it was merged at when the server names none. */
|
|
43
|
+
function mergedSha(mr: GitLabMr, expectHead: string): string {
|
|
44
|
+
return finalShaOf(mr) ?? expectHead;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface MergeAsk {
|
|
48
|
+
readonly pr: PrRef;
|
|
49
|
+
readonly expectHead: string;
|
|
50
|
+
readonly method: MergeMethod;
|
|
51
|
+
readonly when: MergeWhen;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Ask the server to merge, and say how it went. */
|
|
55
|
+
export async function merge(gitlab: GitLab, ask: MergeAsk, ctx: Pick<ActionContext, "emit" | "operationId">): Promise<MergeOutcome> {
|
|
56
|
+
const { pr, expectHead, method, when } = ask;
|
|
57
|
+
const externalId = externalIdOf(pr);
|
|
58
|
+
await ctx.emit(MergeStarted, { operation: ctx.operationId, pr, expectHead, method, when });
|
|
59
|
+
const operation = ctx.operationId;
|
|
60
|
+
const refused = async (why: string): Promise<MergeOutcome> => {
|
|
61
|
+
await ctx.emit(MergeRefused, { pr, operation, reason: why, terminal: false, failed: false });
|
|
62
|
+
return { outcome: "refused", why };
|
|
63
|
+
};
|
|
64
|
+
const mrPath = projectPath(pr.repo, `/merge_requests/${String(pr.number)}`);
|
|
65
|
+
try {
|
|
66
|
+
if (when === "train") {
|
|
67
|
+
await gitlab.send("POST", projectPath(pr.repo, `/merge_trains/merge_requests/${String(pr.number)}`), {
|
|
68
|
+
sha: expectHead,
|
|
69
|
+
squash: method === "squash",
|
|
70
|
+
});
|
|
71
|
+
await ctx.emit(MergeArmed, { pr, operation, mode: "train", externalId, expectHead });
|
|
72
|
+
return { outcome: "queued", externalId, cancel: forgePrMergeCancel.name };
|
|
73
|
+
}
|
|
74
|
+
const mr = await gitlab.send<GitLabMr>("PUT", `${mrPath}/merge`, {
|
|
75
|
+
sha: expectHead,
|
|
76
|
+
squash: method === "squash",
|
|
77
|
+
...(when === "pipeline" ? { merge_when_pipeline_succeeds: true } : {}),
|
|
78
|
+
});
|
|
79
|
+
if (mr.state === "merged") {
|
|
80
|
+
const sha = mergedSha(mr, expectHead);
|
|
81
|
+
await ctx.emit(MergeSettled, { pr, operation, externalId, outcome: "merged", mergeSha: sha });
|
|
82
|
+
return { outcome: "merged", sha, externalId };
|
|
83
|
+
}
|
|
84
|
+
if (mr.merge_when_pipeline_succeeds === true) {
|
|
85
|
+
await ctx.emit(MergeArmed, { pr, operation, mode: "auto-merge", externalId, expectHead });
|
|
86
|
+
return { outcome: "armed", externalId, cancel: forgePrMergeCancel.name };
|
|
87
|
+
}
|
|
88
|
+
return refused(`the server answered the merge with a pull request that is ${mr.state} and not merged`);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (definitelyRejected(error)) {
|
|
91
|
+
if (error.status !== undefined && REFUSALS.has(error.status)) return refused(error.message);
|
|
92
|
+
await ctx.emit(MergeRefused, { pr, operation, reason: error.message, terminal: false, failed: true });
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What the module needs to check a merge that was cut off. */
|
|
99
|
+
export interface CheckPlace {
|
|
100
|
+
readonly journal: () => JournalReader | undefined;
|
|
101
|
+
readonly gitlab: (host: string) => GitLab;
|
|
102
|
+
/** Write a record of the module's own, for what a check finds and nothing recorded. */
|
|
103
|
+
readonly write: MergeWriter;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Claims still waiting for a confirmed result, including after a host restart. */
|
|
107
|
+
export function unresolvedClaims(journal: JournalReader | undefined) {
|
|
108
|
+
const claims = new Map<string, { pr: PrRef; operation: string; cancel: boolean }>();
|
|
109
|
+
const types = [MergeStarted, CancelStarted, MergeArmed, MergeRefused, CancelRefused, MergeDisarmed, MergeSettled];
|
|
110
|
+
for (const row of journal?.since(seq(0), types.map(type => type.name)) ?? []) {
|
|
111
|
+
const { pr, operation } = row.data as { pr: PrRef; operation: string };
|
|
112
|
+
if (row.type === MergeStarted.name || row.type === CancelStarted.name) {
|
|
113
|
+
claims.set(operation, { pr, operation, cancel: row.type === CancelStarted.name });
|
|
114
|
+
} else claims.delete(operation);
|
|
115
|
+
}
|
|
116
|
+
return [...claims.values()];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** What happened to a merge that was cut off. */
|
|
120
|
+
export async function checkMerge(place: CheckPlace, operationId: string): Promise<CheckResult<MergeOutcome>> {
|
|
121
|
+
const journal = place.journal();
|
|
122
|
+
if (journal === undefined) return { status: "unknown" };
|
|
123
|
+
const requested = journal
|
|
124
|
+
.since(seq(0), [MergeStarted.name])
|
|
125
|
+
.map((stored) => MergeStarted.schema.safeParse(stored.data))
|
|
126
|
+
.find((parsed) => parsed.success && parsed.data.operation === operationId);
|
|
127
|
+
if (requested === undefined || !requested.success) return { status: "failed", error: "the merge was never asked of the server" };
|
|
128
|
+
const { pr, expectHead, when } = requested.data;
|
|
129
|
+
const gitlab = place.gitlab(pr.repo.host);
|
|
130
|
+
const externalId = externalIdOf(pr);
|
|
131
|
+
const result = journal.since(seq(0), [MergeArmed.name, MergeRefused.name, MergeSettled.name])
|
|
132
|
+
.find(row => (row.data as { operation: string }).operation === operationId);
|
|
133
|
+
if (result?.type === MergeArmed.name) {
|
|
134
|
+
const { mode } = MergeArmed.schema.parse(result.data);
|
|
135
|
+
return { status: "completed", value: { outcome: mode === "train" ? "queued" : "armed", externalId, cancel: forgePrMergeCancel.name } };
|
|
136
|
+
}
|
|
137
|
+
if (result?.type === MergeRefused.name) {
|
|
138
|
+
const { reason, failed } = MergeRefused.schema.parse(result.data);
|
|
139
|
+
return failed ? { status: "failed", error: reason } : { status: "completed", value: { outcome: "refused", why: reason } };
|
|
140
|
+
}
|
|
141
|
+
if (result?.type === MergeSettled.name) {
|
|
142
|
+
const settled = MergeSettled.schema.parse(result.data);
|
|
143
|
+
return { status: "completed", value: { outcome: "merged", sha: settled.mergeSha ?? expectHead, externalId } };
|
|
144
|
+
}
|
|
145
|
+
const mr = await gitlab.get<GitLabMr>(projectPath(pr.repo, `/merge_requests/${pr.number}`));
|
|
146
|
+
const resultId = `forge:merge-outcome:${operationId}`;
|
|
147
|
+
if (mr.state === "merged" && mr.sha === expectHead) {
|
|
148
|
+
const sha = mergedSha(mr, expectHead);
|
|
149
|
+
await place.write(MergeSettled, { operation: operationId, pr, externalId, outcome: "merged", mergeSha: sha }, resultId);
|
|
150
|
+
return { status: "completed", value: { outcome: "merged", sha, externalId } };
|
|
151
|
+
}
|
|
152
|
+
if (mr.state !== "opened" || mr.sha !== expectHead) {
|
|
153
|
+
const reason = `the pull request is ${mr.state} at ${mr.sha}, expected ${expectHead}`;
|
|
154
|
+
await place.write(MergeRefused, { operation: operationId, pr, reason, terminal: mr.state === "merged", failed: true }, resultId);
|
|
155
|
+
return { status: "failed", error: reason };
|
|
156
|
+
}
|
|
157
|
+
const armed = async (mode: "auto-merge" | "train"): Promise<CheckResult<MergeOutcome>> => {
|
|
158
|
+
await place.write(MergeArmed, { operation: operationId, pr, mode, externalId, expectHead }, resultId);
|
|
159
|
+
return { status: "completed", value: { outcome: mode === "train" ? "queued" : "armed", externalId, cancel: forgePrMergeCancel.name } };
|
|
160
|
+
};
|
|
161
|
+
if (when === "pipeline" && mr.merge_when_pipeline_succeeds === true) return await armed("auto-merge");
|
|
162
|
+
if (when === "train" && await inTrain(gitlab, pr)) return armed("train");
|
|
163
|
+
return { status: "unknown" };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The merges the server took for later and has not made or dropped yet: armed, and neither called
|
|
168
|
+
* off nor followed by a merge or a close of the pull request.
|
|
169
|
+
*/
|
|
170
|
+
function armedMerges(journal: JournalReader | undefined): Array<PendingMerge & { operation: string }> {
|
|
171
|
+
if (journal === undefined) return [];
|
|
172
|
+
const pending = new Map<string, PendingMerge & { operation: string }>();
|
|
173
|
+
for (const stored of journal.since(seq(0), [MergeArmed.name, MergeDisarmed.name, MergeSettled.name])) {
|
|
174
|
+
if (stored.type === MergeArmed.name) {
|
|
175
|
+
const parsed = MergeArmed.schema.safeParse(stored.data);
|
|
176
|
+
if (!parsed.success) continue;
|
|
177
|
+
const { pr, mode, externalId, expectHead } = parsed.data;
|
|
178
|
+
const input = { repo: { host: pr.repo.host, path: pr.repo.path }, number: pr.number };
|
|
179
|
+
pending.set(mergeKey(pr), { pr, operation: parsed.data.operation, mode, externalId, expectHead, cancel: { action: forgePrMergeCancel.name, input } });
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
const ended = stored.type === MergeDisarmed.name ? MergeDisarmed : MergeSettled;
|
|
183
|
+
const parsed = ended.schema.safeParse(stored.data);
|
|
184
|
+
if (parsed.success) pending.delete(mergeKey(parsed.data.pr));
|
|
185
|
+
}
|
|
186
|
+
return [...pending.values()];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function pendingMerges(journal: JournalReader | undefined): PendingMerge[] {
|
|
190
|
+
return armedMerges(journal).map(({ operation: _operation, ...pending }) => pending);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Whether a pull request has a place in the merge train. */
|
|
194
|
+
export async function inTrain(gitlab: GitLab, pr: PrRef): Promise<boolean> {
|
|
195
|
+
try {
|
|
196
|
+
await gitlab.get(projectPath(pr.repo, `/merge_trains/merge_requests/${String(pr.number)}`));
|
|
197
|
+
return true;
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (error instanceof ForgeError && error.code === "not-found") return false;
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Whether an answer to a cancel says the server did not do it: a refusal in the body of a success. */
|
|
205
|
+
function refusedInBody(answer: unknown): boolean {
|
|
206
|
+
return typeof answer === "object" && answer !== null && (answer as { status?: unknown }).status === "error";
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Call off a merge the server took for later: the automatic merge, or the place in the train. The
|
|
211
|
+
* answer of the cancel is not taken for the outcome, for a server may answer a success status over a
|
|
212
|
+
* refusal: the pull request is read back, and the merge is dropped from the pending ones only when it
|
|
213
|
+
* is open and neither armed nor in the train, or no longer a merge to wait for. Merged, it is not
|
|
214
|
+
* called off: the server made it.
|
|
215
|
+
*/
|
|
216
|
+
export async function cancelMerge(gitlab: GitLab, pr: PrRef, journal: JournalReader | undefined, ctx: Pick<ActionContext, "emit" | "operationId">): Promise<boolean> {
|
|
217
|
+
const known = armedMerges(journal).find(one => mergeKey(one.pr) === mergeKey(pr));
|
|
218
|
+
if (known === undefined) return false;
|
|
219
|
+
const claim = { operation: ctx.operationId, pr, basedOn: known.operation, mode: known.mode };
|
|
220
|
+
await ctx.emit(CancelStarted, claim);
|
|
221
|
+
const path = known.mode === "train"
|
|
222
|
+
? projectPath(pr.repo, `/merge_trains/merge_requests/${pr.number}`)
|
|
223
|
+
: projectPath(pr.repo, `/merge_requests/${pr.number}/cancel_merge_when_pipeline_succeeds`);
|
|
224
|
+
let accepted: boolean;
|
|
225
|
+
try {
|
|
226
|
+
accepted = !refusedInBody(await gitlab.send(known.mode === "train" ? "DELETE" : "POST", path));
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (!definitelyRejected(error)) throw error;
|
|
229
|
+
if (error.code !== "not-found" && error.status !== 406 && error.status !== 405) {
|
|
230
|
+
await ctx.emit(CancelRefused, { pr, operation: claim.operation, basedOn: known.operation, error: error.message });
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
accepted = false;
|
|
234
|
+
}
|
|
235
|
+
const result = await observeCancel(gitlab, claim, (type, data) => ctx.emit(type, data).then(() => {}), accepted);
|
|
236
|
+
return result.status === "completed" && result.value.cancelled;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
type CancelClaim = ReturnType<typeof CancelStarted.schema.parse>;
|
|
240
|
+
|
|
241
|
+
async function observeCancel(gitlab: GitLab, claim: CancelClaim, write: MergeWriter, accepted?: boolean): Promise<CheckResult<{cancelled: boolean}>> {
|
|
242
|
+
const { pr, operation, mode, basedOn } = claim;
|
|
243
|
+
const externalId = externalIdOf(pr);
|
|
244
|
+
const id = `forge:cancel-outcome:${operation}`;
|
|
245
|
+
const mr = await gitlab.get<GitLabMr>(projectPath(pr.repo, `/merge_requests/${pr.number}`));
|
|
246
|
+
if (mr.state === "merged" || mr.state === "closed") {
|
|
247
|
+
const mergeSha = finalShaOf(mr);
|
|
248
|
+
await write(MergeSettled, { pr, operation, externalId, outcome: mr.state, ...(mergeSha ? { mergeSha } : {}) }, id);
|
|
249
|
+
return { status: "completed", value: { cancelled: false } };
|
|
250
|
+
}
|
|
251
|
+
if (mr.state !== "opened") return { status: "unknown" };
|
|
252
|
+
const armed = mr.merge_when_pipeline_succeeds === true || (mode === "train" && await inTrain(gitlab, pr));
|
|
253
|
+
if (!armed) {
|
|
254
|
+
const cancelled = accepted !== false;
|
|
255
|
+
await write(MergeDisarmed, { pr, operation, externalId, cancelled }, id);
|
|
256
|
+
return { status: "completed", value: { cancelled } };
|
|
257
|
+
}
|
|
258
|
+
if (accepted === undefined) return { status: "unknown" };
|
|
259
|
+
await write(CancelRefused, { pr, operation, basedOn }, id);
|
|
260
|
+
return { status: "completed", value: { cancelled: false } };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function checkCancel(place: CheckPlace, operation: string): Promise<CheckResult<{cancelled: boolean}>> {
|
|
264
|
+
const journal = place.journal();
|
|
265
|
+
if (journal === undefined) return { status: "unknown" };
|
|
266
|
+
const claim = journal.find({ type: CancelStarted.name, field: "operation", equals: operation })[0];
|
|
267
|
+
if (!claim) return { status: "completed", value: { cancelled: false } };
|
|
268
|
+
const saved = journal.since(claim.seq, [MergeDisarmed.name, CancelRefused.name, MergeSettled.name])
|
|
269
|
+
.find(row => (row.data as { operation: string }).operation === operation);
|
|
270
|
+
if (saved?.type === CancelRefused.name) {
|
|
271
|
+
const { error } = CancelRefused.schema.parse(saved.data);
|
|
272
|
+
if (error) return { status: "failed", error };
|
|
273
|
+
}
|
|
274
|
+
if (saved) return { status: "completed", value: { cancelled: saved.type === MergeDisarmed.name && MergeDisarmed.schema.parse(saved.data).cancelled } };
|
|
275
|
+
const data = CancelStarted.schema.parse(claim.data);
|
|
276
|
+
return observeCancel(place.gitlab(data.pr.repo.host), data, place.write);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** How a record is written for the merges: a record of the module's own type under an id of its own. */
|
|
280
|
+
export type MergeWriter = <T>(type: RecordType<T>, data: T, id: string) => Promise<void>;
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Settle the merges listed as pending on one repository against the server, one read of each pull
|
|
284
|
+
* request: merged or closed there, it is settled; open and no longer armed or in the train, it is
|
|
285
|
+
* disarmed; open and armed, it stays pending. A pull request the server no longer has is left.
|
|
286
|
+
* Pending merges are watched for this whether or not their repository is.
|
|
287
|
+
*/
|
|
288
|
+
export async function settleMerges(place: { gitlab: GitLab; journal: JournalReader; write: MergeWriter }, repo: Repo): Promise<void> {
|
|
289
|
+
const { gitlab, journal } = place;
|
|
290
|
+
for (const one of armedMerges(journal)) {
|
|
291
|
+
if (one.pr.repo.host !== repo.host || one.pr.repo.projectId !== repo.projectId) continue;
|
|
292
|
+
let mr: GitLabMr;
|
|
293
|
+
try {
|
|
294
|
+
mr = await gitlab.get<GitLabMr>(projectPath(repo, `/merge_requests/${String(one.pr.number)}`));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (error instanceof ForgeError && error.code === "not-found") continue;
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
const id = (what: string) => `forge:merge:${one.operation}:${what}`;
|
|
300
|
+
if (mr.state === "merged" || mr.state === "closed") {
|
|
301
|
+
const mergeSha = mr.state === "merged" ? finalShaOf(mr) : undefined;
|
|
302
|
+
await place.write(MergeSettled, { pr: one.pr, operation: one.operation, externalId: one.externalId, outcome: mr.state, ...(mergeSha === undefined ? {} : { mergeSha }) }, id("settled"));
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (mr.state !== "opened") continue;
|
|
306
|
+
const dropped = one.mode === "auto-merge" ? mr.merge_when_pipeline_succeeds !== true : !(await inTrain(gitlab, one.pr));
|
|
307
|
+
if (dropped) await place.write(MergeDisarmed, { pr: one.pr, operation: one.operation, cancelled: false, externalId: one.externalId }, id("disarmed"));
|
|
308
|
+
}
|
|
309
|
+
}
|
package/src/normalize.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What GitLab answers, in the module's words: a merge request is a pull request, a pipeline has a
|
|
3
|
+
* kind, a merge result has the pair of commits it was made of.
|
|
4
|
+
*
|
|
5
|
+
* GitLab names a pipeline of a merge request by its ref: `refs/merge-requests/<n>/head` ran on the
|
|
6
|
+
* head, `…/merge` on the merge of the head into the target, `…/train` in a merge train. The commit a
|
|
7
|
+
* merge result ran on is a merge whose first parent is the target and second the head, so the pair
|
|
8
|
+
* is read from the commit itself and not from the merge request, whose head may have moved since.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { PullRequest } from "./actions.ts";
|
|
12
|
+
import { ForgeError } from "./gitlab.ts";
|
|
13
|
+
import type { GitLab } from "./gitlab.ts";
|
|
14
|
+
import type { ChecksState, Pipeline, PipelineKind, PrRef, Repo, RunState } from "./record-types.ts";
|
|
15
|
+
import { RunState as RunStates } from "./record-types.ts";
|
|
16
|
+
import { projectPath } from "./servers.ts";
|
|
17
|
+
|
|
18
|
+
/** A merge request, as much of it as the module reads. */
|
|
19
|
+
export interface GitLabMr {
|
|
20
|
+
iid: number;
|
|
21
|
+
title: string;
|
|
22
|
+
description?: string | null;
|
|
23
|
+
state: string;
|
|
24
|
+
source_branch: string;
|
|
25
|
+
target_branch: string;
|
|
26
|
+
sha: string;
|
|
27
|
+
draft?: boolean;
|
|
28
|
+
work_in_progress?: boolean;
|
|
29
|
+
author?: { username?: string } | null;
|
|
30
|
+
merge_commit_sha?: string | null;
|
|
31
|
+
squash_commit_sha?: string | null;
|
|
32
|
+
merge_when_pipeline_succeeds?: boolean;
|
|
33
|
+
updated_at?: string;
|
|
34
|
+
web_url?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A pipeline, as much of it as the module reads. */
|
|
38
|
+
export interface GitLabPipeline {
|
|
39
|
+
id: number;
|
|
40
|
+
sha: string;
|
|
41
|
+
ref: string;
|
|
42
|
+
status: string;
|
|
43
|
+
source?: string;
|
|
44
|
+
tag?: boolean;
|
|
45
|
+
updated_at?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A job, as much of it as the module reads. */
|
|
49
|
+
export interface GitLabJob {
|
|
50
|
+
id: number;
|
|
51
|
+
name: string;
|
|
52
|
+
stage: string;
|
|
53
|
+
status: string;
|
|
54
|
+
ref: string;
|
|
55
|
+
pipeline: { id: number };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The commit a merged request left on its base. A squash in a project that merges by merge commit
|
|
60
|
+
* makes two commits, the squash and the merge on top of it: the merge is what lands. Where the
|
|
61
|
+
* project merges by fast-forward there is no merge commit and the squash is the one that lands.
|
|
62
|
+
*/
|
|
63
|
+
export function finalShaOf(mr: GitLabMr): string | undefined {
|
|
64
|
+
return mr.merge_commit_sha ?? mr.squash_commit_sha ?? undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The pull request of a merge request. */
|
|
68
|
+
export function pullRequestOf(repo: Repo, mr: GitLabMr): PullRequest {
|
|
69
|
+
const state = mr.state === "opened" ? "open" : mr.state === "merged" ? "merged" : mr.state === "locked" ? "locked" : "closed";
|
|
70
|
+
const merged = finalShaOf(mr);
|
|
71
|
+
return {
|
|
72
|
+
pr: { repo, number: mr.iid },
|
|
73
|
+
state,
|
|
74
|
+
title: mr.title,
|
|
75
|
+
branch: mr.source_branch,
|
|
76
|
+
base: mr.target_branch,
|
|
77
|
+
head: mr.sha,
|
|
78
|
+
draft: mr.draft ?? mr.work_in_progress ?? false,
|
|
79
|
+
...(mr.author?.username === undefined ? {} : { author: mr.author.username }),
|
|
80
|
+
...(state === "merged" && merged !== undefined ? { mergeSha: merged } : {}),
|
|
81
|
+
autoMerge: mr.merge_when_pipeline_succeeds ?? false,
|
|
82
|
+
...(mr.web_url === undefined ? {} : { webUrl: mr.web_url }),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A state GitLab gave, in the module's enum; an unknown one reads as `created`. */
|
|
87
|
+
export function runStateOf(status: string): RunState {
|
|
88
|
+
const parsed = RunStates.safeParse(status);
|
|
89
|
+
return parsed.success ? parsed.data : "created";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const MR_REF = /^refs\/merge-requests\/(\d+)\/(head|merge|train)$/;
|
|
93
|
+
|
|
94
|
+
/** What a pipeline ran on, and the pull request it ran for, from its ref and source. */
|
|
95
|
+
export function kindOf(pipeline: GitLabPipeline): { kind: PipelineKind; pr?: number } {
|
|
96
|
+
const mr = MR_REF.exec(pipeline.ref);
|
|
97
|
+
if (mr !== null) {
|
|
98
|
+
const kind = mr[2] === "head" ? "head" : mr[2] === "merge" ? "merge-result" : "train";
|
|
99
|
+
return { kind, pr: Number(mr[1]) };
|
|
100
|
+
}
|
|
101
|
+
if (pipeline.tag === true) return { kind: "tag" };
|
|
102
|
+
if (pipeline.source === "schedule") return { kind: "schedule" };
|
|
103
|
+
return { kind: "branch" };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** What a pipeline needs of the server to be told in the module's words. */
|
|
107
|
+
export interface Lookups {
|
|
108
|
+
/** The parents of a commit: what a merge result was made of. */
|
|
109
|
+
readonly parentsOf: (sha: string) => Promise<readonly string[] | undefined>;
|
|
110
|
+
/** Whether the ref of a pipeline is a tag, for a pipeline whose list entry does not say. */
|
|
111
|
+
readonly isTag: (pipeline: GitLabPipeline) => Promise<boolean>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** What is known of a pipeline's ref, by client: whether a pipeline ran for a tag never changes. */
|
|
115
|
+
const TAGS = new WeakMap<GitLab, Map<string, boolean>>();
|
|
116
|
+
|
|
117
|
+
/** The lookups of one project on one server. */
|
|
118
|
+
export function lookupsOf(gitlab: GitLab, repo: Repo): Lookups {
|
|
119
|
+
const tags = TAGS.get(gitlab) ?? new Map<string, boolean>();
|
|
120
|
+
TAGS.set(gitlab, tags);
|
|
121
|
+
return {
|
|
122
|
+
async parentsOf(sha) {
|
|
123
|
+
try {
|
|
124
|
+
return (await gitlab.get<{ parent_ids: string[] }>(projectPath(repo, `/repository/commits/${sha}`))).parent_ids;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error instanceof ForgeError && error.code === "not-found") return undefined;
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
async isTag(pipeline) {
|
|
131
|
+
const key = `${String(repo.projectId)}:${String(pipeline.id)}`;
|
|
132
|
+
const known = tags.get(key);
|
|
133
|
+
if (known !== undefined) return known;
|
|
134
|
+
// The entry of a list leaves `tag` out; the pipeline read by its id has it.
|
|
135
|
+
const full = await gitlab.get<GitLabPipeline>(projectPath(repo, `/pipelines/${String(pipeline.id)}`));
|
|
136
|
+
const tag = full.tag === true;
|
|
137
|
+
tags.set(key, tag);
|
|
138
|
+
return tag;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A pipeline in the module's words. A merge result or a train whose commit the server cannot show
|
|
145
|
+
* as a merge of two parents is not bound to a pair, so it is not answered.
|
|
146
|
+
*/
|
|
147
|
+
export async function pipelineOf(repo: Repo, pipeline: GitLabPipeline, lookups: Lookups): Promise<Pipeline | undefined> {
|
|
148
|
+
const found = kindOf(pipeline);
|
|
149
|
+
const { pr } = found;
|
|
150
|
+
// A pipeline of a ref the list does not say is a tag or not is asked for: a tag is not a branch.
|
|
151
|
+
const kind = found.kind === "branch" && pipeline.tag === undefined && (await lookups.isTag(pipeline)) ? "tag" : found.kind;
|
|
152
|
+
const base = { repo, pipeline: pipeline.id, kind, ref: pipeline.ref, state: runStateOf(pipeline.status), ...(pr === undefined ? {} : { pr }) };
|
|
153
|
+
if (kind !== "merge-result" && kind !== "train") return { ...base, sourceSha: pipeline.sha };
|
|
154
|
+
const parents = await lookups.parentsOf(pipeline.sha);
|
|
155
|
+
const [targetSha, sourceSha] = parents ?? [];
|
|
156
|
+
if (parents?.length !== 2 || targetSha === undefined || sourceSha === undefined) return undefined;
|
|
157
|
+
return { ...base, sourceSha, targetSha, mergeSha: pipeline.sha };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* What one pipeline's state says of the change: green on success, red on a failure or a cancel,
|
|
162
|
+
* none when it was skipped, and pending otherwise, a pipeline that waits on a manual job included.
|
|
163
|
+
*/
|
|
164
|
+
export function verdictOf(state: RunState): ChecksState {
|
|
165
|
+
if (state === "success") return "green";
|
|
166
|
+
if (state === "failed" || state === "canceled") return "red";
|
|
167
|
+
return state === "skipped" ? "none" : "pending";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** What the pipelines of one head say: the latest decides; none is `none`. */
|
|
171
|
+
export function checksOf(pipelines: readonly Pipeline[]): { state: ChecksState; pipeline?: number } {
|
|
172
|
+
const latest = [...pipelines].sort((a, b) => b.pipeline - a.pipeline)[0];
|
|
173
|
+
if (latest === undefined) return { state: "none" };
|
|
174
|
+
return { state: verdictOf(latest.state), pipeline: latest.pipeline };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The ref a pull request's pipelines run on. */
|
|
178
|
+
export function prOfRef(ref: string): number | undefined {
|
|
179
|
+
const mr = MR_REF.exec(ref);
|
|
180
|
+
return mr === null ? undefined : Number(mr[1]);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A pull request reference. */
|
|
184
|
+
export function prRef(repo: Repo, number: number): PrRef {
|
|
185
|
+
return { repo, number };
|
|
186
|
+
}
|