Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
6import {
7 IsoDateTime,
8 NonNegativeInt,
9 resolvePullRequestAuthorFilter,
10 TrimmedNonEmptyString,
11 type PullRequestCapabilities,
12 type PullRequestListFilters,
13 type PullRequestStackHead,
14} from "@t3tools/contracts";
15import {
16 gitHubActionsJobId,
17 PullRequestProviderError,
18 tailLogLines,
19 type ProviderCheckLog,
20 type ProviderCheckRerun,
21 type ProviderRepositoryRef,
22 type PullRequestProviderApi,
23} from "@t3tools/source-control-core/server/PullRequestProvider";
24
25import * as GitCafeApi from "./GitCafeApi.ts";
26import * as GitCafeHosts from "./gitCafeHosts.ts";
27import * as Json from "./gitCafePullRequestJson.ts";
28import { definition } from "../shared/definition.ts";
29
30const CAPABILITIES: PullRequestCapabilities = {
31 diff: true,
32 comment: true,
33 actions: [...definition.changeRequestActions],
34 mergeMethods: ["merge", "squash", "rebase"],
35 // Branch updates restack every layer above the target.
36 updateMethods: ["rebase"],
37 search: true,
38 stacks: true,
39 stackActions: true,
40 reactions: true,
41 mentions: true,
42 referenceSigils: [],
43 labels: true,
44 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
45 review: {
46 inlineComment: false,
47 reply: true,
48 resolve: true,
49 verdicts: ["approve", "request-changes", "comment"],
50 },
51 reviewers: { request: true, listCandidates: true, searchCandidates: false },
52 edit: { changeRequest: true, comment: true },
53};
54
55const PAGE_SIZE = 100;
56const MAX_PAGES = 10;
57/**
58 * Pages read looking for a GitHub-synced author before a listing filtered by them gives up. The
59 * login only appears on their pull requests, so one older than this many is out of reach.
60 */
61const AUTHOR_DISCOVERY_PAGES = 5;
62/** Bounds the logins remembered from listings; a repository's authors fit many times over. */
63const KNOWN_AUTHORS_LIMIT = 10_000;
64/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
65const DIFF_FILES_BATCH = 64;
66/** Changed-path pages carry no hunks, so they can be read in larger pages. */
67const CHANGES_PAGE_LIMIT = 500;
68/** Line totals require hunk reads; omit them for large PRs. */
69const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
70const MAX_CHANGE_PAGES = 20;
71const LINE_STATS_CACHE_SIZE = 256;
72
73const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
74 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
75 items.slice(index * size, (index + 1) * size),
76 );
77
78const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
79 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
80
81const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
82 status.merge.permitted !== false &&
83 status.merge.strategies.includes(strategy) &&
84 !(status.merge.blockers ?? []).some((blocker) =>
85 (blocker.blockedStrategies ?? []).includes(strategy),
86 );
87
88const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
89const isId = Schema.is(Id);
90const isApiError = Schema.is(GitCafeApi.GitCafeApiError);
91const Principal = Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString });
92const User = Schema.Struct({ actorId: TrimmedNonEmptyString });
93const Written = Schema.Struct({ id: Id });
94const Versioned = Schema.Struct({ version: NonNegativeInt });
95const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
96const Status = Schema.Struct({
97 merge: Schema.Struct({
98 // The API reference lists "unknown" and "conflicting", but git.cafe also sends "none" and
99 // "pending", so any state is read and only the known ones are mapped.
100 conflicts: Schema.String,
101 fastForward: Schema.NullOr(Schema.Boolean),
102 strategies: Schema.Array(Schema.String),
103 permitted: Schema.optional(Schema.Boolean),
104 reasons: Schema.optional(Schema.Array(Schema.String)),
105 blockers: Schema.optional(
106 Schema.Array(
107 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
108 ),
109 ),
110 }),
111 checks: Schema.Struct({
112 pending: NonNegativeInt,
113 failing: NonNegativeInt,
114 total: NonNegativeInt,
115 }),
116});
117/** A merge GitCafe accepted runs on afterwards: on GitHub for a synced pull request, or natively. */
118const MERGE_IN_FLIGHT = new Set(["provider-merge-pending", "native-operation-pending"]);
119const Listed = Schema.Struct({
120 items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString })),
121 next: Schema.NullOr(Schema.String),
122});
123const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
124const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
125const CommitOid = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u));
126const isCommitOid = Schema.is(CommitOid);
127const SourceSnapshot = Schema.Struct({
128 version: NonNegativeInt,
129 headOid: CommitOid,
130 comparisonBaseOid: CommitOid,
131});
132const SourceBlob = Schema.Struct({
133 commit: CommitOid,
134 path: Schema.String,
135 size: NonNegativeInt,
136 binary: Schema.Boolean,
137 content: Schema.NullOr(Schema.String),
138});
139const MAX_DIFF_FILE_BYTES = 1024 * 1024;
140
141class GitCafeDiffSourceUnavailableError extends Schema.TaggedError<GitCafeDiffSourceUnavailableError>()(
142 "GitCafeDiffSourceUnavailableError",
143 {
144 path: Schema.String,
145 reason: Schema.Literals(["oversized", "binary", "unavailable"]),
146 cause: Schema.optional(Schema.Defect()),
147 },
148) {}
149const Snapshot = {
150 version: NonNegativeInt,
151 headOid: TrimmedNonEmptyString,
152 comparisonBaseOid: TrimmedNonEmptyString,
153};
154const Changes = Schema.Struct({
155 ...Snapshot,
156 items: Json.GitCafeDiffFiles,
157 next: Schema.NullOr(TrimmedNonEmptyString),
158});
159const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
160const DiffCursor = Schema.Struct({
161 version: NonNegativeInt,
162 headOid: TrimmedNonEmptyString,
163 baseOid: TrimmedNonEmptyString,
164 after: TrimmedNonEmptyString,
165});
166const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
167const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
168const MergeOutcome = Schema.Struct({
169 id: Schema.String,
170 state: Schema.Literals(["accepted", "completed", "failed"]),
171 reason: Schema.optional(Schema.String),
172});
173const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
174const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
175
176// A pull action replies with the pull it left; `closedAt`/`mergedAt` are read only when sent.
177const decodeActionReply = Schema.decodeUnknownOption(
178 Schema.fromJsonString(
179 Schema.Struct({
180 ...Json.GitCafePull.fields,
181 closedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
182 mergedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
183 }),
184 ),
185);
186
187type PullRef = ProviderRepositoryRef & { readonly number: number };
188
189/** GitHub's merge counts as soon as GitCafe records it, ahead of the sync that reports it. */
190const settledMerge = (pull: Json.GitCafePullDetail) =>
191 pull.state === "open" && pull.providerMerge != null
192 ? { state: "merged" as const, mergedAt: pull.providerMerge.mergedAt }
193 : {};
194type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
195
196function stackHeadsCurrent(
197 stack: Json.GitCafeStack,
198 input: { readonly number: number; readonly merge: boolean },
199 expected: ReadonlyArray<PullRequestStackHead>,
200): boolean {
201 const members = stack.members.toSorted((a, b) => a.position - b.position);
202 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
203 if (index === -1) return false;
204 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
205 (member) => member.state !== "merged",
206 );
207 return (
208 moved.length === expected.length &&
209 moved.every(
210 (member) =>
211 member.headOid !== undefined &&
212 expected.some(
213 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
214 ),
215 )
216 );
217}
218
219const POSITION = /^(.+)~(\d+)$/u;
220const parsePosition = (raw: string | undefined) => {
221 const match = raw === undefined ? null : POSITION.exec(raw);
222 const created = match === null ? Number.NaN : Date.parse(match[1]!);
223 return match === null || Number.isNaN(created) ? null : { created, number: Number(match[2]) };
224};
225
226const withDetails = (
227 files: ReadonlyArray<Json.GitCafeDiffFile>,
228 details: ReadonlyArray<Json.GitCafeDiffFile>,
229) => {
230 const byPath = new Map(details.map((file) => [file.path, file]));
231 return files.map((file) => byPath.get(file.path) ?? file);
232};
233
234/** @public */
235const CHECK_LOG_TAIL_BYTES = 256 * 1024;
236const CheckLog = Schema.Struct({ content: Schema.String, truncated: Schema.Boolean });
237
238export const make = Effect.gen(function* () {
239 const api = yield* GitCafeApi.GitCafeApi;
240 // GitCafe filters by actor id and has no lookup from a GitHub login to the actor sync made for
241 // it, so the pairs are learned from the pull requests every listing reads.
242 const knownAuthors = new Map<string, string>();
243 const authorKey = (host: string, login: string) =>
244 `${host.toLowerCase()}\n${login.toLowerCase()}`;
245 const learnAuthors = (host: string, pulls: ReadonlyArray<Json.GitCafePull>) => {
246 for (const { author } of pulls) {
247 if (author.kind !== "github") continue;
248 if (knownAuthors.size >= KNOWN_AUTHORS_LIMIT) knownAuthors.clear();
249 knownAuthors.set(authorKey(host, author.login), author.actorId);
250 }
251 };
252
253 const failure = (operation: string, detail: string, cause?: unknown) =>
254 new PullRequestProviderError({
255 provider: SourceControlProviderKind.make("gitcafe"),
256 operation,
257 reason: "failed",
258 detail,
259 ...(cause === undefined ? {} : { cause }),
260 });
261
262 const repositoryPath = (
263 operation: string,
264 input: ProviderRepositoryRef,
265 ): Effect.Effect<string, PullRequestProviderError> =>
266 GitCafeHosts.isGitCafeHost(input.host) &&
267 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
268 ? Effect.succeed(`/repos/${input.repository}`)
269 : Effect.fail(
270 failure(
271 operation,
272 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
273 ),
274 );
275
276 const send = (
277 operation: string,
278 input: Pick<ProviderRepositoryRef, "host">,
279 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
280 ) =>
281 api.request({ ...request, host: input.host, operation }).pipe(
282 Effect.mapError(
283 (error) =>
284 new PullRequestProviderError({
285 provider: SourceControlProviderKind.make("gitcafe"),
286 operation,
287 reason: error.reason,
288 detail: error.detail,
289 cause: error,
290 }),
291 ),
292 );
293
294 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
295 operation: string,
296 input: Pick<ProviderRepositoryRef, "host">,
297 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
298 schema: S,
299 ) =>
300 send(operation, input, request).pipe(
301 Effect.flatMap((raw) =>
302 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
303 Effect.mapError((cause) =>
304 failure(operation, "GitCafe returned an unreadable response.", cause),
305 ),
306 ),
307 ),
308 );
309
310 const pullPath = (operation: string, input: PullRef) =>
311 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
312
313 const readPull = (operation: string, input: PullRef) =>
314 pullPath(operation, input).pipe(
315 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
316 );
317
318 const readDiffSource = Effect.fn("GitCafePullRequestProvider.readDiffSource")(function* (
319 input: ProviderRepositoryRef,
320 revision: string,
321 filePath: string,
322 ) {
323 const operation = "getDiffFileContents";
324 const base = yield* repositoryPath(operation, input);
325 const query = new URLSearchParams({ oid: revision, path: filePath });
326 const blob = yield* read(operation, input, { path: `${base}/blob?${query}` }, SourceBlob).pipe(
327 Effect.catchIf(
328 (error) =>
329 isApiError(error.cause) && (error.cause.status === 413 || error.cause.status === 501),
330 (error) =>
331 Effect.fail(
332 failure(
333 operation,
334 "GitCafe cannot provide this source file as bounded text.",
335 new GitCafeDiffSourceUnavailableError({
336 path: filePath,
337 reason:
338 isApiError(error.cause) && error.cause.status === 413
339 ? "oversized"
340 : "unavailable",
341 cause: error,
342 }),
343 ),
344 ),
345 ),
346 );
347 if (blob.commit !== revision || blob.path !== filePath)
348 return yield* failure(
349 operation,
350 "GitCafe answered with a different source revision or path.",
351 );
352 const reason =
353 blob.size > MAX_DIFF_FILE_BYTES ||
354 (blob.content !== null && Buffer.byteLength(blob.content, "utf8") > MAX_DIFF_FILE_BYTES)
355 ? "oversized"
356 : blob.binary || blob.content?.includes("\0")
357 ? "binary"
358 : blob.content === null
359 ? "unavailable"
360 : null;
361 if (reason !== null)
362 return yield* failure(
363 operation,
364 "GitCafe cannot provide this source file as bounded text.",
365 new GitCafeDiffSourceUnavailableError({ path: filePath, reason }),
366 );
367 return blob.content!;
368 });
369
370 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
371 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
372 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
373 const items: Array<S["Type"]["items"][number]> = [];
374 let next: string | null = null;
375 for (let page = 0; page < MAX_PAGES; page++) {
376 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
377 if (next !== null) query.set("after", next);
378 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
379 items.push(...batch.items);
380 const previous: string | null = next;
381 next = batch.next;
382 if (next === null || next === previous || batch.items.length === 0) break;
383 }
384 return { items, next };
385 });
386
387 /**
388 * GitCafe filters by ids, so label names and the author's handle are looked up first. A label it
389 * cannot resolve is left out, and the service narrows the rows by name instead. An author it
390 * cannot resolve comes back as `unresolvedAuthor` for the listing to find.
391 */
392 const listFilterParams = Effect.fn("GitCafePullRequestProvider.listFilterParams")(function* (
393 input: ProviderRepositoryRef & {
394 readonly filters?: PullRequestListFilters | undefined;
395 readonly authorNarrowed: boolean;
396 readonly viewer: string;
397 },
398 base: string,
399 ) {
400 const filters = input.filters;
401 const params: Array<readonly [string, string]> = [];
402 if (filters === undefined) return { params, unresolvedAuthor: null };
403 if (filters.draft !== undefined)
404 params.push([filters.draft === "only" ? "states" : "stateNots", encodeIds(["draft"])]);
405 const groups = filters.labels ?? [];
406 const excluded = filters.excludedLabels ?? [];
407 if (groups.length > 0 || excluded.length > 0) {
408 const labels = yield* readPages(
409 "listChangeRequests",
410 input,
411 `${base}/labels`,
412 Json.GitCafeLabels,
413 );
414 const ids = new Map(labels.items.map((label) => [label.name.toLowerCase(), label.id]));
415 const idsOf = (names: ReadonlyArray<string>) =>
416 names.flatMap((name) => {
417 const id = ids.get(name.trim().toLowerCase());
418 return id === undefined ? [] : [id];
419 });
420 // Several ids in `labels` match a pull request holding any one of them, which is exactly
421 // one group; the remaining groups are the service's to narrow.
422 const group = groups.find((names) => idsOf(names).length === names.length);
423 if (group !== undefined) params.push(["labels", encodeIds(idsOf(group))]);
424 const excludedIds = idsOf(excluded);
425 if (excludedIds.length > 0) params.push(["labelNots", encodeIds(excludedIds)]);
426 }
427 if (filters.author !== undefined && !input.authorNarrowed) {
428 const handle = resolvePullRequestAuthorFilter(filters.author, input.viewer);
429 // A profile matches what GitHub sync authored for it too. A GitHub-synced author with no
430 // profile is known only by the actor on their pull requests.
431 const user = yield* read(
432 "listChangeRequests",
433 input,
434 { path: `/users/${encodeURIComponent(handle)}` },
435 User,
436 ).pipe(
437 Effect.asSome,
438 Effect.catchTags({
439 PullRequestProviderError: (error) =>
440 error.reason === "unauthenticated" || error.reason === "rate-limited"
441 ? Effect.fail(error)
442 : Effect.succeedNone,
443 }),
444 );
445 const actorId = Option.isSome(user)
446 ? user.value.actorId
447 : knownAuthors.get(authorKey(input.host, handle));
448 if (actorId === undefined) return { params, unresolvedAuthor: handle };
449 params.push(["authors", encodeIds([actorId])]);
450 }
451 return { params, unresolvedAuthor: null };
452 });
453
454 const readComments = (operation: string, input: PullRef) =>
455 pullPath(operation, input).pipe(
456 Effect.flatMap((path) =>
457 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
458 ),
459 );
460
461 const isCheckFailure = (error: PullRequestProviderError) =>
462 error.reason === "not-found" || error.reason === "forbidden" || error.reason === "failed";
463
464 const isForbidden = (error: PullRequestProviderError) =>
465 isApiError(error.cause) && error.cause.status === 403;
466
467 /**
468 * GitCafe offers no way to read a token's scopes, so reviewer controls show
469 * for anyone who may edit the pull request; a token without the reviewer
470 * scopes learns which ones it lacks when it uses them.
471 */
472 const explainReviewerScopes =
473 (operation: string) =>
474 <A, R>(effect: Effect.Effect<A, PullRequestProviderError, R>) =>
475 effect.pipe(
476 Effect.catchIf(isForbidden, (error) =>
477 Effect.fail(
478 failure(
479 operation,
480 "This GitCafe token cannot request reviewers. It needs the pr:review:read and pr:reviewers:write scopes.",
481 error,
482 ),
483 ),
484 ),
485 );
486
487 /**
488 * GitCafe replaces a pull request's whole reviewer or label list, so one toggle reads the
489 * list, changes it, and writes it back fenced on the pull request's version. The version is
490 * read first: a change landing between the two reads then fails the fence instead of being
491 * overwritten.
492 */
493 const toggleListed = Effect.fn("GitCafePullRequestProvider.toggleListed")(function* (
494 operation: string,
495 input: PullRef,
496 list: { readonly name: "reviewers" | "labels"; readonly key: "actorIds" | "labelIds" },
497 ids: ReadonlyArray<string>,
498 on: boolean,
499 ) {
500 const path = yield* pullPath(operation, input);
501 const pull = yield* readPull(operation, input);
502 const listed = yield* readPages(operation, input, `${path}/${list.name}`, Listed);
503 const current = listed.items.map((item) => item.id);
504 const next = on
505 ? [...new Set([...current, ...ids])]
506 : current.filter((id) => !ids.includes(id));
507 if (next.length === current.length) return;
508 yield* read(
509 operation,
510 input,
511 {
512 method: "PUT",
513 path: `${path}/${list.name}`,
514 body: { expectedVersion: pull.version, [list.key]: next },
515 },
516 Versioned,
517 );
518 });
519
520 /**
521 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
522 * open layer's pull is read.
523 */
524 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
525 operation: string,
526 input: PullRef,
527 ) {
528 const path = yield* pullPath(operation, input);
529 const { stack } = yield* read(
530 operation,
531 input,
532 { path: `${path}/stack` },
533 Json.GitCafeStackEnvelope,
534 );
535 if (stack === null) return null;
536 const members = yield* Effect.forEach(
537 stack.members,
538 (member) =>
539 member.state === "merged"
540 ? Effect.succeed(member)
541 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
542 Effect.map((pull) =>
543 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
544 ),
545 ),
546 { concurrency: 4 },
547 );
548 return { ...stack, members };
549 });
550
551 const readDiffPage = Effect.fn("GitCafePullRequestProvider.readDiffPage")(function* (
552 operation: string,
553 input: Parameters<PullRequestProviderApi["getDiff"]>[0],
554 limit: number,
555 ) {
556 if (input.commit !== undefined)
557 return yield* failure(operation, "GitCafe commit diffs are not supported yet.");
558 const cursor =
559 input.cursor === undefined
560 ? null
561 : yield* decodeDiffCursor(input.cursor).pipe(
562 Effect.mapError((cause) => failure(operation, "Invalid GitCafe diff cursor.", cause)),
563 );
564 // A pull without a head yet has nothing to pin; its version still is.
565 const expected = cursor ?? (yield* readPull(operation, input));
566 const version = expected.version;
567 const path = yield* pullPath(operation, input);
568 const query = new URLSearchParams({ expectedVersion: String(version), limit: String(limit) });
569 if (cursor !== null) query.set("after", cursor.after);
570 const page = yield* read(operation, input, { path: `${path}/changes?${query}` }, Changes);
571 if (
572 page.version !== version ||
573 (expected.headOid !== null && page.headOid !== expected.headOid) ||
574 (cursor !== null && cursor.baseOid !== page.comparisonBaseOid)
575 )
576 return yield* failure(
577 operation,
578 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
579 );
580 if (cursor !== null && page.next !== null && page.next === cursor.after)
581 return yield* failure(operation, "GitCafe returned a repeated diff page cursor.");
582 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
583 return {
584 items: page.items,
585 revision,
586 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
587 };
588 });
589
590 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
591 input: PullRef,
592 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
593 paths: ReadonlyArray<string>,
594 ) {
595 if (paths.length === 0) return [];
596 const path = yield* pullPath("getDiff", input);
597 const files = yield* read(
598 "getDiff",
599 input,
600 {
601 method: "POST",
602 path: `${path}/diff-files`,
603 body: { paths, expectedVersion: revision.version },
604 },
605 DiffFiles,
606 );
607 if (
608 files.version !== revision.version ||
609 files.headOid !== revision.headOid ||
610 files.comparisonBaseOid !== revision.baseOid
611 )
612 return yield* failure(
613 "getDiff",
614 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
615 );
616 return files.items;
617 });
618
619 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
620 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
621 ) {
622 const land = input.action === "merge";
623 const operation = land ? "landStackThrough" : "restackStack";
624 if (!land && input.action !== "update-branch")
625 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
626 const stack = yield* readStack(operation, input);
627 if (
628 stack === null ||
629 stack.number !== input.stackNumber ||
630 input.expectedStackHeads === undefined ||
631 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
632 )
633 return yield* failure(
634 operation,
635 "The stack changed since it was read. Refresh it and try again.",
636 );
637 const base = yield* repositoryPath(operation, input);
638 const outcome = yield* read(
639 operation,
640 input,
641 {
642 method: "POST",
643 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
644 body: land
645 ? {
646 expectedRevision: stack.revision,
647 requestId: yield* randomUuidV4,
648 throughPullRequestNumber: input.number,
649 strategy: input.mergeMethod ?? "merge",
650 }
651 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
652 },
653 StackOutcome,
654 );
655 if (FAILED_STACK_STATES.has(outcome.state))
656 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
657 });
658
659 // GitCafe's pulls carry no line totals, and linked pull requests are summarized every minute,
660 // so hunk totals are held per compared pair of commits. The file list that names the pair is
661 // cheap; a retarget or a landed parent layer moves the base without moving the head.
662 const lineTotals = new Map<string, { readonly additions: number; readonly deletions: number }>();
663 // The compared pair follows from the head and the target tip the pull reports, so while neither
664 // moves the stats are reused without listing the files again.
665 const statsByTips = new Map<
666 string,
667 { readonly changedFiles: number; readonly additions?: number; readonly deletions?: number }
668 >();
669 const remember = <K, V>(cache: Map<K, V>, key: K, value: V) => {
670 if (cache.size >= LINE_STATS_CACHE_SIZE) cache.delete(cache.keys().next().value!);
671 cache.set(key, value);
672 };
673
674 // readLineStats owns the span.
675 const countLines = Effect.fnUntraced(function* (input: PullRef, version: number) {
676 const path = yield* pullPath("getChangeRequest", input);
677 const files: Array<Json.GitCafeDiffFile> = [];
678 let revision: { version: number; headOid: string; baseOid: string } | undefined;
679 let after: string | null = null;
680 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
681 const query = new URLSearchParams({
682 expectedVersion: String(version),
683 limit: String(CHANGES_PAGE_LIMIT),
684 });
685 if (after !== null) query.set("after", after);
686 const batch: typeof Changes.Type = yield* read(
687 "getChangeRequest",
688 input,
689 { path: `${path}/changes?${query}` },
690 Changes,
691 );
692 revision ??= {
693 version: batch.version,
694 headOid: batch.headOid,
695 baseOid: batch.comparisonBaseOid,
696 };
697 files.push(...batch.items);
698 const previous: string | null = after;
699 after = batch.next;
700 if (after === null || after === previous || batch.items.length === 0) break;
701 }
702 if (revision === undefined)
703 return {
704 headOid: null,
705 complete: true,
706 stats: { changedFiles: 0, additions: 0, deletions: 0 },
707 };
708 const key = `${input.host} ${input.repository.toLowerCase()} ${input.number} ${revision.baseOid} ${revision.headOid}`;
709 const held = lineTotals.get(key);
710 const { headOid } = revision;
711 // A listing that stopped before its last page counts only part of the diff, so nothing is held.
712 const listed = after === null;
713 if (held !== undefined)
714 return { headOid, complete: listed, stats: { changedFiles: files.length, ...held } };
715 const tooMany = files.length > LINE_STATS_MAX_FILES;
716 const details = files.some((file) => file.additions !== undefined)
717 ? Option.some(files)
718 : tooMany
719 ? Option.none()
720 : yield* Effect.forEach(
721 chunk(detailablePaths(files), DIFF_FILES_BATCH),
722 (paths) => readDiffFiles(input, revision, paths),
723 { concurrency: 4 },
724 ).pipe(
725 Effect.map((batches) => batches.flat()),
726 Effect.option,
727 );
728 // Unread hunks leave the lines unknown rather than zero; the file count still stands.
729 if (Option.isNone(details))
730 return { headOid, complete: listed && tooMany, stats: { changedFiles: files.length } };
731 const counted = details.value;
732 const totals = {
733 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
734 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
735 };
736 if (listed) remember(lineTotals, key, totals);
737 return { headOid, complete: listed, stats: { changedFiles: files.length, ...totals } };
738 });
739
740 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
741 input: PullRef,
742 pull: Json.GitCafePullDetail,
743 ) {
744 const tipsKey =
745 pull.headOid === null || pull.observedBaseOid == null
746 ? null
747 : `${input.host} ${input.repository.toLowerCase()} ${input.number} ${pull.targetBranch} ${pull.observedBaseOid} ${pull.headOid}`;
748 const heldStats = tipsKey === null ? undefined : statsByTips.get(tipsKey);
749 if (heldStats !== undefined) return heldStats;
750 const stats = yield* countLines(input, pull.version);
751 // A failed hunk read is retried next time rather than held as unknown, and a head that moved
752 // between the two reads would hold another pair's stats.
753 if (tipsKey !== null && stats.complete && stats.headOid === pull.headOid)
754 remember(statsByTips, tipsKey, stats.stats);
755 return stats.stats;
756 });
757
758 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
759 input: Parameters<PullRequestProviderApi["runAction"]>[0],
760 ) {
761 const pull = yield* readPull("merge", input);
762 if (pull.state === "merged") return;
763 if (pull.mergeRoute === "unsupported")
764 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
765 const base = yield* repositoryPath("merge", input);
766 // Native merges fence on the current target commit; provider-routed merges supply the base.
767 const baseOid =
768 pull.mergeRoute === "provider"
769 ? pull.observedBaseOid
770 : (yield* read(
771 "merge",
772 input,
773 {
774 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
775 },
776 BranchCommit,
777 )).oid;
778 if (pull.headOid === null || baseOid == null)
779 return yield* failure(
780 "merge",
781 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
782 );
783 const path = yield* pullPath("merge", input);
784 const outcome = yield* read(
785 "merge",
786 input,
787 {
788 method: "POST",
789 path: `${path}/merge`,
790 body: {
791 requestId: yield* randomUuidV4,
792 expectedVersion: pull.version,
793 headOid: pull.headOid,
794 baseOid,
795 strategy: input.mergeMethod ?? "merge",
796 },
797 },
798 MergeOutcome,
799 );
800 if (outcome.state === "failed")
801 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
802 });
803
804 const provider: PullRequestProviderApi = {
805 kind: SourceControlProviderKind.make("gitcafe"),
806 capabilities: CAPABILITIES,
807 getViewer: (input) =>
808 read(
809 "getViewer",
810 { host: input.host ?? "git.cafe" },
811 { path: "/auth/principal" },
812 Principal,
813 ).pipe(Effect.map((principal) => principal.handle)),
814 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
815 function* (input) {
816 const base = yield* repositoryPath("listChangeRequests", input);
817 const involved = input.involvement === "authored" || input.involvement === "reviewing";
818 let actorId: string | undefined;
819 if (involved) {
820 // The viewer is the token's principal, whose actor also matches the pull requests GitHub
821 // sync authored for its linked profile. When it can't be read, the listing comes back
822 // unnarrowed and the page's own involvement filter does the rest. A refused token or a
823 // rate limit still fails, since the service acts on those for the whole host.
824 const principal = yield* read(
825 "listChangeRequests",
826 input,
827 { path: "/auth/principal" },
828 Principal,
829 ).pipe(
830 Effect.asSome,
831 Effect.catchTags({
832 PullRequestProviderError: (error) =>
833 error.reason === "unauthenticated" || error.reason === "rate-limited"
834 ? Effect.fail(error)
835 : Effect.succeedNone,
836 }),
837 );
838 if (Option.isSome(principal)) {
839 if (principal.value.handle.toLowerCase() !== input.viewer.toLowerCase())
840 return { items: [], truncated: false, continues: false };
841 actorId = principal.value.actorId;
842 }
843 }
844 const { params: filterParams, unresolvedAuthor } = yield* listFilterParams(
845 { ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },
846 base,
847 );
848 const readPage = Effect.fn("readPage")(function (rows: number, after: string | null) {
849 const query = new URLSearchParams({ limit: String(rows), sort: "newest" });
850 if (input.state !== "all") query.set("state", input.state);
851 if (input.query?.trim()) query.set("q", input.query.trim());
852 for (const [key, value] of filterParams) query.set(key, value);
853 if (actorId !== undefined)
854 query.set(
855 input.involvement === "reviewing" ? "reviewers" : "authors",
856 encodeIds([actorId]),
857 );
858 if (after !== null) query.set("after", after);
859 return read(
860 "listChangeRequests",
861 input,
862 { path: `${base}/pulls?${query}` },
863 Json.GitCafePulls,
864 ).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));
865 });
866 if (unresolvedAuthor !== null) {
867 // Rows are only ever handed out narrowed by actor, so a continuation always carries on
868 // the same narrowed listing.
869 const key = authorKey(input.host, unresolvedAuthor);
870 let after: string | null = null;
871 let pages = 0;
872 do {
873 const page: typeof Json.GitCafePulls.Type = yield* readPage(PAGE_SIZE, after);
874 pages += 1;
875 after = page.items.length === 0 ? null : page.next;
876 } while (!knownAuthors.has(key) && after !== null && pages < AUTHOR_DISCOVERY_PAGES);
877 const found = knownAuthors.get(key);
878 if (found === undefined)
879 return { items: [], truncated: after !== null, continues: false };
880 filterParams.push(["authors", encodeIds([found])]);
881 }
882 const limit = Math.max(1, input.limit);
883 const items: Array<Json.GitCafePull> = [];
884 // GitCafe pages by an opaque token and orders by creation, so a continuation reads from the
885 // top and keeps only the rows created after the last one delivered. A count of rows would
886 // skip one for every row above it that closed in between.
887 const resume = parsePosition(input.cursor?.resumeAfter);
888 const isNew = (pull: Json.GitCafePull) => {
889 if (resume === null) return true;
890 const created = Date.parse(pull.createdAt);
891 return (
892 created < resume.created || (created === resume.created && pull.number < resume.number)
893 );
894 };
895 let next: string | null = null;
896 do {
897 const page: typeof Json.GitCafePulls.Type = yield* readPage(
898 resume === null ? Math.min(PAGE_SIZE, limit - items.length) : PAGE_SIZE,
899 next,
900 );
901 items.push(...page.items.filter(isNew));
902 next = page.items.length === 0 ? null : page.next;
903 } while (next !== null && items.length < limit);
904 const delivered = items.slice(0, limit);
905 const last = delivered.at(-1);
906 return {
907 ...(last === undefined ? {} : { resumeAfter: `${last.createdAt}~${last.number}` }),
908 items: delivered.map((pull) => {
909 const item = Json.toChangeRequest(pull, input);
910 return input.involvement === "reviewing" && actorId !== undefined
911 ? {
912 ...item,
913 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
914 }
915 : item;
916 }),
917 truncated: next !== null || items.length > limit,
918 continues: true,
919 };
920 },
921 ),
922 getChangeRequestPreview: (input) =>
923 readPull("getChangeRequestPreview", input).pipe(
924 Effect.map((pull) => ({ ...Json.toChangeRequest(pull, input), ...settledMerge(pull) })),
925 ),
926 getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")(
927 function* (input) {
928 const pull = yield* readPull("getChangeRequestSummary", input);
929 const changes =
930 pull.headOid === null
931 ? null
932 : yield* readLineStats(input, pull).pipe(Effect.orElseSucceed(() => null));
933 // A count that could not be read is absent rather than zero.
934 const {
935 additions: _additions,
936 deletions: _deletions,
937 ...summary
938 } = Json.toChangeRequest(pull, input);
939 return {
940 ...summary,
941 ...(changes === null ? {} : changes),
942 closedAt: pull.closedAt,
943 mergedAt: pull.mergedAt,
944 ...settledMerge(pull),
945 };
946 },
947 ),
948 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
949 const pull = yield* readPull("getChangeRequest", input);
950 const path = yield* pullPath("getChangeRequest", input);
951 const base = yield* repositoryPath("getChangeRequest", input);
952 // A single pull request read carries neither its reviewers nor its labels.
953 const [status, checks, changes, reviewers, labels] = yield* Effect.all(
954 [
955 read("getChangeRequest", input, { path: `${path}/status` }, Status),
956 pull.headOid === null
957 ? Effect.succeed(null)
958 : readPages(
959 "getChangeRequest",
960 input,
961 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
962 Json.GitCafeChecks,
963 ),
964 pull.headOid === null
965 ? Effect.succeed(null)
966 : readLineStats(input, pull).pipe(Effect.orElseSucceed(() => null)),
967 // Reviewers need `pr:review:read`, which a contents-only token lacks.
968 readPages("getChangeRequest", input, `${path}/reviewers`, Json.GitCafeActorEntries).pipe(
969 // @effect-diagnostics-next-line catchConditionalRefailToCatchIf:off - catchIf widens this paginated result to any in tsc-rs.
970 Effect.catch((error) =>
971 isForbidden(error) ? Effect.succeed({ items: [], next: null }) : Effect.fail(error),
972 ),
973 ),
974 readPages("getChangeRequest", input, `${path}/labels`, Json.GitCafeLabels),
975 ],
976 { concurrency: 5 },
977 );
978 const listed = { ...pull, reviewers: reviewers.items, labels: labels.items };
979 const checkList = checks === null ? [] : Json.toChecks(checks);
980 // GitCafe's own counts include runs a re-run replaced, so the newest runs are the state. A
981 // truncated listing may be missing a failure; the counts never call failing checks passing.
982 const checksState =
983 checks !== null && checks.next === null
984 ? Json.checksStateOf(checkList)
985 : status.checks.total === 0
986 ? null
987 : status.checks.failing > 0
988 ? ("failing" as const)
989 : status.checks.pending > 0
990 ? ("pending" as const)
991 : ("passing" as const);
992 const permissions = Json.toViewerPermissions(pull);
993 const merging = status.merge.reasons?.some((reason) => MERGE_IN_FLIGHT.has(reason)) ?? false;
994 return {
995 ...Json.toChangeRequest(listed, input),
996 autoMergeEnabled: merging,
997 headSha: pull.headOid,
998 body: pull.description ?? "",
999 ...(pull.sourceRepo === null
1000 ? {}
1001 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
1002 additions: changes?.additions ?? 0,
1003 deletions: changes?.deletions ?? 0,
1004 changedFiles: changes?.changedFiles ?? 0,
1005 closedAt: pull.closedAt,
1006 mergedAt: pull.mergedAt,
1007 mergeCommitSha: pull.mergeResultOid || pull.providerMerge?.mergeCommitOid || null,
1008 ...settledMerge(pull),
1009 reviewers: Json.toReviewers(listed, input.host),
1010 checks: checkList,
1011 ...(checksState === null ? {} : { checksState }),
1012 mergeability:
1013 status.merge.conflicts === "conflicting"
1014 ? ("conflicting" as const)
1015 : status.merge.conflicts === "none"
1016 ? ("mergeable" as const)
1017 : ("unknown" as const),
1018 baseComparison:
1019 status.merge.fastForward === null
1020 ? ("unknown" as const)
1021 : status.merge.fastForward
1022 ? ("up-to-date" as const)
1023 : ("behind" as const),
1024 mergeCapabilities: {
1025 merge: mergeStrategyOpen(status, "merge"),
1026 squash: mergeStrategyOpen(status, "squash"),
1027 rebase: mergeStrategyOpen(status, "rebase"),
1028 },
1029 viewerPermissions:
1030 status.merge.permitted === false || merging
1031 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
1032 : permissions,
1033 };
1034 }),
1035 getChangeRequestStack: (input) =>
1036 readStack("getChangeRequestStack", input).pipe(
1037 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
1038 ),
1039 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
1040 function* (input) {
1041 const pull = yield* readPull("getChangeRequestActivity", input);
1042 const path = yield* pullPath("getChangeRequestActivity", input);
1043 const operation = "getChangeRequestActivity";
1044 const [comments, reviews, commits, reactions] = yield* Effect.all(
1045 [
1046 readComments(operation, input),
1047 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
1048 pull.headOid === null
1049 ? Effect.succeed({ items: [], next: null })
1050 : // A closed pull request whose branch is gone keeps its head, but git.cafe answers
1051 // 404 for commits it no longer has; the conversation still stands without them.
1052 readPages(operation, input, `${path}/commits`, Json.GitCafeCommits).pipe(
1053 // @effect-diagnostics-next-line catchConditionalRefailToCatchIf:off - catchIf widens this paginated result to any in tsc-rs.
1054 Effect.catch((error) =>
1055 error.reason === "not-found"
1056 ? Effect.succeed({ items: [], next: null })
1057 : Effect.fail(error),
1058 ),
1059 ),
1060 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
1061 Effect.orElseSucceed(() => undefined),
1062 ),
1063 ],
1064 { concurrency: 4 },
1065 );
1066 return Json.toActivity({
1067 comments,
1068 reviews,
1069 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
1070 host: input.host,
1071 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
1072 ...(reactions === undefined ? {} : { reactions }),
1073 });
1074 },
1075 ),
1076 getViewerPermissions: (input) =>
1077 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
1078 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
1079 const page = yield* readDiffPage("getDiff", input, DIFF_FILES_BATCH);
1080 const details = yield* readDiffFiles(input, page.revision, detailablePaths(page.items));
1081 return {
1082 ...Json.toDiff({ items: withDetails(page.items, details) }),
1083 nextCursor: page.nextCursor,
1084 };
1085 }),
1086 getDiffFilePaths: Effect.fn("GitCafePullRequestProvider.getDiffFilePaths")(function* (input) {
1087 const page = yield* readDiffPage("getDiffFilePaths", input, CHANGES_PAGE_LIMIT);
1088 return {
1089 files: page.items.map((file) => ({
1090 oldPath: file.oldPath ?? file.path,
1091 newPath: file.path,
1092 })),
1093 nextCursor: page.nextCursor,
1094 };
1095 }),
1096 getDiffFileContents: Effect.fn("GitCafePullRequestProvider.getDiffFileContents")(
1097 function* (input) {
1098 const operation = "getDiffFileContents";
1099 if (input.commit !== undefined)
1100 return yield* failure(operation, "GitCafe commit diff contents are not supported yet.");
1101 const pull = yield* readPull(operation, input);
1102 if (!isCommitOid(pull.headOid))
1103 return yield* failure(
1104 operation,
1105 "GitCafe has not reported an immutable pull request head.",
1106 );
1107 const path = yield* pullPath(operation, input);
1108 const query = new URLSearchParams({ expectedVersion: String(pull.version), limit: "1" });
1109 // observedBaseOid is the target tip, not necessarily the diff's merge base.
1110 const snapshot = yield* read(
1111 operation,
1112 input,
1113 { path: `${path}/changes?${query}` },
1114 SourceSnapshot,
1115 );
1116 if (snapshot.version !== pull.version || snapshot.headOid !== pull.headOid)
1117 return yield* failure(
1118 operation,
1119 "GitCafe changed the pull request revision. Refresh the diff.",
1120 );
1121 const sourceRepository =
1122 pull.sourceRepo === null
1123 ? input.repository
1124 : `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`;
1125 const [oldContents, newContents] = yield* Effect.all(
1126 [
1127 input.changeType === "new"
1128 ? Effect.succeed("")
1129 : readDiffSource(input, snapshot.comparisonBaseOid, input.oldPath),
1130 input.changeType === "deleted"
1131 ? Effect.succeed("")
1132 : readDiffSource(
1133 { ...input, repository: sourceRepository },
1134 snapshot.headOid,
1135 input.newPath,
1136 ),
1137 ],
1138 { concurrency: 2 },
1139 );
1140 return { oldContents, newContents };
1141 },
1142 ),
1143 getCheckLogs: Effect.fn("GitCafePullRequestProvider.getCheckLogs")(function* (input) {
1144 const base = yield* repositoryPath("getCheckLogs", input);
1145 return yield* Effect.forEach(
1146 input.checks,
1147 (check): Effect.Effect<ProviderCheckLog, PullRequestProviderError> => {
1148 // GitCafe reads the log of a check its GitHub mirror ran.
1149 const checkId = gitHubActionsJobId(check.url);
1150 if (checkId === null) {
1151 return Effect.succeed({
1152 ...check,
1153 log: null,
1154 truncated: false,
1155 detail: "GitCafe holds no log for this check. Open its url.",
1156 });
1157 }
1158 return read(
1159 "getCheckLogs",
1160 input,
1161 { path: `${base}/ci/github/checks/${checkId}/log?tailBytes=${CHECK_LOG_TAIL_BYTES}` },
1162 CheckLog,
1163 ).pipe(
1164 Effect.map((log) => {
1165 const tail = tailLogLines(log.content, input.tailLines);
1166 return {
1167 ...check,
1168 log: tail.log,
1169 truncated: tail.truncated || log.truncated,
1170 detail: null,
1171 };
1172 }),
1173 // Sign-in and rate-limit failures fail the call; the rest are this check's.
1174 Effect.catchIf(isCheckFailure, (error) =>
1175 Effect.succeed({ ...check, log: null, truncated: false, detail: error.detail }),
1176 ),
1177 );
1178 },
1179 { concurrency: 4 },
1180 );
1181 }),
1182 rerunChecks: Effect.fn("GitCafePullRequestProvider.rerunChecks")(function* (input) {
1183 const base = yield* repositoryPath("rerunChecks", input);
1184 const runIds = new Set<string>();
1185 const located = input.checks.map((check) => {
1186 const runId = /\/actions\/runs\/(actwfrun_[A-Za-z0-9]+)/.exec(check.url ?? "")?.[1] ?? null;
1187 if (runId !== null) runIds.add(runId);
1188 return { check, runId };
1189 });
1190 const outcomes = new Map<string, string | null>();
1191 yield* Effect.forEach(
1192 runIds,
1193 (runId) =>
1194 send("rerunChecks", input, {
1195 method: "POST",
1196 path: `${base}/actions/runs/${runId}/rerun`,
1197 }).pipe(
1198 Effect.as<string | null>(null),
1199 Effect.catchIf(isCheckFailure, (error) => Effect.succeed(error.detail)),
1200 Effect.map((detail) => outcomes.set(runId, detail)),
1201 ),
1202 { concurrency: 2, discard: true },
1203 );
1204 return located.map(({ check, runId }): ProviderCheckRerun => {
1205 if (runId === null) {
1206 return {
1207 name: check.name,
1208 rerun: false,
1209 detail:
1210 gitHubActionsJobId(check.url) === null
1211 ? "GitCafe cannot re-run this check."
1212 : "This check ran on the GitHub mirror, so GitCafe cannot re-run it. Re-run it on GitHub.",
1213 };
1214 }
1215 const detail = outcomes.get(runId) ?? null;
1216 return { name: check.name, rerun: detail === null, detail };
1217 });
1218 }),
1219 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
1220 if (input.stackNumber !== undefined)
1221 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
1222 switch (input.action) {
1223 case "merge":
1224 return yield* merge(input);
1225 case "ready":
1226 case "draft":
1227 case "close":
1228 case "reopen": {
1229 const pull = yield* readPull(input.action, input);
1230 const path = yield* pullPath(input.action, input);
1231 const reply = yield* send(input.action, input, {
1232 method: "POST",
1233 path: `${path}/${input.action}`,
1234 body: { expectedVersion: pull.version },
1235 });
1236 const left = decodeActionReply(reply);
1237 if (Option.isNone(left)) return;
1238 // The reply carries no line totals or conflict state, so they stay absent.
1239 const {
1240 additions: _additions,
1241 deletions: _deletions,
1242 mergeability: _mergeability,
1243 ...summary
1244 } = Json.toChangeRequest(left.value, input);
1245 return {
1246 ...summary,
1247 ...(left.value.headOid === null ? {} : { headSha: left.value.headOid }),
1248 ...(left.value.closedAt === undefined ? {} : { closedAt: left.value.closedAt }),
1249 ...(left.value.mergedAt === undefined ? {} : { mergedAt: left.value.mergedAt }),
1250 };
1251 }
1252 default:
1253 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
1254 }
1255 }),
1256 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
1257 function* (input) {
1258 const pull = yield* readPull("updateChangeRequest", input);
1259 const path = yield* pullPath("updateChangeRequest", input);
1260 yield* read(
1261 "updateChangeRequest",
1262 input,
1263 {
1264 method: "PATCH",
1265 path,
1266 body: {
1267 expectedVersion: pull.version,
1268 ...(input.title === undefined ? {} : { title: input.title }),
1269 ...(input.body === undefined ? {} : { description: input.body }),
1270 },
1271 },
1272 Versioned,
1273 );
1274 },
1275 ),
1276 comment: (input) =>
1277 pullPath("comment", input).pipe(
1278 Effect.flatMap((path) =>
1279 read(
1280 "comment",
1281 input,
1282 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
1283 Written,
1284 ),
1285 ),
1286 Effect.asVoid,
1287 ),
1288 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
1289 if (!isId(input.commentId))
1290 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
1291 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
1292 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
1293 yield* read(
1294 "updateComment",
1295 input,
1296 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
1297 Written,
1298 );
1299 }),
1300 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
1301 if (input.comments.length > 0)
1302 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
1303 const pull = yield* readPull("submitReview", input);
1304 if (pull.headOid === null)
1305 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
1306 const path = yield* pullPath("submitReview", input);
1307 yield* read(
1308 "submitReview",
1309 input,
1310 {
1311 method: "POST",
1312 path: `${path}/reviews`,
1313 body: {
1314 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
1315 ...(input.body.length === 0 ? {} : { body: input.body }),
1316 commitOid: pull.headOid,
1317 expectedVersion: pull.version,
1318 requestId: yield* randomUuidV4,
1319 },
1320 },
1321 Written,
1322 );
1323 }),
1324 listReviewerCandidates: Effect.fn("GitCafePullRequestProvider.listReviewerCandidates")(
1325 function* (input) {
1326 const operation = "listReviewerCandidates";
1327 const path = yield* pullPath(operation, input);
1328 const [pull, candidates, reviewers] = yield* Effect.all(
1329 [
1330 readPull(operation, input),
1331 readPages(
1332 operation,
1333 input,
1334 `${path}/reviewer-candidates`,
1335 Json.GitCafeActorEntries,
1336 ).pipe(explainReviewerScopes(operation)),
1337 readPages(operation, input, `${path}/reviewers`, Listed).pipe(
1338 explainReviewerScopes(operation),
1339 ),
1340 ],
1341 { concurrency: 3 },
1342 );
1343 return {
1344 candidates: Json.toReviewerCandidates(candidates, {
1345 requested: new Set(reviewers.items.map((reviewer) => reviewer.id)),
1346 authorActorId: pull.author.actorId,
1347 host: input.host,
1348 }),
1349 truncated: candidates.next !== null,
1350 };
1351 },
1352 ),
1353 setReviewerRequest: (input) =>
1354 toggleListed(
1355 "setReviewerRequest",
1356 input,
1357 { name: "reviewers", key: "actorIds" },
1358 input.reviewers.map((reviewer) => reviewer.id),
1359 input.requested,
1360 ).pipe(explainReviewerScopes("setReviewerRequest")),
1361 listLabelCandidates: Effect.fn("GitCafePullRequestProvider.listLabelCandidates")(
1362 function* (input) {
1363 const operation = "listLabelCandidates";
1364 const base = yield* repositoryPath(operation, input);
1365 const [labels, applied] = yield* Effect.all(
1366 [
1367 readPages(operation, input, `${base}/labels`, Json.GitCafeLabels),
1368 readPages(operation, input, `${base}/pulls/${input.number}/labels`, Listed),
1369 ],
1370 { concurrency: 2 },
1371 );
1372 const appliedIds = new Set(applied.items.map((label) => label.id));
1373 return {
1374 candidates: labels.items.map((label) => ({
1375 name: label.name,
1376 color: label.color,
1377 description: label.description ?? null,
1378 isApplied: appliedIds.has(label.id),
1379 })),
1380 truncated: labels.next !== null,
1381 };
1382 },
1383 ),
1384 listRepositoryLabels: Effect.fn("GitCafePullRequestProvider.listRepositoryLabels")(
1385 function* (input) {
1386 const operation = "listRepositoryLabels";
1387 const base = yield* repositoryPath(operation, input);
1388 const labels = yield* readPages(operation, input, `${base}/labels`, Json.GitCafeLabels);
1389 return {
1390 items: labels.items.map((label) => ({ name: label.name, color: label.color })),
1391 truncated: labels.next !== null,
1392 };
1393 },
1394 ),
1395 searchRepositoryAuthors: Effect.fn("GitCafePullRequestProvider.searchRepositoryAuthors")(
1396 function* (input) {
1397 const operation = "searchRepositoryAuthors";
1398 const query = input.query?.trim() ?? "";
1399 // User search needs two characters; before that the repository's own people stand in.
1400 const path =
1401 query.length < 2
1402 ? `${yield* repositoryPath(operation, input)}/collaborators?${new URLSearchParams({ limit: "50" })}`
1403 : `/users?${new URLSearchParams({ q: query, limit: "50" })}`;
1404 const people = yield* read(operation, input, { path }, Json.GitCafePeople);
1405 return { items: Json.toPeople(people, input.host), truncated: people.next !== null };
1406 },
1407 ),
1408 setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {
1409 const base = yield* repositoryPath("setLabels", input);
1410 const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);
1411 const selected = labels.items.filter((label) => input.labels.includes(label.name));
1412 if (selected.length !== input.labels.length)
1413 return yield* failure("setLabels", "One or more requested labels could not be found.");
1414 yield* toggleListed(
1415 "setLabels",
1416 input,
1417 { name: "labels", key: "labelIds" },
1418 selected.map((label) => label.id),
1419 input.applied,
1420 );
1421 }),
1422 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
1423 if (!isId(input.threadId))
1424 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
1425 const path = yield* pullPath("replyToThread", input);
1426 yield* read(
1427 "replyToThread",
1428 input,
1429 {
1430 method: "POST",
1431 path: `${path}/comments/${input.threadId}/replies`,
1432 body: { body: input.body },
1433 },
1434 Written,
1435 );
1436 }),
1437 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
1438 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
1439 const subject =
1440 input.subjectId === undefined
1441 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
1442 : { kind: "pull_request_comment" as const, id: input.subjectId };
1443 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
1444 const mine = reactions.items.find(
1445 (item) =>
1446 item.subject.kind === subject.kind &&
1447 item.subject.id === subject.id &&
1448 item.emoji.kind === "unicode" &&
1449 Json.reactionContent(item.emoji.value) === input.content,
1450 )?.viewerReactionId;
1451 if (input.reacted === (mine != null)) return;
1452 if (input.reacted) {
1453 yield* send("setReaction", input, {
1454 method: "POST",
1455 path,
1456 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
1457 });
1458 return;
1459 }
1460 if (mine == null) return;
1461 if (!isId(mine))
1462 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
1463 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
1464 }),
1465 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
1466 function* (input) {
1467 const comments = yield* readComments("setThreadResolution", input);
1468 const root = comments.items.find(
1469 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
1470 );
1471 if (root === undefined || root.version === undefined || !isId(root.id))
1472 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
1473 if (input.resolved === (root.resolvedAt !== null)) return;
1474 const path = yield* pullPath("setThreadResolution", input);
1475 yield* read(
1476 "setThreadResolution",
1477 input,
1478 {
1479 method: "POST",
1480 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
1481 body: { expectedVersion: root.version },
1482 },
1483 Written,
1484 );
1485 },
1486 ),
1487 };
1488 return provider;
1489});