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