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 getChangeRequest: (input) =>
147 Effect.all(
148 [
149 cli.getMergeRequestDetail(input),
150 cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
151 ],
152 { concurrency: 2 },
153 ).pipe(
154 Effect.mapError(fail("getChangeRequest")),
155 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
156 ...mergeRequest,
157 mergeCapabilities,
158 viewerPermissions: gitLabViewerPermissions(mergeRequest),
159 // A GitLab too old to count the divergence says nothing here rather than "up to
160 // date": the banner is worth missing, and a wrong all-clear is not worth showing.
161 baseComparison:
162 mergeRequest.divergedCommits === undefined
163 ? "unknown"
164 : mergeRequest.divergedCommits > 0
165 ? "behind"
166 : "up-to-date",
167 ...(mergeRequest.divergedCommits === undefined
168 ? {}
169 : { behindBy: mergeRequest.divergedCommits }),
170 })),
171 ),
172
173 getChangeRequestActivity: (input) =>
174 Effect.all(
175 [
176 cli
177 .listNotes(input)
178 .pipe(Effect.orElseSucceed(() => ({ comments: [], truncated: true }))),
179 cli.listCommits(input).pipe(Effect.orElseSucceed(() => [])),
180 cli
181 .listDiscussions(input)
182 .pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
183 // The notes endpoint carries no award of any kind, so they are read alongside it. A
184 // failed read costs the conversation its reactions rather than its words.
185 cli.listReactions(input).pipe(
186 Effect.orElseSucceed(() => ({
187 reactions: [] as ReadonlyArray<PullRequestReaction>,
188 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
189 })),
190 ),
191 ],
192 { concurrency: 4 },
193 ).pipe(
194 Effect.mapError(fail("getChangeRequestActivity")),
195 Effect.map(([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
196 reactions: awards.reactions,
197 comments: notes.comments.map((comment) => ({
198 ...comment,
199 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
200 })),
201 // GitLab reports no count of its own, so the walk's own total is the host's: the
202 // notes endpoint carries every comment on the merge request, including the ones
203 // written under a discussion, and it is read until GitLab runs out.
204 commentCount: notes.comments.length,
205 commentsTruncated: notes.truncated || discussions.truncated,
206 reviewThreads: discussions.threads.map((thread) => ({
207 ...thread,
208 comments: thread.comments.map((comment) => ({
209 ...comment,
210 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
211 })),
212 })),
213 commits,
214 })),
215 ),
216
217 // The same read the detail takes it from, on its own: `user.can_merge` lives on the merge
218 // request, so there is no cheaper thing to ask GitLab.
219 getViewerPermissions: (input) =>
220 cli
221 .getMergeRequestDetail(input)
222 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
223
224 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
225
226 // What each marked file is at the head, which is what tells a mark that still stands from one
227 // the branch has moved past. GitLab's own local-storage marks are keyed on the blob id too,
228 // so this stales at the same moment its web UI would.
229 getFileRevisions: (input) =>
230 cli.getFileRevisions(input).pipe(
231 Effect.mapError(fail("getFileRevisions")),
232 Effect.map((revisions) => ({ revisions })),
233 ),
234
235 // Users only: GitLab requests a review of a person, and the groups that can stand in for one
236 // appear in approval rules rather than in a merge request's reviewers.
237 listReviewerCandidates: (input) =>
238 cli
239 .listReviewerCandidates({
240 cwd: input.cwd,
241 repository: input.repository,
242 number: input.number,
243 })
244 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
245
246 setReviewerRequest: (input) =>
247 cli
248 .setReviewerRequest({
249 cwd: input.cwd,
250 repository: input.repository,
251 number: input.number,
252 reviewers: input.reviewers,
253 requested: input.requested,
254 })
255 .pipe(Effect.mapError(fail("setReviewerRequest"))),
256
257 runAction: (input) =>
258 cli
259 .runMergeRequestAction({
260 cwd: input.cwd,
261 repository: input.repository,
262 number: input.number,
263 action: input.action,
264 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
265 })
266 .pipe(Effect.mapError(fail("runAction"))),
267
268 updateChangeRequest: (input) =>
269 cli
270 .updateMergeRequest({
271 cwd: input.cwd,
272 repository: input.repository,
273 number: input.number,
274 ...(input.title === undefined ? {} : { title: input.title }),
275 ...(input.body === undefined ? {} : { description: input.body }),
276 })
277 .pipe(Effect.mapError(fail("updateChangeRequest"))),
278
279 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
280
281 // The kind is not read: every comment this provider hands out, positioned or not, carries a
282 // plain REST note id, and one endpoint rewrites both.
283 updateComment: (input) =>
284 cli
285 .updateNote({
286 cwd: input.cwd,
287 repository: input.repository,
288 number: input.number,
289 noteId: input.commentId,
290 body: input.body,
291 })
292 .pipe(Effect.mapError(fail("updateComment"))),
293
294 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
295
296 replyToThread: (input) =>
297 cli
298 .replyToDiscussion({
299 cwd: input.cwd,
300 repository: input.repository,
301 number: input.number,
302 discussionId: input.threadId,
303 body: input.body,
304 })
305 .pipe(Effect.mapError(fail("replyToThread"))),
306
307 setReaction: (input) =>
308 cli
309 .setReaction({
310 cwd: input.cwd,
311 repository: input.repository,
312 number: input.number,
313 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
314 content: input.content,
315 reacted: input.reacted,
316 })
317 .pipe(Effect.mapError(fail("setReaction"))),
318
319 setThreadResolution: (input) =>
320 cli
321 .setDiscussionResolution({
322 cwd: input.cwd,
323 repository: input.repository,
324 number: input.number,
325 discussionId: input.threadId,
326 resolved: input.resolved,
327 })
328 .pipe(Effect.mapError(fail("setThreadResolution"))),
329 };
330
331 return provider;
332});