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 "../shared/definition.ts";
18
19const CAPABILITIES: PullRequestCapabilities = {
20 diff: true,
21 comment: true,
22 actions: [...definition.changeRequestActions],
23 mergeMethods: ["merge", "squash", "rebase"],
24 // GitLab has no merge-target-into-source operation.
25 updateMethods: ["rebase"],
26 search: true,
27 reactions: true,
28 // GitLab's viewed marks live in browser-local storage.
29 viewedFiles: "environment",
30 review: {
31 inlineComment: true,
32 reply: true,
33 resolve: true,
34 // GitLab has no requested-changes verdict.
35 verdicts: ["comment", "approve"],
36 },
37 reviewers: { request: true, listCandidates: true },
38 edit: { changeRequest: true, comment: true },
39};
40
41const UNAVAILABLE_REQUIREMENT = {
42 missing:
43 "GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",
44 unauthenticated: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
45};
46
47/**
48 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
49 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
50 * and someone it will not let land this change has no business rewriting its branch either.
51 */
52const MERGE_ACTIONS: ReadonlySet<string> = new Set([
53 "merge",
54 "update-branch",
55 "enable-auto-merge",
56 "disable-auto-merge",
57]);
58
59/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
60export function gitLabViewerPermissions(input: {
61 readonly viewerCanMerge: boolean;
62}): PullRequestViewerPermissions {
63 return {
64 actions: CAPABILITIES.actions.filter(
65 (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
66 ),
67 comment: true,
68 resolve: true,
69 verdicts: CAPABILITIES.review.verdicts,
70 requestReviewers: true,
71 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
72 };
73}
74
75function gitLabProviderFailure(
76 error: GitLabPullRequestCli.GitLabPullRequestCliError,
77): PullRequestProviderFailure {
78 if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };
79 if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };
80 if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };
81 if (error._tag === "GitLabMergeRequestNotFoundError") return { reason: "not-found" };
82 return { reason: "failed" };
83}
84
85export const make = Effect.gen(function* () {
86 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
87
88 const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
89 new PullRequestProviderError({
90 provider: SourceControlProviderKind.make("gitlab"),
91 operation,
92 ...gitLabProviderFailure(error),
93 detail: error.detail,
94 cause: error,
95 });
96
97 // Optional endpoints may lose part of the activity, but an unusable CLI or account must
98 // reach the caller so it can report authentication failures and pause a throttled host.
99 const recoverRead = <A>(
100 read: Effect.Effect<A, GitLabPullRequestCli.GitLabPullRequestCliError>,
101 fallback: A,
102 ) =>
103 read.pipe(
104 Effect.catch((error) => {
105 const { reason } = gitLabProviderFailure(error);
106 return reason === "rate-limited" ||
107 reason === "unauthenticated" ||
108 reason === "missing-tool"
109 ? Effect.fail(error)
110 : Effect.succeed(fallback);
111 }),
112 );
113
114 const provider: PullRequestProviderApi = {
115 kind: SourceControlProviderKind.make("gitlab"),
116 capabilities: CAPABILITIES,
117 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
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 // Missing divergence counts mean unknown, not up to date.
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 getFileRevisions: (input) =>
216 cli.getFileRevisions(input).pipe(
217 Effect.mapError(fail("getFileRevisions")),
218 Effect.map((revisions) => ({ revisions })),
219 ),
220
221 // MR reviewers are users; groups belong to approval rules.
222 listReviewerCandidates: (input) =>
223 cli
224 .listReviewerCandidates({
225 cwd: input.cwd,
226 repository: input.repository,
227 number: input.number,
228 })
229 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
230
231 listRepositoryLabels: (input) =>
232 cli
233 .listProjectLabels({ cwd: input.cwd, repository: input.repository, search: input.query })
234 .pipe(Effect.mapError(fail("listRepositoryLabels"))),
235
236 searchRepositoryAuthors: (input) =>
237 cli
238 .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })
239 .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
240
241 setReviewerRequest: (input) =>
242 cli
243 .setReviewerRequest({
244 cwd: input.cwd,
245 repository: input.repository,
246 number: input.number,
247 reviewers: input.reviewers,
248 requested: input.requested,
249 })
250 .pipe(Effect.mapError(fail("setReviewerRequest"))),
251
252 runAction: (input) =>
253 cli
254 .runMergeRequestAction({
255 cwd: input.cwd,
256 repository: input.repository,
257 number: input.number,
258 action: input.action,
259 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
260 })
261 .pipe(Effect.mapError(fail("runAction"))),
262
263 updateChangeRequest: (input) =>
264 cli
265 .updateMergeRequest({
266 cwd: input.cwd,
267 repository: input.repository,
268 number: input.number,
269 ...(input.title === undefined ? {} : { title: input.title }),
270 ...(input.body === undefined ? {} : { description: input.body }),
271 })
272 .pipe(Effect.mapError(fail("updateChangeRequest"))),
273
274 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
275
276 updateComment: (input) =>
277 cli
278 .updateNote({
279 cwd: input.cwd,
280 repository: input.repository,
281 number: input.number,
282 noteId: input.commentId,
283 body: input.body,
284 })
285 .pipe(Effect.mapError(fail("updateComment"))),
286
287 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
288
289 replyToThread: (input) =>
290 cli
291 .replyToDiscussion({
292 cwd: input.cwd,
293 repository: input.repository,
294 number: input.number,
295 discussionId: input.threadId,
296 body: input.body,
297 })
298 .pipe(Effect.mapError(fail("replyToThread"))),
299
300 setReaction: (input) =>
301 cli
302 .setReaction({
303 cwd: input.cwd,
304 repository: input.repository,
305 number: input.number,
306 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
307 content: input.content,
308 reacted: input.reacted,
309 })
310 .pipe(Effect.mapError(fail("setReaction"))),
311
312 setThreadResolution: (input) =>
313 cli
314 .setDiscussionResolution({
315 cwd: input.cwd,
316 repository: input.repository,
317 number: input.number,
318 discussionId: input.threadId,
319 resolved: input.resolved,
320 })
321 .pipe(Effect.mapError(fail("setThreadResolution"))),
322 };
323
324 return provider;
325});