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