Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitCafePullRequestProvider.ts

1,007 lines38.7 KB

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 NonNegativeInt,
8 TrimmedNonEmptyString,
9 type PullRequestCapabilities,
10 type PullRequestStackHead,
11} from "@t3tools/contracts";
12import {
13 PullRequestProviderError,
14 type ProviderRepositoryRef,
15 type PullRequestProviderApi,
16} from "@t3tools/source-control-core/server/PullRequestProvider";
17​
18import * as GitCafeApi from "./GitCafeApi.ts";
19import * as GitCafeHosts from "./gitCafeHosts.ts";
20import * as Json from "./gitCafePullRequestJson.ts";
21import { definition } from "../client/definition.ts";
22​
23const CAPABILITIES: PullRequestCapabilities = {
24 diff: true,
25 comment: true,
26 actions: [...definition.changeRequestActions],
27 mergeMethods: ["merge", "squash", "rebase"],
28 // Only through a stack: GitCafe's one branch update restacks every layer above it.
29 updateMethods: ["rebase"],
30 search: true,
31 stacks: true,
32 stackActions: true,
33 reactions: true,
34 labels: true,
35 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
36 review: {
37 inlineComment: false,
38 reply: true,
39 resolve: true,
40 verdicts: ["approve", "request-changes", "comment"],
41 },
42 reviewers: { request: true, listCandidates: true },
43 edit: { changeRequest: true, comment: true },
44};
45​
46const PAGE_SIZE = 100;
47const MAX_PAGES = 10;
48/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
49const DIFF_FILES_BATCH = 64;
50/**
51 * Line totals cost one hunk read per batch, so a pull request larger than this reports none
52 * rather than reading every file.
53 */
54const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
55const MAX_CHANGE_PAGES = 20;
56const LINE_STATS_CACHE_SIZE = 256;
57​
58const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
59 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
60 items.slice(index * size, (index + 1) * size),
61 );
62​
63const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
64 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
65​
66const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
67 status.merge.permitted !== false &&
68 status.merge.strategies.includes(strategy) &&
69 !(status.merge.blockers ?? []).some((blocker) =>
70 (blocker.blockedStrategies ?? []).includes(strategy),
71 );
72​
73const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
74const isId = Schema.is(Id);
75const isApiError = Schema.is(GitCafeApi.GitCafeApiError);
76const Principal = Schema.Struct({ handle: TrimmedNonEmptyString });
77const Written = Schema.Struct({ id: Id });
78const Versioned = Schema.Struct({ version: NonNegativeInt });
79const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
80const Status = Schema.Struct({
81 merge: Schema.Struct({
82 // The API reference lists "unknown" and "conflicting", but git.cafe also sends "none" and
83 // "pending", so any state is read and only the known ones are mapped.
84 conflicts: Schema.String,
85 fastForward: Schema.NullOr(Schema.Boolean),
86 strategies: Schema.Array(Schema.String),
87 permitted: Schema.optional(Schema.Boolean),
88 blockers: Schema.optional(
89 Schema.Array(
90 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
91 ),
92 ),
93 }),
94 checks: Schema.Struct({
95 pending: NonNegativeInt,
96 failing: NonNegativeInt,
97 total: NonNegativeInt,
98 }),
99});
100const Listed = Schema.Struct({
101 items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString })),
102 next: Schema.NullOr(Schema.String),
103});
104const FilterOptions = Schema.Struct({
105 actors: Schema.Array(
106 Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString }),
107 ),
108});
109const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
110const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
111const Snapshot = {
112 version: NonNegativeInt,
113 headOid: TrimmedNonEmptyString,
114 comparisonBaseOid: TrimmedNonEmptyString,
115};
116const Changes = Schema.Struct({
117 ...Snapshot,
118 items: Json.GitCafeDiffFiles,
119 next: Schema.NullOr(TrimmedNonEmptyString),
120});
121const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
122const DiffCursor = Schema.Struct({
123 version: NonNegativeInt,
124 headOid: TrimmedNonEmptyString,
125 baseOid: TrimmedNonEmptyString,
126 after: TrimmedNonEmptyString,
127});
128const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
129const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
130const MergeOutcome = Schema.Struct({
131 id: Schema.String,
132 state: Schema.Literals(["accepted", "completed", "failed"]),
133 reason: Schema.optional(Schema.String),
134});
135const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
136const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
137​
138type PullRef = ProviderRepositoryRef & { readonly number: number };
139type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
140​
141function stackHeadsCurrent(
142 stack: Json.GitCafeStack,
143 input: { readonly number: number; readonly merge: boolean },
144 expected: ReadonlyArray<PullRequestStackHead>,
145): boolean {
146 const members = stack.members.toSorted((a, b) => a.position - b.position);
147 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
148 if (index === -1) return false;
149 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
150 (member) => member.state !== "merged",
151 );
152 return (
153 moved.length === expected.length &&
154 moved.every(
155 (member) =>
156 member.headOid !== undefined &&
157 expected.some(
158 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
159 ),
160 )
161 );
163​
164const withDetails = (
165 files: ReadonlyArray<Json.GitCafeDiffFile>,
166 details: ReadonlyArray<Json.GitCafeDiffFile>,
167) => {
168 const byPath = new Map(details.map((file) => [file.path, file]));
169 return files.map((file) => byPath.get(file.path) ?? file);
170};
171​
172/** @public Service construction is part of the canonical Effect module API. */
173export const make = Effect.gen(function* () {
174 const api = yield* GitCafeApi.GitCafeApi;
175​
176 const failure = (operation: string, detail: string, cause?: unknown) =>
177 new PullRequestProviderError({
178 provider: SourceControlProviderKind.make("gitcafe"),
179 operation,
180 reason: "failed",
181 detail,
182 ...(cause === undefined ? {} : { cause }),
183 });
184​
185 const repositoryPath = (
186 operation: string,
187 input: ProviderRepositoryRef,
188 ): Effect.Effect<string, PullRequestProviderError> =>
189 GitCafeHosts.isGitCafeHost(input.host) &&
190 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
191 ? Effect.succeed(`/repos/${input.repository}`)
192 : Effect.fail(
193 failure(
194 operation,
195 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
196 ),
197 );
198​
199 const send = (
200 operation: string,
201 input: Pick<ProviderRepositoryRef, "host">,
202 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
203 ) =>
204 api.request({ ...request, host: input.host, operation }).pipe(
205 Effect.mapError(
206 (error) =>
207 new PullRequestProviderError({
208 provider: SourceControlProviderKind.make("gitcafe"),
209 operation,
210 reason: error.reason,
211 detail: error.detail,
212 cause: error,
213 }),
214 ),
215 );
216​
217 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
218 operation: string,
219 input: Pick<ProviderRepositoryRef, "host">,
220 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
221 schema: S,
222 ) =>
223 send(operation, input, request).pipe(
224 Effect.flatMap((raw) =>
225 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
226 Effect.mapError((cause) =>
227 failure(operation, "GitCafe returned an unreadable response.", cause),
228 ),
229 ),
230 ),
231 );
232​
233 const pullPath = (operation: string, input: PullRef) =>
234 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
235​
236 const readPull = (operation: string, input: PullRef) =>
237 pullPath(operation, input).pipe(
238 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
239 );
240​
241 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
242 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
243 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
244 const items: Array<S["Type"]["items"][number]> = [];
245 let next: string | null = null;
246 for (let page = 0; page < MAX_PAGES; page++) {
247 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
248 if (next !== null) query.set("after", next);
249 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
250 items.push(...batch.items);
251 const previous: string | null = next;
252 next = batch.next;
253 if (next === null || next === previous || batch.items.length === 0) break;
254 }
255 return { items, next };
256 });
257​
258 const readComments = (operation: string, input: PullRef) =>
259 pullPath(operation, input).pipe(
260 Effect.flatMap((path) =>
261 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
262 ),
263 );
264​
265 const isForbidden = (error: PullRequestProviderError) =>
266 isApiError(error.cause) && error.cause.status === 403;
267​
268 /**
269 * GitCafe offers no way to read a token's scopes, so reviewer controls show
270 * for anyone who may edit the pull request; a token without the reviewer
271 * scopes learns which ones it lacks when it uses them.
272 */
273 const explainReviewerScopes =
274 (operation: string) =>
275 <A, R>(effect: Effect.Effect<A, PullRequestProviderError, R>) =>
276 effect.pipe(
277 Effect.catchIf(isForbidden, (error) =>
278 Effect.fail(
279 failure(
280 operation,
281 "This GitCafe token cannot request reviewers. It needs the pr:review:read and pr:reviewers:write scopes.",
282 error,
283 ),
284 ),
285 ),
286 );
287​
288 /**
289 * GitCafe replaces a pull request's whole reviewer or label list, so one toggle reads the
290 * list, changes it, and writes it back fenced on the pull request's version. The version is
291 * read first: a change landing between the two reads then fails the fence instead of being
292 * overwritten.
293 */
294 const toggleListed = Effect.fn("GitCafePullRequestProvider.toggleListed")(function* (
295 operation: string,
296 input: PullRef,
297 list: { readonly name: "reviewers" | "labels"; readonly key: "actorIds" | "labelIds" },
298 ids: ReadonlyArray<string>,
299 on: boolean,
300 ) {
301 const path = yield* pullPath(operation, input);
302 const pull = yield* readPull(operation, input);
303 const listed = yield* readPages(operation, input, `${path}/${list.name}`, Listed);
304 const current = listed.items.map((item) => item.id);
305 const next = on
306 ? [...new Set([...current, ...ids])]
307 : current.filter((id) => !ids.includes(id));
308 if (next.length === current.length) return;
309 yield* read(
310 operation,
311 input,
312 {
313 method: "PUT",
314 path: `${path}/${list.name}`,
315 body: { expectedVersion: pull.version, [list.key]: next },
316 },
317 Versioned,
318 );
319 });
320​
321 /**
322 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
323 * open layer's pull is read.
324 */
325 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
326 operation: string,
327 input: PullRef,
328 ) {
329 const path = yield* pullPath(operation, input);
330 const { stack } = yield* read(
331 operation,
332 input,
333 { path: `${path}/stack` },
334 Json.GitCafeStackEnvelope,
335 );
336 if (stack === null) return null;
337 const members = yield* Effect.forEach(
338 stack.members,
339 (member) =>
340 member.state === "merged"
341 ? Effect.succeed(member)
342 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
343 Effect.map((pull) =>
344 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
345 ),
346 ),
347 { concurrency: 4 },
348 );
349 return { ...stack, members };
350 });
351​
352 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
353 input: PullRef,
354 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
355 paths: ReadonlyArray<string>,
356 ) {
357 if (paths.length === 0) return [];
358 const path = yield* pullPath("getDiff", input);
359 const files = yield* read(
360 "getDiff",
361 input,
362 {
363 method: "POST",
364 path: `${path}/diff-files`,
365 body: { paths, expectedVersion: revision.version },
366 },
367 DiffFiles,
368 );
369 if (
370 files.version !== revision.version ||
371 files.headOid !== revision.headOid ||
372 files.comparisonBaseOid !== revision.baseOid
373 )
374 return yield* failure(
375 "getDiff",
376 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
377 );
378 return files.items;
379 });
380​
381 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
382 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
383 ) {
384 const land = input.action === "merge";
385 const operation = land ? "landStackThrough" : "restackStack";
386 if (!land && input.action !== "update-branch")
387 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
388 const stack = yield* readStack(operation, input);
389 if (
390 stack === null ||
391 stack.number !== input.stackNumber ||
392 input.expectedStackHeads === undefined ||
393 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
394 )
395 return yield* failure(
396 operation,
397 "The stack changed since it was read. Refresh it and try again.",
398 );
399 const base = yield* repositoryPath(operation, input);
400 const outcome = yield* read(
401 operation,
402 input,
403 {
404 method: "POST",
405 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
406 body: land
407 ? {
408 expectedRevision: stack.revision,
409 requestId: yield* randomUuidV4,
410 throughPullRequestNumber: input.number,
411 strategy: input.mergeMethod ?? "merge",
412 }
413 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
414 },
415 StackOutcome,
416 );
417 if (FAILED_STACK_STATES.has(outcome.state))
418 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
419 });
420​
421 // GitCafe's pulls carry no line totals, and linked pull requests are summarized every minute,
422 // so hunk totals are held per compared pair of commits. The file list that names the pair is
423 // cheap; a retarget or a landed parent layer moves the base without moving the head.
424 const lineTotals = new Map<string, { readonly additions: number; readonly deletions: number }>();
425​
426 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
427 input: PullRef,
428 version: number,
429 ) {
430 const path = yield* pullPath("getChangeRequest", input);
431 const files: Array<Json.GitCafeDiffFile> = [];
432 let revision: { version: number; headOid: string; baseOid: string } | undefined;
433 let after: string | null = null;
434 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
435 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
436 if (after !== null) query.set("after", after);
437 const batch: typeof Changes.Type = yield* read(
438 "getChangeRequest",
439 input,
440 { path: `${path}/changes?${query}` },
441 Changes,
442 );
443 revision ??= {
444 version: batch.version,
445 headOid: batch.headOid,
446 baseOid: batch.comparisonBaseOid,
447 };
448 files.push(...batch.items);
449 const previous: string | null = after;
450 after = batch.next;
451 if (after === null || after === previous || batch.items.length === 0) break;
452 }
453 if (revision === undefined) return { changedFiles: 0, additions: 0, deletions: 0 };
454 const key = `${input.host} ${input.repository.toLowerCase()} ${input.number} ${revision.baseOid} ${revision.headOid}`;
455 const held = lineTotals.get(key);
456 if (held !== undefined) return { changedFiles: files.length, ...held };
457 const details = files.some((file) => file.additions !== undefined)
458 ? Option.some(files)
459 : files.length > LINE_STATS_MAX_FILES
460 ? Option.none()
461 : yield* Effect.forEach(
462 chunk(detailablePaths(files), DIFF_FILES_BATCH),
463 (paths) => readDiffFiles(input, revision, paths),
464 { concurrency: 4 },
465 ).pipe(
466 Effect.map((batches) => batches.flat()),
467 Effect.option,
468 );
469 // Unread hunks leave the lines unknown rather than zero; the file count still stands.
470 if (Option.isNone(details)) return { changedFiles: files.length };
471 const counted = details.value;
472 const totals = {
473 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
474 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
475 };
476 if (lineTotals.size >= LINE_STATS_CACHE_SIZE)
477 lineTotals.delete(lineTotals.keys().next().value!);
478 lineTotals.set(key, totals);
479 return { changedFiles: files.length, ...totals };
480 });
481​
482 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
483 input: Parameters<PullRequestProviderApi["runAction"]>[0],
484 ) {
485 const pull = yield* readPull("merge", input);
486 if (pull.state === "merged") return;
487 if (pull.mergeRoute === "unsupported")
488 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
489 const base = yield* repositoryPath("merge", input);
490 // GitCafe observes the base only for merges it routes to the provider; a native merge is
491 // fenced on the target branch's current commit.
492 const baseOid =
493 pull.mergeRoute === "provider"
494 ? pull.observedBaseOid
495 : (yield* read(
496 "merge",
497 input,
498 {
499 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
500 },
501 BranchCommit,
502 )).oid;
503 if (pull.headOid === null || baseOid == null)
504 return yield* failure(
505 "merge",
506 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
507 );
508 const path = yield* pullPath("merge", input);
509 const outcome = yield* read(
510 "merge",
511 input,
512 {
513 method: "POST",
514 path: `${path}/merge`,
515 body: {
516 requestId: yield* randomUuidV4,
517 expectedVersion: pull.version,
518 headOid: pull.headOid,
519 baseOid,
520 strategy: input.mergeMethod ?? "merge",
521 },
522 },
523 MergeOutcome,
524 );
525 if (outcome.state === "failed")
526 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
527 });
528​
529 const provider: PullRequestProviderApi = {
530 kind: SourceControlProviderKind.make("gitcafe"),
531 capabilities: CAPABILITIES,
532 getViewer: (input) =>
533 read(
534 "getViewer",
535 { host: input.host ?? "git.cafe" },
536 { path: "/auth/principal" },
537 Principal,
538 ).pipe(Effect.map((principal) => principal.handle)),
539 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
540 function* (input) {
541 const base = yield* repositoryPath("listChangeRequests", input);
542 const involved = input.involvement === "authored" || input.involvement === "reviewing";
543 let actorId: string | undefined;
544 if (involved) {
545 // A host narrows as far as it can: when the actor list can't be read, the listing comes
546 // back unnarrowed and the page's own involvement filter does the rest. A refused token
547 // or a rate limit still fails, since the service acts on those for the whole host.
548 const options = yield* read(
549 "listChangeRequests",
550 input,
551 { path: `${base}/filter-options` },
552 FilterOptions,
553 ).pipe(
554 Effect.map(Option.some),
555 Effect.catchTags({
556 PullRequestProviderError: (error) =>
557 error.reason === "unauthenticated" || error.reason === "rate-limited"
558 ? Effect.fail(error)
559 : Effect.succeed(Option.none()),
560 }),
561 );
562 if (Option.isSome(options)) {
563 actorId = options.value.actors.find(
564 (actor) => actor.handle.toLowerCase() === input.viewer.toLowerCase(),
565 )?.actorId;
566 if (actorId === undefined) return { items: [], truncated: false, continues: false };
567 }
568 }
569 const limit = Math.max(1, input.limit);
570 const items: Array<Json.GitCafePull> = [];
571 let next: string | null = null;
572 do {
573 const query = new URLSearchParams({
574 limit: String(Math.min(PAGE_SIZE, limit - items.length)),
575 sort: "newest",
576 });
577 if (input.state !== "all") query.set("state", input.state);
578 if (input.query?.trim()) query.set("q", input.query.trim());
579 if (actorId !== undefined)
580 query.set(
581 input.involvement === "reviewing" ? "reviewers" : "authors",
582 encodeActorIds([actorId]),
583 );
584 if (next !== null) query.set("after", next);
585 const page: typeof Json.GitCafePulls.Type = yield* read(
586 "listChangeRequests",
587 input,
588 { path: `${base}/pulls?${query}` },
589 Json.GitCafePulls,
590 );
591 items.push(...page.items);
592 next = page.items.length === 0 ? null : page.next;
593 } while (next !== null && items.length < limit);
594 return {
595 items: items.slice(0, limit).map((pull) => {
596 const item = Json.toChangeRequest(pull, input);
597 return input.involvement === "reviewing" && actorId !== undefined
598 ? {
599 ...item,
600 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
601 }
602 : item;
603 }),
604 truncated: next !== null,
605 continues: false,
606 };
607 },
608 ),
609 getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")(
610 function* (input) {
611 const pull = yield* readPull("getChangeRequestSummary", input);
612 const changes =
613 pull.headOid === null
614 ? null
615 : yield* readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null));
616 // A count that could not be read is absent rather than zero.
617 const {
618 additions: _additions,
619 deletions: _deletions,
620 ...summary
621 } = Json.toChangeRequest(pull, input);
622 return {
623 ...summary,
624 ...(changes === null ? {} : changes),
625 closedAt: pull.closedAt,
626 mergedAt: pull.mergedAt,
627 };
628 },
629 ),
630 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
631 const pull = yield* readPull("getChangeRequest", input);
632 const path = yield* pullPath("getChangeRequest", input);
633 const base = yield* repositoryPath("getChangeRequest", input);
634 // A single pull request read carries neither its reviewers nor its labels.
635 const [status, checks, changes, reviewers, labels] = yield* Effect.all(
636 [
637 read("getChangeRequest", input, { path: `${path}/status` }, Status),
638 pull.headOid === null
639 ? Effect.succeed(null)
640 : readPages(
641 "getChangeRequest",
642 input,
643 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
644 Json.GitCafeChecks,
645 ),
646 pull.headOid === null
647 ? Effect.succeed(null)
648 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
649 // Reviewers need `pr:review:read`, which a contents-only token lacks.
650 readPages("getChangeRequest", input, `${path}/reviewers`, Json.GitCafeActorEntries).pipe(
651 Effect.catch((error) =>
652 isForbidden(error) ? Effect.succeed({ items: [], next: null }) : Effect.fail(error),
653 ),
654 ),
655 readPages("getChangeRequest", input, `${path}/labels`, Json.GitCafeLabels),
656 ],
657 { concurrency: 5 },
658 );
659 const listed = { ...pull, reviewers: reviewers.items, labels: labels.items };
660 const permissions = Json.toViewerPermissions(pull);
661 return {
662 ...Json.toChangeRequest(listed, input),
663 headSha: pull.headOid,
664 body: pull.description ?? "",
665 ...(pull.sourceRepo === null
666 ? {}
667 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
668 additions: changes?.additions ?? 0,
669 deletions: changes?.deletions ?? 0,
670 changedFiles: changes?.changedFiles ?? 0,
671 closedAt: pull.closedAt,
672 mergedAt: pull.mergedAt,
673 reviewers: Json.toReviewers(listed, input.host),
674 checks: checks === null ? [] : Json.toChecks(checks),
675 ...(status.checks.total === 0
676 ? {}
677 : {
678 checksState:
679 status.checks.failing > 0
680 ? ("failing" as const)
681 : status.checks.pending > 0
682 ? ("pending" as const)
683 : ("passing" as const),
684 }),
685 mergeability:
686 status.merge.conflicts === "conflicting"
687 ? ("conflicting" as const)
688 : status.merge.conflicts === "none"
689 ? ("mergeable" as const)
690 : ("unknown" as const),
691 baseComparison:
692 status.merge.fastForward === null
693 ? ("unknown" as const)
694 : status.merge.fastForward
695 ? ("up-to-date" as const)
696 : ("behind" as const),
697 mergeCapabilities: {
698 merge: mergeStrategyOpen(status, "merge"),
699 squash: mergeStrategyOpen(status, "squash"),
700 rebase: mergeStrategyOpen(status, "rebase"),
701 },
702 viewerPermissions:
703 status.merge.permitted === false
704 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
705 : permissions,
706 };
707 }),
708 getChangeRequestStack: (input) =>
709 readStack("getChangeRequestStack", input).pipe(
710 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
711 ),
712 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
713 function* (input) {
714 const pull = yield* readPull("getChangeRequestActivity", input);
715 const path = yield* pullPath("getChangeRequestActivity", input);
716 const operation = "getChangeRequestActivity";
717 const [comments, reviews, commits, reactions] = yield* Effect.all(
718 [
719 readComments(operation, input),
720 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
721 pull.headOid === null
722 ? Effect.succeed({ items: [], next: null })
723 : readPages(operation, input, `${path}/commits`, Json.GitCafeCommits),
724 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
725 Effect.orElseSucceed(() => undefined),
726 ),
727 ],
728 { concurrency: 4 },
729 );
730 return Json.toActivity({
731 comments,
732 reviews,
733 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
734 host: input.host,
735 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
736 ...(reactions === undefined ? {} : { reactions }),
737 });
738 },
739 ),
740 getViewerPermissions: (input) =>
741 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
742 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
743 if (input.commit !== undefined)
744 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
745 const cursor =
746 input.cursor === undefined
747 ? null
748 : yield* decodeDiffCursor(input.cursor).pipe(
749 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
750 );
751 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
752 const path = yield* pullPath("getDiff", input);
753 const query = new URLSearchParams({
754 expectedVersion: String(version),
755 limit: String(DIFF_FILES_BATCH),
756 });
757 if (cursor !== null) query.set("after", cursor.after);
758 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
759 if (
760 page.version !== version ||
761 (cursor !== null &&
762 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
763 )
764 return yield* failure(
765 "getDiff",
766 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
767 );
768 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
769 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
770 return {
771 ...Json.toDiff({ items: withDetails(page.items, details) }),
772 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
773 };
774 }),
775 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
776 if (input.stackNumber !== undefined)
777 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
778 switch (input.action) {
779 case "merge":
780 return yield* merge(input);
781 case "ready":
782 case "draft":
783 case "close":
784 case "reopen": {
785 const pull = yield* readPull(input.action, input);
786 const path = yield* pullPath(input.action, input);
787 yield* send(input.action, input, {
788 method: "POST",
789 path: `${path}/${input.action}`,
790 body: { expectedVersion: pull.version },
791 });
792 return;
793 }
794 default:
795 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
796 }
797 }),
798 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
799 function* (input) {
800 const pull = yield* readPull("updateChangeRequest", input);
801 const path = yield* pullPath("updateChangeRequest", input);
802 yield* read(
803 "updateChangeRequest",
804 input,
805 {
806 method: "PATCH",
807 path,
808 body: {
809 expectedVersion: pull.version,
810 ...(input.title === undefined ? {} : { title: input.title }),
811 ...(input.body === undefined ? {} : { description: input.body }),
812 },
813 },
814 Versioned,
815 );
816 },
817 ),
818 comment: (input) =>
819 pullPath("comment", input).pipe(
820 Effect.flatMap((path) =>
821 read(
822 "comment",
823 input,
824 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
825 Written,
826 ),
827 ),
828 Effect.asVoid,
829 ),
830 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
831 if (!isId(input.commentId))
832 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
833 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
834 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
835 yield* read(
836 "updateComment",
837 input,
838 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
839 Written,
840 );
841 }),
842 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
843 if (input.comments.length > 0)
844 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
845 const pull = yield* readPull("submitReview", input);
846 if (pull.headOid === null)
847 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
848 const path = yield* pullPath("submitReview", input);
849 yield* read(
850 "submitReview",
851 input,
852 {
853 method: "POST",
854 path: `${path}/reviews`,
855 body: {
856 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
857 ...(input.body.length === 0 ? {} : { body: input.body }),
858 commitOid: pull.headOid,
859 expectedVersion: pull.version,
860 requestId: yield* randomUuidV4,
861 },
862 },
863 Written,
864 );
865 }),
866 listReviewerCandidates: Effect.fn("GitCafePullRequestProvider.listReviewerCandidates")(
867 function* (input) {
868 const operation = "listReviewerCandidates";
869 const path = yield* pullPath(operation, input);
870 const [pull, candidates, reviewers] = yield* Effect.all(
871 [
872 readPull(operation, input),
873 readPages(
874 operation,
875 input,
876 `${path}/reviewer-candidates`,
877 Json.GitCafeActorEntries,
878 ).pipe(explainReviewerScopes(operation)),
879 readPages(operation, input, `${path}/reviewers`, Listed).pipe(
880 explainReviewerScopes(operation),
881 ),
882 ],
883 { concurrency: 3 },
884 );
885 return {
886 candidates: Json.toReviewerCandidates(candidates, {
887 requested: new Set(reviewers.items.map((reviewer) => reviewer.id)),
888 authorActorId: pull.author.actorId,
889 host: input.host,
890 }),
891 truncated: candidates.next !== null,
892 };
893 },
894 ),
895 setReviewerRequest: (input) =>
896 toggleListed(
897 "setReviewerRequest",
898 input,
899 { name: "reviewers", key: "actorIds" },
900 input.reviewers.map((reviewer) => reviewer.id),
901 input.requested,
902 ).pipe(explainReviewerScopes("setReviewerRequest")),
903 listLabelCandidates: Effect.fn("GitCafePullRequestProvider.listLabelCandidates")(
904 function* (input) {
905 const operation = "listLabelCandidates";
906 const base = yield* repositoryPath(operation, input);
907 const [labels, applied] = yield* Effect.all(
908 [
909 readPages(operation, input, `${base}/labels`, Json.GitCafeLabels),
910 readPages(operation, input, `${base}/pulls/${input.number}/labels`, Listed),
911 ],
912 { concurrency: 2 },
913 );
914 const appliedIds = new Set(applied.items.map((label) => label.id));
915 return {
916 candidates: labels.items.map((label) => ({
917 name: label.name,
918 color: label.color,
919 description: label.description ?? null,
920 isApplied: appliedIds.has(label.id),
921 })),
922 truncated: labels.next !== null,
923 };
924 },
925 ),
926 setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {
927 const base = yield* repositoryPath("setLabels", input);
928 const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);
929 const selected = labels.items.filter((label) => input.labels.includes(label.name));
930 if (selected.length !== input.labels.length)
931 return yield* failure("setLabels", "One or more requested labels could not be found.");
932 yield* toggleListed(
933 "setLabels",
934 input,
935 { name: "labels", key: "labelIds" },
936 selected.map((label) => label.id),
937 input.applied,
938 );
939 }),
940 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
941 if (!isId(input.threadId))
942 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
943 const path = yield* pullPath("replyToThread", input);
944 yield* read(
945 "replyToThread",
946 input,
947 {
948 method: "POST",
949 path: `${path}/comments/${input.threadId}/replies`,
950 body: { body: input.body },
951 },
952 Written,
953 );
954 }),
955 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
956 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
957 const subject =
958 input.subjectId === undefined
959 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
960 : { kind: "pull_request_comment" as const, id: input.subjectId };
961 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
962 const mine = reactions.items.find(
963 (item) =>
964 item.subject.kind === subject.kind &&
965 item.subject.id === subject.id &&
966 item.emoji.kind === "unicode" &&
967 Json.reactionContent(item.emoji.value) === input.content,
968 )?.viewerReactionId;
969 if (input.reacted === (mine != null)) return;
970 if (input.reacted) {
971 yield* send("setReaction", input, {
972 method: "POST",
973 path,
974 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
975 });
976 return;
977 }
978 if (mine == null) return;
979 if (!isId(mine))
980 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
981 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
982 }),
983 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
984 function* (input) {
985 const comments = yield* readComments("setThreadResolution", input);
986 const root = comments.items.find(
987 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
988 );
989 if (root === undefined || root.version === undefined || !isId(root.id))
990 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
991 if (input.resolved === (root.resolvedAt !== null)) return;
992 const path = yield* pullPath("setThreadResolution", input);
993 yield* read(
994 "setThreadResolution",
995 input,
996 {
997 method: "POST",
998 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
999 body: { expectedVersion: root.version },
1000 },
1001 Written,
1002 );
1003 },
1004 ),
1005 };
1006 return provider;
1007});