Open History to see the last commit
1import * as Effect from "effect/Effect";
2import type {
3 PullRequestCapabilities,
4 PullRequestReaction,
5 PullRequestViewerPermissions,
6} from "@t3tools/contracts";
7
8import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
9import {
10 PullRequestProviderError,
11 type PullRequestProviderFailure,
12 type ProviderChangeRequestActivity,
13 type ProviderChangeRequestDetail,
14 type PullRequestProviderApi,
15} from "./PullRequestProvider.ts";
16
17const CAPABILITIES: PullRequestCapabilities = {
18 diff: true,
19 comment: true,
20 actions: [
21 "merge",
22 "ready",
23 "draft",
24 "close",
25 "reopen",
26 "update-branch",
27 "enable-auto-merge",
28 "disable-auto-merge",
29 ],
30 // GitLab offers all three, though a project settles on one; `mergeCapabilities` narrows it.
31 mergeMethods: ["merge", "squash", "rebase"],
32 // Rebase alone: GitLab moves a stale branch onto its target by replaying it, and has nothing
33 // that merges the target back in the way GitHub's update button can. Declaring only what it
34 // does is what lets a request to merge the target in be refused instead of quietly rebasing.
35 updateMethods: ["rebase"],
36 search: true,
37 reactions: true,
38 review: {
39 inlineComment: true,
40 reply: true,
41 resolve: true,
42 // No "changes requested": GitLab has approval and unresolved discussions, and nothing that
43 // says a merge request has been reviewed and rejected.
44 verdicts: ["comment", "approve"],
45 },
46 reviewers: { request: true, listCandidates: true },
47 edit: { changeRequest: true, comment: true },
48};
49
50/**
51 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
52 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
53 * and someone it will not let land this change has no business rewriting its branch either.
54 */
55const MERGE_ACTIONS: ReadonlySet<string> = new Set([
56 "merge",
57 "update-branch",
58 "enable-auto-merge",
59 "disable-auto-merge",
60]);
61
62/**
63 * What the signed-in account may do here. GitLab answers exactly one of these questions per
64 * viewer, on the merge request itself: `user.can_merge`, which is why merging is the only thing
65 * narrowed.
66 *
67 * The rest stay granted. GitLab's REST API reports the viewer's role on the project but never
68 * whether they opened this merge request — and its author may close it, reopen it and move it in
69 * and out of draft whatever their role, just as the author of a note may resolve the discussion
70 * it started. Withholding those controls from the one person entitled to them is the worse of the
71 * two mistakes, so they are offered and GitLab explains any refusal itself.
72 *
73 * Asking for a review is granted for the same reason: GitLab takes a reviewer set from the author
74 * and from anyone with the Developer role, and states neither of those two facts here.
75 */
76export function gitLabViewerPermissions(input: {
77 readonly viewerCanMerge: boolean;
78}): PullRequestViewerPermissions {
79 return {
80 // Arming the merge and taking the arming back are the merge, deferred, so they answer to
81 // the same `can_merge` the merge itself does.
82 actions: CAPABILITIES.actions.filter(
83 (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
84 ),
85 comment: true,
86 resolve: true,
87 verdicts: CAPABILITIES.review.verdicts,
88 requestReviewers: true,
89 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
90 };
91}
92
93/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
94export function gitLabProviderFailure(
95 error: GitLabPullRequestCli.GitLabPullRequestCliError,
96): PullRequestProviderFailure {
97 if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };
98 if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };
99 if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };
100 return { reason: "failed" };
101}
102
103export const make = Effect.gen(function* () {
104 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
105
106 const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
107 new PullRequestProviderError({
108 provider: "gitlab",
109 operation,
110 ...gitLabProviderFailure(error),
111 detail: error.detail,
112 cause: error,
113 });
114
115 const provider: PullRequestProviderApi = {
116 kind: "gitlab",
117 capabilities: CAPABILITIES,
118
119 getViewer: (input) =>
120 cli.getViewerUsername({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
121
122 listChangeRequests: (input) =>
123 cli
124 .listMergeRequests({
125 cwd: input.cwd,
126 repository: input.repository,
127 state: input.state,
128 involvement: input.involvement,
129 viewer: input.viewer,
130 limit: input.limit,
131 query: input.query,
132 cursor: input.cursor,
133 })
134 .pipe(
135 Effect.mapError(fail("listChangeRequests")),
136 // GitLab is asked for its merge requests by update, newest first, whether or not it is
137 // being carried on from — so every page it answers is one a cursor can continue.
138 Effect.map((batch) => ({ ...batch, continues: true })),
139 ),
140
141 getChangeRequest: (input) =>
142 Effect.all(
143 [
144 cli.getMergeRequestDetail(input),
145 cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
146 ],
147 { concurrency: 2 },
148 ).pipe(
149 Effect.mapError(fail("getChangeRequest")),
150 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
151 ...mergeRequest,
152 mergeCapabilities,
153 viewerPermissions: gitLabViewerPermissions(mergeRequest),
154 // A GitLab too old to count the divergence says nothing here rather than "up to
155 // date": the banner is worth missing, and a wrong all-clear is not worth showing.
156 baseComparison:
157 mergeRequest.divergedCommits === undefined
158 ? "unknown"
159 : mergeRequest.divergedCommits > 0
160 ? "behind"
161 : "up-to-date",
162 ...(mergeRequest.divergedCommits === undefined
163 ? {}
164 : { behindBy: mergeRequest.divergedCommits }),
165 })),
166 ),
167
168 getChangeRequestActivity: (input) =>
169 Effect.all(
170 [
171 cli
172 .listNotes(input)
173 .pipe(Effect.orElseSucceed(() => ({ comments: [], truncated: true }))),
174 cli.listCommits(input).pipe(Effect.orElseSucceed(() => [])),
175 cli
176 .listDiscussions(input)
177 .pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
178 // The notes endpoint carries no award of any kind, so they are read alongside it. A
179 // failed read costs the conversation its reactions rather than its words.
180 cli.listReactions(input).pipe(
181 Effect.orElseSucceed(() => ({
182 reactions: [] as ReadonlyArray<PullRequestReaction>,
183 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
184 })),
185 ),
186 ],
187 { concurrency: 4 },
188 ).pipe(
189 Effect.mapError(fail("getChangeRequestActivity")),
190 Effect.map(([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
191 reactions: awards.reactions,
192 comments: notes.comments.map((comment) => ({
193 ...comment,
194 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
195 })),
196 // GitLab reports no count of its own, so the walk's own total is the host's: the
197 // notes endpoint carries every comment on the merge request, including the ones
198 // written under a discussion, and it is read until GitLab runs out.
199 commentCount: notes.comments.length,
200 commentsTruncated: notes.truncated || discussions.truncated,
201 reviewThreads: discussions.threads.map((thread) => ({
202 ...thread,
203 comments: thread.comments.map((comment) => ({
204 ...comment,
205 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
206 })),
207 })),
208 commits,
209 })),
210 ),
211
212 // The same read the detail takes it from, on its own: `user.can_merge` lives on the merge
213 // request, so there is no cheaper thing to ask GitLab.
214 getViewerPermissions: (input) =>
215 cli
216 .getMergeRequestDetail(input)
217 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
218
219 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
220
221 // Users only: GitLab requests a review of a person, and the groups that can stand in for one
222 // appear in approval rules rather than in a merge request's reviewers.
223 listReviewerCandidates: (input) =>
224 cli
225 .listReviewerCandidates({
226 cwd: input.cwd,
227 repository: input.repository,
228 number: input.number,
229 })
230 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
231
232 setReviewerRequest: (input) =>
233 cli
234 .setReviewerRequest({
235 cwd: input.cwd,
236 repository: input.repository,
237 number: input.number,
238 reviewers: input.reviewers,
239 requested: input.requested,
240 })
241 .pipe(Effect.mapError(fail("setReviewerRequest"))),
242
243 runAction: (input) =>
244 cli
245 .runMergeRequestAction({
246 cwd: input.cwd,
247 repository: input.repository,
248 number: input.number,
249 action: input.action,
250 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
251 })
252 .pipe(Effect.mapError(fail("runAction"))),
253
254 updateChangeRequest: (input) =>
255 cli
256 .updateMergeRequest({
257 cwd: input.cwd,
258 repository: input.repository,
259 number: input.number,
260 ...(input.title === undefined ? {} : { title: input.title }),
261 ...(input.body === undefined ? {} : { description: input.body }),
262 })
263 .pipe(Effect.mapError(fail("updateChangeRequest"))),
264
265 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
266
267 // The kind is not read: every comment this provider hands out, positioned or not, carries a
268 // plain REST note id, and one endpoint rewrites both.
269 updateComment: (input) =>
270 cli
271 .updateNote({
272 cwd: input.cwd,
273 repository: input.repository,
274 number: input.number,
275 noteId: input.commentId,
276 body: input.body,
277 })
278 .pipe(Effect.mapError(fail("updateComment"))),
279
280 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
281
282 replyToThread: (input) =>
283 cli
284 .replyToDiscussion({
285 cwd: input.cwd,
286 repository: input.repository,
287 number: input.number,
288 discussionId: input.threadId,
289 body: input.body,
290 })
291 .pipe(Effect.mapError(fail("replyToThread"))),
292
293 setReaction: (input) =>
294 cli
295 .setReaction({
296 cwd: input.cwd,
297 repository: input.repository,
298 number: input.number,
299 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
300 content: input.content,
301 reacted: input.reacted,
302 })
303 .pipe(Effect.mapError(fail("setReaction"))),
304
305 setThreadResolution: (input) =>
306 cli
307 .setDiscussionResolution({
308 cwd: input.cwd,
309 repository: input.repository,
310 number: input.number,
311 discussionId: input.threadId,
312 resolved: input.resolved,
313 })
314 .pipe(Effect.mapError(fail("setThreadResolution"))),
315 };
316
317 return provider;
318});