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

GitLabIssueTracker.ts

810 lines27.8 KB

1/**
2 * GitLab's issue tracker over `glab api`. GitLab pages by offset, so every cursor is a page
3 * number. Notes, label events, linked merge requests and awards are separate endpoints, joined
4 * into the detail.
5 */
6import * as Effect from "effect/Effect";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import {
10 IssueTrackerKind,
11 type IssueCapabilities,
12 type IssueEvent,
13 type IssueViewerPermissions,
14} from "@t3tools/contracts";
15import {
16 IssueTrackerError,
17 type IssueInvolvementFilter,
18 type IssueTrackerApi,
19} from "@t3tools/source-control-core/server/IssueTracker";
20​
21import * as GitLabCli from "./GitLabCli.ts";
22import {
23 decodeCreatedIssueJson,
24 decodeUserIdsJson,
25 decodeIssueDetailListJson,
26 decodeIssueListJson,
27 decodeIssueNotesJson,
28 withMentionReference,
29 decodeLabelEventsJson,
30 decodeLinkedMergeRequestsJson,
31 decodeProjectLabelsJson,
32 decodeProjectMembersJson,
33 decodeTemplateEntriesJson,
34 decodeTemplateJson,
35 ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
36 ISSUE_STATES,
37 PAGE_SIZE,
38 type GitLabTemplateEntry,
39} from "./gitLabIssueJson.ts";
40import {
41 awardReactions,
42 decodeAwardEmojiJson,
43 decodeAwardListJson,
44 decodeOwnAwardIdJson,
45 decodeViewerJson,
46 gitLabAwardName,
47} from "./gitLabMergeRequestJson.ts";
48​
49const KIND = IssueTrackerKind.make("gitlab");
50/** How many pages of system notes the timeline reads before giving up on the rest. */
51const MAX_ACTIVITY_PAGES = 20;
52​
53const CAPABILITIES: IssueCapabilities = {
54 create: true,
55 edit: true,
56 comment: true,
57 labels: true,
58 assignees: true,
59 reactions: true,
60 templates: true,
61 linkedPullRequests: true,
62 events: true,
63 search: true,
64};
65​
66/**
67 * Everything granted. GitLab's REST API reports the viewer's role on the project but never whether
68 * they opened this issue, and an issue's author may close, reopen and edit it whatever their role.
69 * Withholding those controls from the one person entitled to them is the worse mistake, so they
70 * are offered and GitLab explains any refusal itself.
71 */
72const VIEWER_PERMISSIONS: IssueViewerPermissions = {
73 setState: true,
74 comment: true,
75 edit: true,
76 labels: true,
77 assignees: true,
78};
79​
80/** How many of a scope's templates are read in full; each one is a request of its own. */
81const TEMPLATE_LIMIT = 20;
82​
83const encodeBody = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
84​
85/** The REST API addresses a project by its URL-encoded full path. */
86function projectPath(scope: string): string {
87 return encodeURIComponent(scope.trim());
89​
90/** An issue key is its iid; anything else names no GitLab issue. */
91function parseNumber(key: string): number | null {
92 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
94​
95/** A page cursor this tracker handed out, or null for anything it could not have issued. */
96function parsePage(cursor: string | undefined): number | null {
97 if (cursor === undefined) return 1;
98 return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
100​
101/**
102 * A comments cursor: the next REST page of notes and, after a colon, where GraphQL's awards for
103 * that page start. The two page alike, so a page of comments is joined with its own awards.
104 */
105function parseCommentsCursor(
106 cursor: string,
107): { readonly page: number; readonly awards: string | null } | null {
108 const match = /^([1-9]\d{0,6})(?::(.{1,512}))?$/.exec(cursor);
109 return match === null ? null : { page: Number(match[1]), awards: match[2] ?? null };
111​
112function commentsCursor(notesNext: string | null, awardsNext: string | null): string | null {
113 if (notesNext === null) return null;
114 return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`;
116​
117/**
118 * `glab api --include` output split into the body and GitLab's next page. GitLab can return a
119 * short page when it hides notes the viewer may not see, so only `X-Next-Page` says whether more
120 * exists; without headers a full page is taken as the sign.
121 */
122function splitPagedResponse(raw: string): {
123 readonly body: string;
124 readonly nextPage: number | null | undefined;
125} {
126 if (!raw.startsWith("HTTP/")) return { body: raw, nextPage: undefined };
127 const end = /\r?\n\r?\n/.exec(raw);
128 const headers = end === null ? raw : raw.slice(0, end.index);
129 const body = end === null ? "" : raw.slice(end.index + end[0].length);
130 const next = /^x-next-page:[ \t]*([1-9]\d{0,6})?[ \t]*\r?$/im.exec(headers);
131 return {
132 body,
133 nextPage: next === null ? undefined : next[1] === undefined ? null : Number(next[1]),
134 };
136​
137function query(params: ReadonlyArray<readonly [string, string]>): string {
138 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
140​
141function involvementParams(
142 input: IssueInvolvementFilter & { readonly assignee?: string | undefined },
143): ReadonlyArray<readonly [string, string]> {
144 switch (input.involvement) {
145 case "authored":
146 return [["author_username", input.viewer]];
147 case "assigned":
148 // A named assignee takes the one assignee parameter GitLab reads; `listIssues` keeps the
149 // viewer by dropping rows.
150 return input.assignee === undefined ? [["assignee_username", input.viewer]] : [];
151 // GitLab's `my_reaction_emoji` and `iteration` filters aside, nothing narrows to mentions, so
152 // the listing stays as wide as `all` rather than guessing.
153 case "mentioned":
154 case "all":
155 return [];
156 }
158​
159function reasonFor(error: GitLabCli.GitLabCliError): IssueTrackerError["reason"] {
160 switch (error._tag) {
161 case "GitLabCliUnavailableError":
162 return "missing-tool";
163 case "GitLabCliAuthenticationError":
164 return "unauthenticated";
165 case "GitLabCliRateLimitError":
166 return "rate-limited";
167 default:
168 return "failed";
169 }
171​
172export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> = Effect.gen(
173 function* () {
174 const gitlab = yield* GitLabCli.GitLabCli;
175​
176 const fail = (operation: string) => (error: GitLabCli.GitLabCliError) =>
177 new IssueTrackerError({
178 tracker: KIND,
179 operation,
180 reason: reasonFor(error),
181 detail: error.detail,
182 cause: error,
183 });
184​
185 const unreadable = (operation: string, cause: unknown) =>
186 new IssueTrackerError({
187 tracker: KIND,
188 operation,
189 reason: "failed",
190 detail: `GitLab returned an unreadable ${operation} response.`,
191 cause,
192 });
193​
194 const notFound = (operation: string) =>
195 new IssueTrackerError({
196 tracker: KIND,
197 operation,
198 reason: "not-found",
199 detail: "GitLab could not find the requested issue.",
200 });
201​
202 const refused = (operation: string, detail: string) =>
203 new IssueTrackerError({ tracker: KIND, operation, reason: "failed", detail });
204​
205 const api = (input: {
206 readonly cwd: string;
207 readonly host: string;
208 readonly operation: string;
209 readonly path: string;
210 readonly method?: string;
211 readonly body?: unknown;
212 readonly includeHeaders?: boolean;
213 }) =>
214 gitlab
215 .execute({
216 cwd: input.cwd,
217 host: input.host,
218 args: [
219 "api",
220 input.path,
221 ...(input.includeHeaders === true ? ["--include"] : []),
222 ...(input.method === undefined ? [] : ["--method", input.method]),
223 // A JSON body from stdin: argv is visible in process listings, and `glab api --input`
224 // sends no Content-Type of its own, which GitLab answers with HTTP 415.
225 ...(input.body === undefined
226 ? []
227 : ["--input", "-", "--header", "Content-Type: application/json"]),
228 ],
229 ...(input.body === undefined ? {} : { stdin: encodeBody(input.body) }),
230 })
231 .pipe(
232 Effect.map((result) => result.stdout.trim()),
233 Effect.mapError(fail(input.operation)),
234 );
235​
236 const read = <A>(input: {
237 readonly cwd: string;
238 readonly host: string;
239 readonly operation: string;
240 readonly path: string;
241 readonly method?: string;
242 readonly body?: unknown;
243 readonly includeHeaders?: boolean;
244 readonly decode: (raw: string) => Result.Result<A, unknown>;
245 }): Effect.Effect<A, IssueTrackerError> =>
246 api(input).pipe(
247 Effect.flatMap((raw) => {
248 const decoded = input.decode(raw);
249 return Result.isSuccess(decoded)
250 ? Effect.succeed(decoded.success)
251 : Effect.fail(unreadable(input.operation, decoded.failure));
252 }),
253 );
254​
255 const write = (input: {
256 readonly cwd: string;
257 readonly host: string;
258 readonly operation: string;
259 readonly path: string;
260 readonly method: string;
261 readonly body?: unknown;
262 }) => api(input).pipe(Effect.asVoid);
263​
264 /** The signed-in account; an answer naming nobody is a failure, since every comparison needs a login. */
265 const viewer = (input: {
266 readonly cwd: string;
267 readonly host: string;
268 readonly operation: string;
269 }): Effect.Effect<string, IssueTrackerError> =>
270 read({
271 cwd: input.cwd,
272 host: input.host,
273 operation: input.operation,
274 path: "user",
275 decode: decodeViewerJson,
276 }).pipe(
277 Effect.filterOrFail(
278 (login) => login !== null,
279 () => refused(input.operation, "GitLab returned no username for the signed-in account."),
280 ),
281 );
282​
283 /** The issue as REST addresses it, or a not-found for a key that names no iid. */
284 const issuePath = (
285 input: { readonly scope: string; readonly key: string },
286 operation: string,
287 ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
288 const number = parseNumber(input.key);
289 return number === null
290 ? Effect.fail(notFound(operation))
291 : Effect.succeed({ number, path: `projects/${projectPath(input.scope)}/issues/${number}` });
292 };
293​
294 /**
295 * GitLab writes assignees by numeric id, which is what the candidates carry as `id`. An issue
296 * names the people it already has by username, so a kept assignee is looked up.
297 */
298 const assigneeIds = (
299 input: { readonly cwd: string; readonly host: string },
300 operation: string,
301 assignees: ReadonlyArray<string>,
302 ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> =>
303 Effect.forEach(assignees, (assignee) =>
304 /^[1-9]\d*$/.test(assignee)
305 ? Effect.succeed(Number(assignee))
306 : read({
307 cwd: input.cwd,
308 host: input.host,
309 operation,
310 path: `users?${query([["username", assignee]])}`,
311 decode: decodeUserIdsJson,
312 }).pipe(
313 Effect.flatMap(([id]) =>
314 id === undefined
315 ? Effect.fail(refused(operation, `GitLab has no user named ${assignee}.`))
316 : Effect.succeed(id),
317 ),
318 ),
319 );
320​
321 const paged = (path: string, page: number) =>
322 `${path}?${query([
323 ["per_page", String(PAGE_SIZE)],
324 ["page", String(page)],
325 ])}`;
326​
327 const notesPage = (input: {
328 readonly cwd: string;
329 readonly host: string;
330 readonly path: string;
331 readonly page: number;
332 readonly operation: string;
333 readonly onlyActivity?: boolean;
334 }) =>
335 read({
336 cwd: input.cwd,
337 host: input.host,
338 operation: input.operation,
339 path: `${input.path}/notes?${query([
340 ["per_page", String(PAGE_SIZE)],
341 ["page", String(input.page)],
342 ["order_by", "created_at"],
343 ["sort", "asc"],
344 ...(input.onlyActivity === true ? [["activity_filter", "only_activity"] as const] : []),
345 ])}`,
346 includeHeaders: true,
347 decode: (raw) => {
348 const { body, nextPage } = splitPagedResponse(raw);
349 return Result.map(decodeIssueNotesJson(body), (notes) => {
350 const next =
351 nextPage === undefined
352 ? notes.rawCount < PAGE_SIZE
353 ? null
354 : input.page + 1
355 : nextPage;
356 return { ...notes, nextCursor: next === null ? null : String(next) };
357 });
358 },
359 });
360​
361 /** Every system note, wherever it falls among the comments, for the issue's timeline. */
362 const activity = Effect.fn("GitLabIssueTracker.activity")(function* (input: {
363 readonly cwd: string;
364 readonly host: string;
365 readonly path: string;
366 }) {
367 const events: Array<IssueEvent> = [];
368 let page = 1;
369 for (let count = 0; count < MAX_ACTIVITY_PAGES; count++) {
370 const notes = yield* notesPage({
371 ...input,
372 page,
373 operation: "getIssue",
374 onlyActivity: true,
375 });
376 events.push(...notes.events);
377 if (notes.nextCursor === null) break;
378 page = Number(notes.nextCursor);
379 }
380 return events;
381 });
382​
383 const awards = (input: {
384 readonly cwd: string;
385 readonly host: string;
386 readonly scope: string;
387 readonly number: number;
388 readonly operation: string;
389 readonly cursor?: string | undefined;
390 }) =>
391 read({
392 cwd: input.cwd,
393 host: input.host,
394 operation: input.operation,
395 path: "graphql",
396 method: "POST",
397 body: {
398 query: ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
399 variables: {
400 fullPath: input.scope.trim(),
401 iid: String(input.number),
402 cursor: input.cursor ?? null,
403 },
404 },
405 decode: decodeAwardEmojiJson,
406 }).pipe(
407 // GitLab before 16.1 has no `Note.awardEmoji`; comments then load without reactions.
408 Effect.catchIf(
409 (error) => error.reason === "failed",
410 () => Effect.succeed(null),
411 ),
412 );
413​
414 const linked = (input: {
415 readonly cwd: string;
416 readonly host: string;
417 readonly path: string;
418 readonly endpoint: "closed_by" | "related_merge_requests";
419 }) =>
420 read({
421 cwd: input.cwd,
422 host: input.host,
423 operation: "getIssue",
424 path: paged(`${input.path}/${input.endpoint}`, 1),
425 decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
426 });
427​
428 const template =
429 (input: { readonly cwd: string; readonly host: string; readonly scope: string }) =>
430 (entry: GitLabTemplateEntry) =>
431 read({
432 cwd: input.cwd,
433 host: input.host,
434 operation: "listTemplates",
435 path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
436 decode: (raw) => decodeTemplateJson(entry, raw),
437 });
438​
439 return {
440 kind: KIND,
441 capabilities: CAPABILITIES,
442​
443 getViewer: (input) => viewer({ cwd: input.cwd, host: input.host, operation: "getViewer" }),
444​
445 listIssues: Effect.fn("GitLabIssueTracker.listIssues")(function* (input) {
446 const page = parsePage(input.cursor);
447 if (page === null) {
448 return yield* refused("listIssues", "The cursor was not one GitLab handed out.");
449 }
450 const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
451 const text = input.query?.trim() ?? "";
452 const alsoAssignedTo =
453 input.involvement === "assigned" && input.assignee !== undefined
454 ? input.viewer.toLowerCase()
455 : null;
456 return yield* read({
457 cwd: input.cwd,
458 host: input.host,
459 operation: "listIssues",
460 path: `projects/${projectPath(input.scope)}/issues?${query([
461 ["state", input.state === "open" ? "opened" : input.state],
462 ...involvementParams(input),
463 // GitLab's own `search` matches title and description, URL-encoded like every other
464 // value here, so no text in it can become a parameter of its own.
465 ...(text.length === 0 ? [] : [["search", text] as const]),
466 ...(input.labels === undefined || input.labels.length === 0
467 ? []
468 : [["labels", input.labels.join(",")] as const]),
469 ...(input.assignee === undefined
470 ? []
471 : [["assignee_username", input.assignee] as const]),
472 ["order_by", input.sort === "created" ? "created_at" : "updated_at"],
473 ["sort", "desc"],
474 ["with_labels_details", "true"],
475 ["per_page", String(perPage)],
476 ["page", String(page)],
477 ])}`,
478 decode: decodeIssueListJson,
479 }).pipe(
480 Effect.map((list) => ({
481 items:
482 alsoAssignedTo === null
483 ? list.items
484 : list.items.filter((issue) =>
485 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo),
486 ),
487 nextCursor: list.rawCount < perPage ? null : String(page + 1),
488 })),
489 );
490 }),
491​
492 getIssue: (input) =>
493 issuePath(input, "getIssue").pipe(
494 Effect.flatMap(({ number, path }) =>
495 Effect.all(
496 [
497 read({
498 cwd: input.cwd,
499 host: input.host,
500 operation: "getIssue",
501 path: `projects/${projectPath(input.scope)}/issues?${query([
502 ["iids[]", String(number)],
503 ["with_labels_details", "true"],
504 ["per_page", "1"],
505 ])}`,
506 decode: decodeIssueDetailListJson,
507 }).pipe(
508 Effect.filterOrFail(
509 (issue) => issue !== null,
510 () => notFound("getIssue"),
511 ),
512 ),
513 viewer({ cwd: input.cwd, host: input.host, operation: "getIssue" }),
514 notesPage({
515 cwd: input.cwd,
516 host: input.host,
517 path,
518 page: 1,
519 operation: "getIssue",
520 }),
521 activity({ cwd: input.cwd, host: input.host, path }),
522 read({
523 cwd: input.cwd,
524 host: input.host,
525 operation: "getIssue",
526 path: paged(`${path}/resource_label_events`, 1),
527 decode: decodeLabelEventsJson,
528 }),
529 linked({ cwd: input.cwd, host: input.host, path, endpoint: "closed_by" }),
530 linked({
531 cwd: input.cwd,
532 host: input.host,
533 path,
534 endpoint: "related_merge_requests",
535 }),
536 awards({
537 cwd: input.cwd,
538 host: input.host,
539 scope: input.scope,
540 number,
541 operation: "getIssue",
542 }),
543 read({
544 cwd: input.cwd,
545 host: input.host,
546 operation: "getIssue",
547 path: paged(`${path}/award_emoji`, 1),
548 decode: decodeAwardListJson,
549 }),
550 ],
551 { concurrency: 4 },
552 ),
553 ),
554 Effect.map(
555 ([
556 issue,
557 viewerLogin,
558 notes,
559 systemEvents,
560 labelEvents,
561 closing,
562 related,
563 awardPage,
564 issueAwards,
565 ]) => {
566 const closingKeys = new Set(
567 closing.map((link) => `${link.repository}!${link.number}`),
568 );
569 return {
570 ...issue,
571 viewer: viewerLogin,
572 viewerPermissions: VIEWER_PERMISSIONS,
573 states: ISSUE_STATES,
574 reactions: awardReactions(issueAwards, viewerLogin),
575 comments: notes.comments.map((comment) => ({
576 ...comment,
577 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
578 })),
579 commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
580 events: [
581 ...systemEvents.map((event) =>
582 withMentionReference(event, issue.url, input.scope),
583 ),
584 ...labelEvents,
585 ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)),
586 // A merge request that closes the issue outranks its sighting as a mere mention.
587 linkedPullRequests: [
588 ...closing,
589 ...related.filter(
590 (link) => !closingKeys.has(`${link.repository}!${link.number}`),
591 ),
592 ],
593 };
594 },
595 ),
596 ),
597​
598 getComments: (input) => {
599 const cursor = parseCommentsCursor(input.cursor);
600 return cursor === null
601 ? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
602 : issuePath(input, "getComments").pipe(
603 Effect.flatMap(({ number, path }) =>
604 Effect.all(
605 [
606 notesPage({
607 cwd: input.cwd,
608 host: input.host,
609 path,
610 page: cursor.page,
611 operation: "getComments",
612 }),
613 // Without its awards cursor a later page's awards cannot be found.
614 cursor.awards === null && cursor.page > 1
615 ? Effect.succeed(null)
616 : awards({
617 cwd: input.cwd,
618 host: input.host,
619 scope: input.scope,
620 number,
621 operation: "getComments",
622 cursor: cursor.awards ?? undefined,
623 }),
624 ],
625 { concurrency: 2 },
626 ),
627 ),
628 Effect.map(([notes, awardPage]) => ({
629 comments: notes.comments.map((comment) => ({
630 ...comment,
631 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
632 })),
633 nextCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
634 })),
635 );
636 },
637​
638 create: (input) =>
639 assigneeIds(input, "create", input.assignees).pipe(
640 Effect.flatMap((assignee_ids) =>
641 read({
642 cwd: input.cwd,
643 host: input.host,
644 operation: "create",
645 path: `projects/${projectPath(input.scope)}/issues`,
646 method: "POST",
647 body: {
648 title: input.title,
649 description: input.body,
650 labels: input.labels.join(","),
651 assignee_ids,
652 },
653 decode: decodeCreatedIssueJson,
654 }),
655 ),
656 Effect.map((issue) => ({
657 key: String(issue.number),
658 displayKey: `#${issue.number}`,
659 url: issue.url,
660 })),
661 ),
662​
663 comment: (input) =>
664 issuePath(input, "comment").pipe(
665 Effect.flatMap(({ path }) =>
666 write({
667 cwd: input.cwd,
668 host: input.host,
669 operation: "comment",
670 path: `${path}/notes`,
671 method: "POST",
672 body: { body: input.body },
673 }),
674 ),
675 ),
676​
677 update: (input) =>
678 Effect.all([
679 issuePath(input, "update"),
680 input.assignees === undefined
681 ? Effect.void
682 : assigneeIds(input, "update", input.assignees),
683 ]).pipe(
684 Effect.flatMap(([{ path }, assignee_ids]) =>
685 write({
686 cwd: input.cwd,
687 host: input.host,
688 operation: "update",
689 path,
690 method: "PUT",
691 body: {
692 ...(input.title === undefined ? {} : { title: input.title }),
693 ...(input.body === undefined ? {} : { description: input.body }),
694 ...(input.labels === undefined ? {} : { labels: input.labels.join(",") }),
695 ...(assignee_ids === undefined ? {} : { assignee_ids }),
696 },
697 }),
698 ),
699 ),
700​
701 setState: (input) => {
702 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
703 if (wanted === undefined) {
704 return Effect.fail(refused("setState", `A GitLab issue has no "${input.state}" state.`));
705 }
706 return issuePath(input, "setState").pipe(
707 Effect.flatMap(({ path }) =>
708 write({
709 cwd: input.cwd,
710 host: input.host,
711 operation: "setState",
712 path,
713 method: "PUT",
714 body: { state_event: wanted.category === "closed" ? "close" : "reopen" },
715 }),
716 ),
717 );
718 },
719​
720 setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
721 const { path } = yield* issuePath(input, "setReaction");
722 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
723 return yield* refused("setReaction", "The comment id names no GitLab note.");
724 }
725 const subject =
726 input.subjectId === undefined
727 ? `${path}/award_emoji`
728 : `${path}/notes/${input.subjectId}/award_emoji`;
729 if (input.reacted) {
730 return yield* write({
731 cwd: input.cwd,
732 host: input.host,
733 operation: "setReaction",
734 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
735 method: "POST",
736 });
737 }
738 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
739 // award of that name is looked up first. Nothing to delete is success.
740 const login = yield* viewer({
741 cwd: input.cwd,
742 host: input.host,
743 operation: "setReaction",
744 });
745 for (let page = 1; ; page++) {
746 const own = yield* read({
747 cwd: input.cwd,
748 host: input.host,
749 operation: "setReaction",
750 path: paged(subject, page),
751 decode: (raw) => decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
752 });
753 if (own.id !== null) {
754 return yield* write({
755 cwd: input.cwd,
756 host: input.host,
757 operation: "setReaction",
758 path: `${subject}/${own.id}`,
759 method: "DELETE",
760 });
761 }
762 // An empty raw page establishes exhaustion even when the host caps page size.
763 if (own.empty) return;
764 }
765 }),
766​
767 listTemplates: (input) =>
768 read({
769 cwd: input.cwd,
770 host: input.host,
771 operation: "listTemplates",
772 path: `projects/${projectPath(input.scope)}/templates/issues`,
773 decode: decodeTemplateEntriesJson,
774 }).pipe(
775 Effect.flatMap((entries) =>
776 Effect.forEach(entries.slice(0, TEMPLATE_LIMIT), template(input), { concurrency: 4 }),
777 ),
778 // GitLab has no switch that forbids an issue filed from nothing.
779 Effect.map((templates) => ({ templates, blankIssuesEnabled: true })),
780 ),
781​
782 listCandidates: (input) =>
783 Effect.all(
784 [
785 read({
786 cwd: input.cwd,
787 host: input.host,
788 operation: "listCandidates",
789 path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
790 decode: decodeProjectLabelsJson,
791 }),
792 read({
793 cwd: input.cwd,
794 host: input.host,
795 operation: "listCandidates",
796 path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
797 decode: decodeProjectMembersJson,
798 }),
799 ],
800 { concurrency: 2 },
801 ).pipe(
802 Effect.map(([labels, assignees]) => ({
803 labels,
804 assignees,
805 truncated: labels.length >= PAGE_SIZE || assignees.length >= PAGE_SIZE,
806 })),
807 ),
808 };
809 },
810);