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 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: false,
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: false, listCandidates: false },
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;
56
57const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
58 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
59 items.slice(index * size, (index + 1) * size),
60 );
61
62const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
63 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
64
65const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
66 status.merge.permitted !== false &&
67 status.merge.strategies.includes(strategy) &&
68 !(status.merge.blockers ?? []).some((blocker) =>
69 (blocker.blockedStrategies ?? []).includes(strategy),
70 );
71
72const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
73const isId = Schema.is(Id);
74const Principal = Schema.Struct({ handle: TrimmedNonEmptyString });
75const Written = Schema.Struct({ id: Id });
76const Versioned = Schema.Struct({ version: NonNegativeInt });
77const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
78const Status = Schema.Struct({
79 merge: Schema.Struct({
80 conflicts: Schema.Literals(["unknown", "conflicting"]),
81 fastForward: Schema.NullOr(Schema.Boolean),
82 strategies: Schema.Array(Schema.String),
83 permitted: Schema.optional(Schema.Boolean),
84 blockers: Schema.optional(
85 Schema.Array(
86 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
87 ),
88 ),
89 }),
90 checks: Schema.Struct({
91 pending: NonNegativeInt,
92 failing: NonNegativeInt,
93 total: NonNegativeInt,
94 }),
95});
96const FilterOptions = Schema.Struct({
97 actors: Schema.Array(
98 Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString }),
99 ),
100});
101const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
102const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
103const Snapshot = {
104 version: NonNegativeInt,
105 headOid: TrimmedNonEmptyString,
106 comparisonBaseOid: TrimmedNonEmptyString,
107};
108const Changes = Schema.Struct({
109 ...Snapshot,
110 items: Json.GitCafeDiffFiles,
111 next: Schema.NullOr(TrimmedNonEmptyString),
112});
113const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
114const DiffCursor = Schema.Struct({
115 version: NonNegativeInt,
116 headOid: TrimmedNonEmptyString,
117 baseOid: TrimmedNonEmptyString,
118 after: TrimmedNonEmptyString,
119});
120const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
121const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
122const MergeOutcome = Schema.Struct({
123 id: Schema.String,
124 state: Schema.Literals(["accepted", "completed", "failed"]),
125 reason: Schema.optional(Schema.String),
126});
127const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
128const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
129
130type PullRef = ProviderRepositoryRef & { readonly number: number };
131type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
132
133function stackHeadsCurrent(
134 stack: Json.GitCafeStack,
135 input: { readonly number: number; readonly merge: boolean },
136 expected: ReadonlyArray<PullRequestStackHead>,
137): boolean {
138 const members = stack.members.toSorted((a, b) => a.position - b.position);
139 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
140 if (index === -1) return false;
141 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
142 (member) => member.state !== "merged",
143 );
144 return (
145 moved.length === expected.length &&
146 moved.every(
147 (member) =>
148 member.headOid !== undefined &&
149 expected.some(
150 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
151 ),
152 )
153 );
154}
155
156const withDetails = (
157 files: ReadonlyArray<Json.GitCafeDiffFile>,
158 details: ReadonlyArray<Json.GitCafeDiffFile>,
159) => {
160 const byPath = new Map(details.map((file) => [file.path, file]));
161 return files.map((file) => byPath.get(file.path) ?? file);
162};
163
164/** @public Service construction is part of the canonical Effect module API. */
165export const make = Effect.gen(function* () {
166 const api = yield* GitCafeApi.GitCafeApi;
167
168 const failure = (operation: string, detail: string, cause?: unknown) =>
169 new PullRequestProviderError({
170 provider: SourceControlProviderKind.make("gitcafe"),
171 operation,
172 reason: "failed",
173 detail,
174 ...(cause === undefined ? {} : { cause }),
175 });
176
177 const repositoryPath = (
178 operation: string,
179 input: ProviderRepositoryRef,
180 ): Effect.Effect<string, PullRequestProviderError> =>
181 GitCafeHosts.isGitCafeHost(input.host) &&
182 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
183 ? Effect.succeed(`/repos/${input.repository}`)
184 : Effect.fail(
185 failure(
186 operation,
187 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
188 ),
189 );
190
191 const send = (
192 operation: string,
193 input: Pick<ProviderRepositoryRef, "host">,
194 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
195 ) =>
196 api.request({ ...request, host: input.host, operation }).pipe(
197 Effect.mapError(
198 (error) =>
199 new PullRequestProviderError({
200 provider: SourceControlProviderKind.make("gitcafe"),
201 operation,
202 reason: error.reason,
203 detail: error.detail,
204 cause: error,
205 }),
206 ),
207 );
208
209 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
210 operation: string,
211 input: Pick<ProviderRepositoryRef, "host">,
212 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
213 schema: S,
214 ) =>
215 send(operation, input, request).pipe(
216 Effect.flatMap((raw) =>
217 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
218 Effect.mapError((cause) =>
219 failure(operation, "GitCafe returned an unreadable response.", cause),
220 ),
221 ),
222 ),
223 );
224
225 const pullPath = (operation: string, input: PullRef) =>
226 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
227
228 const readPull = (operation: string, input: PullRef) =>
229 pullPath(operation, input).pipe(
230 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
231 );
232
233 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
234 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
235 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
236 const items: Array<S["Type"]["items"][number]> = [];
237 let next: string | null = null;
238 for (let page = 0; page < MAX_PAGES; page++) {
239 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
240 if (next !== null) query.set("after", next);
241 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
242 items.push(...batch.items);
243 const previous: string | null = next;
244 next = batch.next;
245 if (next === null || next === previous || batch.items.length === 0) break;
246 }
247 return { items, next };
248 });
249
250 const readComments = (operation: string, input: PullRef) =>
251 pullPath(operation, input).pipe(
252 Effect.flatMap((path) =>
253 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
254 ),
255 );
256
257 /**
258 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
259 * open layer's pull is read.
260 */
261 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
262 operation: string,
263 input: PullRef,
264 ) {
265 const path = yield* pullPath(operation, input);
266 const { stack } = yield* read(
267 operation,
268 input,
269 { path: `${path}/stack` },
270 Json.GitCafeStackEnvelope,
271 );
272 if (stack === null) return null;
273 const members = yield* Effect.forEach(
274 stack.members,
275 (member) =>
276 member.state === "merged"
277 ? Effect.succeed(member)
278 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
279 Effect.map((pull) =>
280 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
281 ),
282 ),
283 { concurrency: 4 },
284 );
285 return { ...stack, members };
286 });
287
288 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
289 input: PullRef,
290 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
291 paths: ReadonlyArray<string>,
292 ) {
293 if (paths.length === 0) return [];
294 const path = yield* pullPath("getDiff", input);
295 const files = yield* read(
296 "getDiff",
297 input,
298 {
299 method: "POST",
300 path: `${path}/diff-files`,
301 body: { paths, expectedVersion: revision.version },
302 },
303 DiffFiles,
304 );
305 if (
306 files.version !== revision.version ||
307 files.headOid !== revision.headOid ||
308 files.comparisonBaseOid !== revision.baseOid
309 )
310 return yield* failure(
311 "getDiff",
312 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
313 );
314 return files.items;
315 });
316
317 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
318 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
319 ) {
320 const land = input.action === "merge";
321 const operation = land ? "landStackThrough" : "restackStack";
322 if (!land && input.action !== "update-branch")
323 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
324 const stack = yield* readStack(operation, input);
325 if (
326 stack === null ||
327 stack.number !== input.stackNumber ||
328 input.expectedStackHeads === undefined ||
329 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
330 )
331 return yield* failure(
332 operation,
333 "The stack changed since it was read. Refresh it and try again.",
334 );
335 const base = yield* repositoryPath(operation, input);
336 const outcome = yield* read(
337 operation,
338 input,
339 {
340 method: "POST",
341 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
342 body: land
343 ? {
344 expectedRevision: stack.revision,
345 requestId: yield* randomUuidV4,
346 throughPullRequestNumber: input.number,
347 strategy: input.mergeMethod ?? "merge",
348 }
349 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
350 },
351 StackOutcome,
352 );
353 if (FAILED_STACK_STATES.has(outcome.state))
354 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
355 });
356
357 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
358 input: PullRef,
359 version: number,
360 ) {
361 const path = yield* pullPath("getChangeRequest", input);
362 const files: Array<Json.GitCafeDiffFile> = [];
363 let revision: { version: number; headOid: string; baseOid: string } | undefined;
364 let after: string | null = null;
365 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
366 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
367 if (after !== null) query.set("after", after);
368 const batch: typeof Changes.Type = yield* read(
369 "getChangeRequest",
370 input,
371 { path: `${path}/changes?${query}` },
372 Changes,
373 );
374 revision ??= {
375 version: batch.version,
376 headOid: batch.headOid,
377 baseOid: batch.comparisonBaseOid,
378 };
379 files.push(...batch.items);
380 const previous: string | null = after;
381 after = batch.next;
382 if (after === null || after === previous || batch.items.length === 0) break;
383 }
384 const counted =
385 files.some((file) => file.additions !== undefined) ||
386 files.length > LINE_STATS_MAX_FILES ||
387 revision === undefined
388 ? files
389 : (yield* Effect.forEach(
390 chunk(detailablePaths(files), DIFF_FILES_BATCH),
391 (paths) => readDiffFiles(input, revision, paths),
392 { concurrency: 4 },
393 ).pipe(Effect.orElseSucceed(() => [[]]))).flat();
394 return {
395 changedFiles: files.length,
396 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
397 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
398 };
399 });
400
401 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
402 input: Parameters<PullRequestProviderApi["runAction"]>[0],
403 ) {
404 const pull = yield* readPull("merge", input);
405 if (pull.state === "merged") return;
406 if (pull.mergeRoute === "unsupported")
407 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
408 const base = yield* repositoryPath("merge", input);
409 // GitCafe observes the base only for merges it routes to the provider; a native merge is
410 // fenced on the target branch's current commit.
411 const baseOid =
412 pull.mergeRoute === "provider"
413 ? pull.observedBaseOid
414 : (yield* read(
415 "merge",
416 input,
417 {
418 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
419 },
420 BranchCommit,
421 )).oid;
422 if (pull.headOid === null || baseOid == null)
423 return yield* failure(
424 "merge",
425 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
426 );
427 const path = yield* pullPath("merge", input);
428 const outcome = yield* read(
429 "merge",
430 input,
431 {
432 method: "POST",
433 path: `${path}/merge`,
434 body: {
435 requestId: yield* randomUuidV4,
436 expectedVersion: pull.version,
437 headOid: pull.headOid,
438 baseOid,
439 strategy: input.mergeMethod ?? "merge",
440 },
441 },
442 MergeOutcome,
443 );
444 if (outcome.state === "failed")
445 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
446 });
447
448 const provider: PullRequestProviderApi = {
449 kind: SourceControlProviderKind.make("gitcafe"),
450 capabilities: CAPABILITIES,
451 getViewer: (input) =>
452 read(
453 "getViewer",
454 { host: input.host ?? "git.cafe" },
455 { path: "/auth/principal" },
456 Principal,
457 ).pipe(Effect.map((principal) => principal.handle)),
458 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
459 function* (input) {
460 const base = yield* repositoryPath("listChangeRequests", input);
461 const involved = input.involvement === "authored" || input.involvement === "reviewing";
462 let actorId: string | undefined;
463 if (involved) {
464 // A host narrows as far as it can: when the actor list can't be read, the listing comes
465 // back unnarrowed and the page's own involvement filter does the rest. A refused token
466 // or a rate limit still fails, since the service acts on those for the whole host.
467 const options = yield* read(
468 "listChangeRequests",
469 input,
470 { path: `${base}/filter-options` },
471 FilterOptions,
472 ).pipe(
473 Effect.map(Option.some),
474 Effect.catchTags({
475 PullRequestProviderError: (error) =>
476 error.reason === "unauthenticated" || error.reason === "rate-limited"
477 ? Effect.fail(error)
478 : Effect.succeed(Option.none()),
479 }),
480 );
481 if (Option.isSome(options)) {
482 actorId = options.value.actors.find(
483 (actor) => actor.handle.toLowerCase() === input.viewer.toLowerCase(),
484 )?.actorId;
485 if (actorId === undefined) return { items: [], truncated: false, continues: false };
486 }
487 }
488 const limit = Math.max(1, input.limit);
489 const items: Array<Json.GitCafePull> = [];
490 let next: string | null = null;
491 do {
492 const query = new URLSearchParams({
493 limit: String(Math.min(PAGE_SIZE, limit - items.length)),
494 sort: "newest",
495 });
496 if (input.state !== "all") query.set("state", input.state);
497 if (input.query?.trim()) query.set("q", input.query.trim());
498 if (actorId !== undefined)
499 query.set(
500 input.involvement === "reviewing" ? "reviewers" : "authors",
501 encodeActorIds([actorId]),
502 );
503 if (next !== null) query.set("after", next);
504 const page: typeof Json.GitCafePulls.Type = yield* read(
505 "listChangeRequests",
506 input,
507 { path: `${base}/pulls?${query}` },
508 Json.GitCafePulls,
509 );
510 items.push(...page.items);
511 next = page.items.length === 0 ? null : page.next;
512 } while (next !== null && items.length < limit);
513 return {
514 items: items.slice(0, limit).map((pull) => {
515 const item = Json.toChangeRequest(pull, input);
516 return input.involvement === "reviewing" && actorId !== undefined
517 ? {
518 ...item,
519 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
520 }
521 : item;
522 }),
523 truncated: next !== null,
524 continues: false,
525 };
526 },
527 ),
528 getChangeRequestSummary: (input) =>
529 readPull("getChangeRequestSummary", input).pipe(
530 Effect.map((pull) => ({
531 ...Json.toChangeRequest(pull, input),
532 closedAt: pull.closedAt,
533 mergedAt: pull.mergedAt,
534 })),
535 ),
536 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
537 const pull = yield* readPull("getChangeRequest", input);
538 const path = yield* pullPath("getChangeRequest", input);
539 const base = yield* repositoryPath("getChangeRequest", input);
540 const [status, checks, changes] = yield* Effect.all(
541 [
542 read("getChangeRequest", input, { path: `${path}/status` }, Status),
543 pull.headOid === null
544 ? Effect.succeed(null)
545 : readPages(
546 "getChangeRequest",
547 input,
548 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
549 Json.GitCafeChecks,
550 ),
551 pull.headOid === null
552 ? Effect.succeed(null)
553 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
554 ],
555 { concurrency: 3 },
556 );
557 const permissions = Json.toViewerPermissions(pull);
558 return {
559 ...Json.toChangeRequest(pull, input),
560 headSha: pull.headOid,
561 body: pull.description ?? "",
562 ...(pull.sourceRepo === null
563 ? {}
564 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
565 additions: changes?.additions ?? 0,
566 deletions: changes?.deletions ?? 0,
567 changedFiles: changes?.changedFiles ?? 0,
568 closedAt: pull.closedAt,
569 mergedAt: pull.mergedAt,
570 reviewers: Json.toReviewers(pull, input.host),
571 checks: checks === null ? [] : Json.toChecks(checks),
572 ...(status.checks.total === 0
573 ? {}
574 : {
575 checksState:
576 status.checks.failing > 0
577 ? ("failing" as const)
578 : status.checks.pending > 0
579 ? ("pending" as const)
580 : ("passing" as const),
581 }),
582 mergeability:
583 status.merge.conflicts === "conflicting"
584 ? ("conflicting" as const)
585 : ("unknown" as const),
586 baseComparison:
587 status.merge.fastForward === null
588 ? ("unknown" as const)
589 : status.merge.fastForward
590 ? ("up-to-date" as const)
591 : ("behind" as const),
592 mergeCapabilities: {
593 merge: mergeStrategyOpen(status, "merge"),
594 squash: mergeStrategyOpen(status, "squash"),
595 rebase: mergeStrategyOpen(status, "rebase"),
596 },
597 viewerPermissions:
598 status.merge.permitted === false
599 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
600 : permissions,
601 };
602 }),
603 getChangeRequestStack: (input) =>
604 readStack("getChangeRequestStack", input).pipe(
605 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
606 ),
607 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
608 function* (input) {
609 const pull = yield* readPull("getChangeRequestActivity", input);
610 const path = yield* pullPath("getChangeRequestActivity", input);
611 const operation = "getChangeRequestActivity";
612 const [comments, reviews, commits, reactions] = yield* Effect.all(
613 [
614 readComments(operation, input),
615 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
616 pull.headOid === null
617 ? Effect.succeed({ items: [], next: null })
618 : readPages(operation, input, `${path}/commits`, Json.GitCafeCommits),
619 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
620 Effect.orElseSucceed(() => undefined),
621 ),
622 ],
623 { concurrency: 4 },
624 );
625 return Json.toActivity({
626 comments,
627 reviews,
628 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
629 host: input.host,
630 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
631 ...(reactions === undefined ? {} : { reactions }),
632 });
633 },
634 ),
635 getViewerPermissions: (input) =>
636 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
637 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
638 if (input.commit !== undefined)
639 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
640 const cursor =
641 input.cursor === undefined
642 ? null
643 : yield* decodeDiffCursor(input.cursor).pipe(
644 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
645 );
646 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
647 const path = yield* pullPath("getDiff", input);
648 const query = new URLSearchParams({
649 expectedVersion: String(version),
650 limit: String(DIFF_FILES_BATCH),
651 });
652 if (cursor !== null) query.set("after", cursor.after);
653 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
654 if (
655 page.version !== version ||
656 (cursor !== null &&
657 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
658 )
659 return yield* failure(
660 "getDiff",
661 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
662 );
663 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
664 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
665 return {
666 ...Json.toDiff({ items: withDetails(page.items, details) }),
667 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
668 };
669 }),
670 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
671 if (input.stackNumber !== undefined)
672 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
673 switch (input.action) {
674 case "merge":
675 return yield* merge(input);
676 case "ready":
677 case "draft":
678 case "close":
679 case "reopen": {
680 const pull = yield* readPull(input.action, input);
681 const path = yield* pullPath(input.action, input);
682 yield* send(input.action, input, {
683 method: "POST",
684 path: `${path}/${input.action}`,
685 body: { expectedVersion: pull.version },
686 });
687 return;
688 }
689 default:
690 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
691 }
692 }),
693 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
694 function* (input) {
695 const pull = yield* readPull("updateChangeRequest", input);
696 const path = yield* pullPath("updateChangeRequest", input);
697 yield* read(
698 "updateChangeRequest",
699 input,
700 {
701 method: "PATCH",
702 path,
703 body: {
704 expectedVersion: pull.version,
705 ...(input.title === undefined ? {} : { title: input.title }),
706 ...(input.body === undefined ? {} : { description: input.body }),
707 },
708 },
709 Versioned,
710 );
711 },
712 ),
713 comment: (input) =>
714 pullPath("comment", input).pipe(
715 Effect.flatMap((path) =>
716 read(
717 "comment",
718 input,
719 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
720 Written,
721 ),
722 ),
723 Effect.asVoid,
724 ),
725 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
726 if (!isId(input.commentId))
727 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
728 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
729 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
730 yield* read(
731 "updateComment",
732 input,
733 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
734 Written,
735 );
736 }),
737 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
738 if (input.comments.length > 0)
739 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
740 const pull = yield* readPull("submitReview", input);
741 if (pull.headOid === null)
742 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
743 const path = yield* pullPath("submitReview", input);
744 yield* read(
745 "submitReview",
746 input,
747 {
748 method: "POST",
749 path: `${path}/reviews`,
750 body: {
751 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
752 ...(input.body.length === 0 ? {} : { body: input.body }),
753 commitOid: pull.headOid,
754 expectedVersion: pull.version,
755 requestId: yield* randomUuidV4,
756 },
757 },
758 Written,
759 );
760 }),
761 listReviewerCandidates: () =>
762 Effect.fail(
763 failure("listReviewerCandidates", "GitCafe reviewer requests are not supported."),
764 ),
765 setReviewerRequest: () =>
766 Effect.fail(failure("setReviewerRequest", "GitCafe reviewer requests are not supported.")),
767 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
768 if (!isId(input.threadId))
769 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
770 const path = yield* pullPath("replyToThread", input);
771 yield* read(
772 "replyToThread",
773 input,
774 {
775 method: "POST",
776 path: `${path}/comments/${input.threadId}/replies`,
777 body: { body: input.body },
778 },
779 Written,
780 );
781 }),
782 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
783 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
784 const subject =
785 input.subjectId === undefined
786 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
787 : { kind: "pull_request_comment" as const, id: input.subjectId };
788 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
789 const mine = reactions.items.find(
790 (item) =>
791 item.subject.kind === subject.kind &&
792 item.subject.id === subject.id &&
793 item.emoji.kind === "unicode" &&
794 Json.reactionContent(item.emoji.value) === input.content,
795 )?.viewerReactionId;
796 if (input.reacted === (mine != null)) return;
797 if (input.reacted) {
798 yield* send("setReaction", input, {
799 method: "POST",
800 path,
801 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
802 });
803 return;
804 }
805 if (mine == null) return;
806 if (!isId(mine))
807 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
808 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
809 }),
810 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
811 function* (input) {
812 const comments = yield* readComments("setThreadResolution", input);
813 const root = comments.items.find(
814 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
815 );
816 if (root === undefined || root.version === undefined || !isId(root.id))
817 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
818 if (input.resolved === (root.resolvedAt !== null)) return;
819 const path = yield* pullPath("setThreadResolution", input);
820 yield* read(
821 "setThreadResolution",
822 input,
823 {
824 method: "POST",
825 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
826 body: { expectedVersion: root.version },
827 },
828 Written,
829 );
830 },
831 ),
832 };
833 return provider;
834});