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

GitLabPullRequestProvider.ts

329 lines11.6 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 edit: { changeRequest: true, comment: true },
42};
43​
44/**
45 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
46 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
47 * and someone it will not let land this change has no business rewriting its branch either.
48 */
49const MERGE_ACTIONS: ReadonlySet<string> = new Set([
50 "merge",
51 "update-branch",
52 "enable-auto-merge",
53 "disable-auto-merge",
54]);
55​
56/**
57 * GitLab's REST API reports the viewer's role on the project but never whether they opened this
58 * merge request — and its author may close it, reopen it and move it in and out of draft
59 * whatever their role, just as the author of a note may resolve the discussion it started.
60 */
61export function gitLabViewerPermissions(input: {
62 readonly viewerCanMerge: boolean;
63}): PullRequestViewerPermissions {
64 return {
65 actions: CAPABILITIES.actions.filter(
66 (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
67 ),
68 comment: true,
69 resolve: true,
70 verdicts: CAPABILITIES.review.verdicts,
71 requestReviewers: true,
72 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
73 };
75​
76function gitLabProviderFailure(
77 error: GitLabPullRequestCli.GitLabPullRequestCliError,
78): PullRequestProviderFailure {
79 if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };
80 if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };
81 if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };
82 if (error._tag === "GitLabMergeRequestNotFoundError") return { reason: "not-found" };
83 return { reason: "failed" };
85​
86export const make = Effect.gen(function* () {
87 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
88​
89 const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
90 new PullRequestProviderError({
91 provider: SourceControlProviderKind.make("gitlab"),
92 operation,
93 ...gitLabProviderFailure(error),
94 detail: error.detail,
95 cause: error,
96 });
97​
98 // Optional endpoints may lose part of the activity, but an unusable CLI or account must
99 // reach the caller so it can report authentication failures and pause a throttled host.
100 const recoverRead = <A>(
101 read: Effect.Effect<A, GitLabPullRequestCli.GitLabPullRequestCliError>,
102 fallback: A,
103 ) =>
104 read.pipe(
105 Effect.catch((error) => {
106 const { reason } = gitLabProviderFailure(error);
107 return reason === "rate-limited" ||
108 reason === "unauthenticated" ||
109 reason === "missing-tool"
110 ? Effect.fail(error)
111 : Effect.succeed(fallback);
112 }),
113 );
114​
115 const provider: PullRequestProviderApi = {
116 kind: SourceControlProviderKind.make("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 filters: input.filters,
134 })
135 .pipe(
136 Effect.mapError(fail("listChangeRequests")),
137 Effect.map((batch) => ({ ...batch, continues: true })),
138 ),
139​
140 getChangeRequestChecks: (input) =>
141 cli.getMergeRequestDetail(input).pipe(
142 Effect.map(({ state, checks }) => ({ state, checks })),
143 Effect.mapError(fail("getChangeRequestChecks")),
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 recoverRead(cli.listNotes(input), { comments: [], truncated: true }),
177 recoverRead(cli.listCommits(input), []),
178 recoverRead(cli.listDiscussions(input), { threads: [], truncated: true }),
179 recoverRead(cli.listReactions(input), {
180 reactions: [] as ReadonlyArray<PullRequestReaction>,
181 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
182 }),
183 ],
184 { concurrency: 4 },
185 ).pipe(
186 Effect.mapError(fail("getChangeRequestActivity")),
187 Effect.map(([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
188 reactions: awards.reactions,
189 comments: notes.comments.map((comment) => ({
190 ...comment,
191 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
192 })),
193 commentCount: notes.comments.length,
194 commentsTruncated: notes.truncated || discussions.truncated,
195 reviewThreads: discussions.threads.map((thread) => ({
196 ...thread,
197 comments: thread.comments.map((comment) => ({
198 ...comment,
199 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
200 })),
201 })),
202 commits,
203 })),
204 ),
205​
206 getViewerPermissions: (input) =>
207 cli
208 .getMergeRequestDetail(input)
209 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
210​
211 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
212​
213 getDiffFileContents: (input) =>
214 cli.getMergeRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
215​
216 // GitLab's own local-storage marks are keyed on the blob id too, so this stales at the same
217 // moment its web UI would.
218 getFileRevisions: (input) =>
219 cli.getFileRevisions(input).pipe(
220 Effect.mapError(fail("getFileRevisions")),
221 Effect.map((revisions) => ({ revisions })),
222 ),
223​
224 // Users only: GitLab requests a review of a person, and the groups that can stand in for one
225 // appear in approval rules rather than in a merge request's reviewers.
226 listReviewerCandidates: (input) =>
227 cli
228 .listReviewerCandidates({
229 cwd: input.cwd,
230 repository: input.repository,
231 number: input.number,
232 })
233 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
234​
235 listRepositoryLabels: (input) =>
236 cli
237 .listProjectLabels({ cwd: input.cwd, repository: input.repository, search: input.query })
238 .pipe(Effect.mapError(fail("listRepositoryLabels"))),
239​
240 searchRepositoryAuthors: (input) =>
241 cli
242 .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })
243 .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
244​
245 setReviewerRequest: (input) =>
246 cli
247 .setReviewerRequest({
248 cwd: input.cwd,
249 repository: input.repository,
250 number: input.number,
251 reviewers: input.reviewers,
252 requested: input.requested,
253 })
254 .pipe(Effect.mapError(fail("setReviewerRequest"))),
255​
256 runAction: (input) =>
257 cli
258 .runMergeRequestAction({
259 cwd: input.cwd,
260 repository: input.repository,
261 number: input.number,
262 action: input.action,
263 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
264 })
265 .pipe(Effect.mapError(fail("runAction"))),
266​
267 updateChangeRequest: (input) =>
268 cli
269 .updateMergeRequest({
270 cwd: input.cwd,
271 repository: input.repository,
272 number: input.number,
273 ...(input.title === undefined ? {} : { title: input.title }),
274 ...(input.body === undefined ? {} : { description: input.body }),
275 })
276 .pipe(Effect.mapError(fail("updateChangeRequest"))),
277​
278 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
279​
280 updateComment: (input) =>
281 cli
282 .updateNote({
283 cwd: input.cwd,
284 repository: input.repository,
285 number: input.number,
286 noteId: input.commentId,
287 body: input.body,
288 })
289 .pipe(Effect.mapError(fail("updateComment"))),
290​
291 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
292​
293 replyToThread: (input) =>
294 cli
295 .replyToDiscussion({
296 cwd: input.cwd,
297 repository: input.repository,
298 number: input.number,
299 discussionId: input.threadId,
300 body: input.body,
301 })
302 .pipe(Effect.mapError(fail("replyToThread"))),
303​
304 setReaction: (input) =>
305 cli
306 .setReaction({
307 cwd: input.cwd,
308 repository: input.repository,
309 number: input.number,
310 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
311 content: input.content,
312 reacted: input.reacted,
313 })
314 .pipe(Effect.mapError(fail("setReaction"))),
315​
316 setThreadResolution: (input) =>
317 cli
318 .setDiscussionResolution({
319 cwd: input.cwd,
320 repository: input.repository,
321 number: input.number,
322 discussionId: input.threadId,
323 resolved: input.resolved,
324 })
325 .pipe(Effect.mapError(fail("setThreadResolution"))),
326 };
327​
328 return provider;
329});