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

GitLabPullRequestProvider.ts

339 lines12.7 KB

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