Open History to see the last commit
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 };
74}
75
76export function 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" };
84}
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 })
134 .pipe(
135 Effect.mapError(fail("listChangeRequests")),
136 Effect.map((batch) => ({ ...batch, continues: true })),
137 ),
138
139 getChangeRequestChecks: (input) =>
140 cli.getMergeRequestDetail(input).pipe(
141 Effect.map(({ state, checks }) => ({ state, checks })),
142 Effect.mapError(fail("getChangeRequestChecks")),
143 ),
144
145 getChangeRequest: (input) =>
146 Effect.all(
147 [
148 cli.getMergeRequestDetail(input),
149 cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
150 ],
151 { concurrency: 2 },
152 ).pipe(
153 Effect.mapError(fail("getChangeRequest")),
154 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
155 ...mergeRequest,
156 mergeCapabilities,
157 viewerPermissions: gitLabViewerPermissions(mergeRequest),
158 // A GitLab too old to count the divergence says nothing here rather than "up to
159 // date": the banner is worth missing, and a wrong all-clear is not worth showing.
160 baseComparison:
161 mergeRequest.divergedCommits === undefined
162 ? "unknown"
163 : mergeRequest.divergedCommits > 0
164 ? "behind"
165 : "up-to-date",
166 ...(mergeRequest.divergedCommits === undefined
167 ? {}
168 : { behindBy: mergeRequest.divergedCommits }),
169 })),
170 ),
171
172 getChangeRequestActivity: (input) =>
173 Effect.all(
174 [
175 recoverRead(cli.listNotes(input), { comments: [], truncated: true }),
176 recoverRead(cli.listCommits(input), []),
177 recoverRead(cli.listDiscussions(input), { threads: [], truncated: true }),
178 recoverRead(cli.listReactions(input), {
179 reactions: [] as ReadonlyArray<PullRequestReaction>,
180 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
181 }),
182 ],
183 { concurrency: 4 },
184 ).pipe(
185 Effect.mapError(fail("getChangeRequestActivity")),
186 Effect.map(([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
187 reactions: awards.reactions,
188 comments: notes.comments.map((comment) => ({
189 ...comment,
190 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
191 })),
192 commentCount: notes.comments.length,
193 commentsTruncated: notes.truncated || discussions.truncated,
194 reviewThreads: discussions.threads.map((thread) => ({
195 ...thread,
196 comments: thread.comments.map((comment) => ({
197 ...comment,
198 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
199 })),
200 })),
201 commits,
202 })),
203 ),
204
205 getViewerPermissions: (input) =>
206 cli
207 .getMergeRequestDetail(input)
208 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
209
210 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
211
212 getDiffFileContents: (input) =>
213 cli.getMergeRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
214
215 // GitLab's own local-storage marks are keyed on the blob id too, so this stales at the same
216 // moment its web UI would.
217 getFileRevisions: (input) =>
218 cli.getFileRevisions(input).pipe(
219 Effect.mapError(fail("getFileRevisions")),
220 Effect.map((revisions) => ({ revisions })),
221 ),
222
223 // Users only: GitLab requests a review of a person, and the groups that can stand in for one
224 // appear in approval rules rather than in a merge request's reviewers.
225 listReviewerCandidates: (input) =>
226 cli
227 .listReviewerCandidates({
228 cwd: input.cwd,
229 repository: input.repository,
230 number: input.number,
231 })
232 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
233
234 setReviewerRequest: (input) =>
235 cli
236 .setReviewerRequest({
237 cwd: input.cwd,
238 repository: input.repository,
239 number: input.number,
240 reviewers: input.reviewers,
241 requested: input.requested,
242 })
243 .pipe(Effect.mapError(fail("setReviewerRequest"))),
244
245 runAction: (input) =>
246 cli
247 .runMergeRequestAction({
248 cwd: input.cwd,
249 repository: input.repository,
250 number: input.number,
251 action: input.action,
252 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
253 })
254 .pipe(Effect.mapError(fail("runAction"))),
255
256 updateChangeRequest: (input) =>
257 cli
258 .updateMergeRequest({
259 cwd: input.cwd,
260 repository: input.repository,
261 number: input.number,
262 ...(input.title === undefined ? {} : { title: input.title }),
263 ...(input.body === undefined ? {} : { description: input.body }),
264 })
265 .pipe(Effect.mapError(fail("updateChangeRequest"))),
266
267 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
268
269 updateComment: (input) =>
270 cli
271 .updateNote({
272 cwd: input.cwd,
273 repository: input.repository,
274 number: input.number,
275 noteId: input.commentId,
276 body: input.body,
277 })
278 .pipe(Effect.mapError(fail("updateComment"))),
279
280 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
281
282 replyToThread: (input) =>
283 cli
284 .replyToDiscussion({
285 cwd: input.cwd,
286 repository: input.repository,
287 number: input.number,
288 discussionId: input.threadId,
289 body: input.body,
290 })
291 .pipe(Effect.mapError(fail("replyToThread"))),
292
293 setReaction: (input) =>
294 cli
295 .setReaction({
296 cwd: input.cwd,
297 repository: input.repository,
298 number: input.number,
299 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
300 content: input.content,
301 reacted: input.reacted,
302 })
303 .pipe(Effect.mapError(fail("setReaction"))),
304
305 setThreadResolution: (input) =>
306 cli
307 .setDiscussionResolution({
308 cwd: input.cwd,
309 repository: input.repository,
310 number: input.number,
311 discussionId: input.threadId,
312 resolved: input.resolved,
313 })
314 .pipe(Effect.mapError(fail("setThreadResolution"))),
315 };
316
317 return provider;
318});