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

GitLabPullRequestProvider.ts

343 lines11.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import type {
4 PullRequestCapabilities,
5 PullRequestReaction,
6 PullRequestViewerPermissions,
7} from "@t3tools/contracts";
8​
9import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
10import {
11 PullRequestProviderError,
12 type PullRequestProviderFailure,
13 type ProviderChangeRequestActivity,
14 type ProviderChangeRequestDetail,
15 type PullRequestProviderApi,
16} from "@t3tools/source-control-core/server/PullRequestProvider";
17import { definition } from "../client/definition.ts";
18​
19const CAPABILITIES: PullRequestCapabilities = {
20 diff: true,
21 comment: true,
22 actions: [...definition.changeRequestActions],
23 mergeMethods: ["merge", "squash", "rebase"],
24 // Rebase alone: GitLab moves a stale branch onto its target by replaying it, and has nothing
25 // that merges the target back in the way GitHub's update button can.
26 updateMethods: ["rebase"],
27 search: true,
28 reactions: true,
29 // GitLab keeps a reader's viewed files in one browser's local storage, where nothing outside
30 // that browser can read or write them.
31 viewedFiles: "environment",
32 review: {
33 inlineComment: true,
34 reply: true,
35 resolve: true,
36 // No "changes requested": GitLab has approval and unresolved discussions, and nothing that
37 // says a merge request has been reviewed and rejected.
38 verdicts: ["comment", "approve"],
39 },
40 reviewers: { request: true, listCandidates: true },
41 assignees: true,
42 edit: { changeRequest: true, comment: true },
43};
44​
45/**
46 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
47 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
48 * and someone it will not let land this change has no business rewriting its branch either.
49 */
50const MERGE_ACTIONS: ReadonlySet<string> = new Set([
51 "merge",
52 "update-branch",
53 "enable-auto-merge",
54 "disable-auto-merge",
55]);
56​
57/**
58 * GitLab's REST API reports the viewer's role on the project but never whether they opened this
59 * merge request — and its author may close it, reopen it and move it in and out of draft
60 * whatever their role, just as the author of a note may resolve the discussion it started.
61 */
62export function gitLabViewerPermissions(input: {
63 readonly viewerCanMerge: boolean;
64}): PullRequestViewerPermissions {
65 return {
66 actions: CAPABILITIES.actions.filter(
67 (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
68 ),
69 comment: true,
70 resolve: true,
71 verdicts: CAPABILITIES.review.verdicts,
72 requestReviewers: true,
73 // GitLab does not say whether this viewer may assign; it refuses when they may not.
74 assignees: true,
75 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
76 };
78​
79function gitLabProviderFailure(
80 error: GitLabPullRequestCli.GitLabPullRequestCliError,
81): PullRequestProviderFailure {
82 if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };
83 if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };
84 if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };
85 if (error._tag === "GitLabMergeRequestNotFoundError") return { reason: "not-found" };
86 return { reason: "failed" };
88​
89export const make = Effect.gen(function* () {
90 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
91​
92 const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
93 new PullRequestProviderError({
94 provider: SourceControlProviderKind.make("gitlab"),
95 operation,
96 ...gitLabProviderFailure(error),
97 detail: error.detail,
98 cause: error,
99 });
100​
101 // Optional endpoints may lose part of the activity, but an unusable CLI or account must
102 // reach the caller so it can report authentication failures and pause a throttled host.
103 const recoverRead = <A>(
104 read: Effect.Effect<A, GitLabPullRequestCli.GitLabPullRequestCliError>,
105 fallback: A,
106 ) =>
107 read.pipe(
108 Effect.catch((error) => {
109 const { reason } = gitLabProviderFailure(error);
110 return reason === "rate-limited" ||
111 reason === "unauthenticated" ||
112 reason === "missing-tool"
113 ? Effect.fail(error)
114 : Effect.succeed(fallback);
115 }),
116 );
117​
118 const provider: PullRequestProviderApi = {
119 kind: SourceControlProviderKind.make("gitlab"),
120 capabilities: CAPABILITIES,
121​
122 getViewer: (input) =>
123 cli.getViewerUsername({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
124​
125 listChangeRequests: (input) =>
126 cli
127 .listMergeRequests({
128 cwd: input.cwd,
129 repository: input.repository,
130 state: input.state,
131 involvement: input.involvement,
132 viewer: input.viewer,
133 limit: input.limit,
134 query: input.query,
135 assignee: input.filters?.assignee,
136 cursor: input.cursor,
137 })
138 .pipe(
139 Effect.mapError(fail("listChangeRequests")),
140 Effect.map((batch) => ({ ...batch, continues: true })),
141 ),
142​
143 getChangeRequestChecks: (input) =>
144 cli.getMergeRequestDetail(input).pipe(
145 Effect.map(({ state, checks }) => ({ state, checks })),
146 Effect.mapError(fail("getChangeRequestChecks")),
147 ),
148​
149 getChangeRequest: (input) =>
150 Effect.all(
151 [
152 cli.getMergeRequestDetail(input),
153 cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
154 ],
155 { concurrency: 2 },
156 ).pipe(
157 Effect.mapError(fail("getChangeRequest")),
158 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
159 ...mergeRequest,
160 mergeCapabilities,
161 viewerPermissions: gitLabViewerPermissions(mergeRequest),
162 // A GitLab too old to count the divergence says nothing here rather than "up to
163 // date": the banner is worth missing, and a wrong all-clear is not worth showing.
164 baseComparison:
165 mergeRequest.divergedCommits === undefined
166 ? "unknown"
167 : mergeRequest.divergedCommits > 0
168 ? "behind"
169 : "up-to-date",
170 ...(mergeRequest.divergedCommits === undefined
171 ? {}
172 : { behindBy: mergeRequest.divergedCommits }),
173 })),
174 ),
175​
176 getChangeRequestActivity: (input) =>
177 Effect.all(
178 [
179 recoverRead(cli.listNotes(input), { comments: [], truncated: true }),
180 recoverRead(cli.listCommits(input), []),
181 recoverRead(cli.listDiscussions(input), { threads: [], truncated: true }),
182 recoverRead(cli.listReactions(input), {
183 reactions: [] as ReadonlyArray<PullRequestReaction>,
184 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
185 }),
186 ],
187 { concurrency: 4 },
188 ).pipe(
189 Effect.mapError(fail("getChangeRequestActivity")),
190 Effect.map(([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
191 reactions: awards.reactions,
192 comments: notes.comments.map((comment) => ({
193 ...comment,
194 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
195 })),
196 commentCount: notes.comments.length,
197 commentsTruncated: notes.truncated || discussions.truncated,
198 reviewThreads: discussions.threads.map((thread) => ({
199 ...thread,
200 comments: thread.comments.map((comment) => ({
201 ...comment,
202 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
203 })),
204 })),
205 commits,
206 })),
207 ),
208​
209 getViewerPermissions: (input) =>
210 cli
211 .getMergeRequestDetail(input)
212 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
213​
214 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
215​
216 getDiffFileContents: (input) =>
217 cli.getMergeRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
218​
219 // GitLab's own local-storage marks are keyed on the blob id too, so this stales at the same
220 // moment its web UI would.
221 getFileRevisions: (input) =>
222 cli.getFileRevisions(input).pipe(
223 Effect.mapError(fail("getFileRevisions")),
224 Effect.map((revisions) => ({ revisions })),
225 ),
226​
227 // Users only: GitLab requests a review of a person, and the groups that can stand in for one
228 // appear in approval rules rather than in a merge request's reviewers.
229 listReviewerCandidates: (input) =>
230 cli
231 .listReviewerCandidates({
232 cwd: input.cwd,
233 repository: input.repository,
234 number: input.number,
235 })
236 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
237​
238 setReviewerRequest: (input) =>
239 cli
240 .setReviewerRequest({
241 cwd: input.cwd,
242 repository: input.repository,
243 number: input.number,
244 reviewers: input.reviewers,
245 requested: input.requested,
246 })
247 .pipe(Effect.mapError(fail("setReviewerRequest"))),
248​
249 listAssigneeCandidates: (input) =>
250 cli
251 .listAssigneeCandidates({
252 cwd: input.cwd,
253 repository: input.repository,
254 number: input.number,
255 query: input.query,
256 })
257 .pipe(Effect.mapError(fail("listAssigneeCandidates"))),
258​
259 setAssignees: (input) =>
260 cli
261 .setAssignees({
262 cwd: input.cwd,
263 repository: input.repository,
264 number: input.number,
265 assignees: input.assignees,
266 assigned: input.assigned,
267 })
268 .pipe(Effect.mapError(fail("setAssignees"))),
269​
270 runAction: (input) =>
271 cli
272 .runMergeRequestAction({
273 cwd: input.cwd,
274 repository: input.repository,
275 number: input.number,
276 action: input.action,
277 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
278 })
279 .pipe(Effect.mapError(fail("runAction"))),
280​
281 updateChangeRequest: (input) =>
282 cli
283 .updateMergeRequest({
284 cwd: input.cwd,
285 repository: input.repository,
286 number: input.number,
287 ...(input.title === undefined ? {} : { title: input.title }),
288 ...(input.body === undefined ? {} : { description: input.body }),
289 })
290 .pipe(Effect.mapError(fail("updateChangeRequest"))),
291​
292 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
293​
294 updateComment: (input) =>
295 cli
296 .updateNote({
297 cwd: input.cwd,
298 repository: input.repository,
299 number: input.number,
300 noteId: input.commentId,
301 body: input.body,
302 })
303 .pipe(Effect.mapError(fail("updateComment"))),
304​
305 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
306​
307 replyToThread: (input) =>
308 cli
309 .replyToDiscussion({
310 cwd: input.cwd,
311 repository: input.repository,
312 number: input.number,
313 discussionId: input.threadId,
314 body: input.body,
315 })
316 .pipe(Effect.mapError(fail("replyToThread"))),
317​
318 setReaction: (input) =>
319 cli
320 .setReaction({
321 cwd: input.cwd,
322 repository: input.repository,
323 number: input.number,
324 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
325 content: input.content,
326 reacted: input.reacted,
327 })
328 .pipe(Effect.mapError(fail("setReaction"))),
329​
330 setThreadResolution: (input) =>
331 cli
332 .setDiscussionResolution({
333 cwd: input.cwd,
334 repository: input.repository,
335 number: input.number,
336 discussionId: input.threadId,
337 resolved: input.resolved,
338 })
339 .pipe(Effect.mapError(fail("setThreadResolution"))),
340 };
341​
342 return provider;
343});