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

GitCafePullRequestProvider.ts

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