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

GitLabPullRequestProvider.ts

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