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 // Merge settings only affect the detail panel's actions.
147 getChangeRequestPreview: (input) =>
148 cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
149
150 getChangeRequestSummary: (input) =>
151 cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestSummary"))),
152
153 getChangeRequest: (input) =>
154 Effect.all(
155 [
156 cli.getMergeRequestDetail(input),
157 cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
158 ],
159 { concurrency: 2 },
160 ).pipe(
161 Effect.mapError(fail("getChangeRequest")),
162 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
163 ...mergeRequest,
164 mergeCapabilities,
165 viewerPermissions: gitLabViewerPermissions(mergeRequest),
166 // Missing divergence counts mean unknown, not up to date.
167 baseComparison:
168 mergeRequest.divergedCommits === undefined
169 ? "unknown"
170 : mergeRequest.divergedCommits > 0
171 ? "behind"
172 : "up-to-date",
173 ...(mergeRequest.divergedCommits === undefined
174 ? {}
175 : { behindBy: mergeRequest.divergedCommits }),
176 })),
177 ),
178
179 getChangeRequestActivity: (input) =>
180 Effect.all(
181 [
182 recoverRead(cli.listNotes(input), { comments: [], truncated: true }),
183 recoverRead(cli.listCommits(input), []),
184 recoverRead(cli.listDiscussions(input), { threads: [], truncated: true }),
185 recoverRead(cli.listReactions(input), {
186 reactions: [] as ReadonlyArray<PullRequestReaction>,
187 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
188 }),
189 ],
190 { concurrency: 4 },
191 ).pipe(
192 Effect.mapError(fail("getChangeRequestActivity")),
193 Effect.map(([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 commentCount: notes.comments.length,
200 commentsTruncated: notes.truncated || discussions.truncated,
201 reviewThreads: discussions.threads.map((thread) => ({
202 ...thread,
203 comments: thread.comments.map((comment) => ({
204 ...comment,
205 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
206 })),
207 })),
208 commits,
209 })),
210 ),
211
212 getViewerPermissions: (input) =>
213 cli
214 .getMergeRequestDetail(input)
215 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
216
217 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
218
219 getDiffFileContents: (input) =>
220 cli.getMergeRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
221
222 getFileRevisions: (input) =>
223 cli.getFileRevisions(input).pipe(
224 Effect.mapError(fail("getFileRevisions")),
225 Effect.map((revisions) => ({ revisions })),
226 ),
227
228 // MR reviewers are users; groups belong to approval rules.
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 listRepositoryLabels: (input) =>
239 cli
240 .listProjectLabels({ cwd: input.cwd, repository: input.repository, search: input.query })
241 .pipe(Effect.mapError(fail("listRepositoryLabels"))),
242
243 searchRepositoryAuthors: (input) =>
244 cli
245 .listProjectUsers({ cwd: input.cwd, repository: input.repository, search: input.query })
246 .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
247
248 setReviewerRequest: (input) =>
249 cli
250 .setReviewerRequest({
251 cwd: input.cwd,
252 repository: input.repository,
253 number: input.number,
254 reviewers: input.reviewers,
255 requested: input.requested,
256 })
257 .pipe(Effect.mapError(fail("setReviewerRequest"))),
258
259 runAction: (input) =>
260 cli
261 .runMergeRequestAction({
262 cwd: input.cwd,
263 repository: input.repository,
264 number: input.number,
265 action: input.action,
266 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
267 })
268 .pipe(Effect.mapError(fail("runAction"))),
269
270 updateChangeRequest: (input) =>
271 cli
272 .updateMergeRequest({
273 cwd: input.cwd,
274 repository: input.repository,
275 number: input.number,
276 ...(input.title === undefined ? {} : { title: input.title }),
277 ...(input.body === undefined ? {} : { description: input.body }),
278 })
279 .pipe(Effect.mapError(fail("updateChangeRequest"))),
280
281 comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
282
283 updateComment: (input) =>
284 cli
285 .updateNote({
286 cwd: input.cwd,
287 repository: input.repository,
288 number: input.number,
289 noteId: input.commentId,
290 body: input.body,
291 })
292 .pipe(Effect.mapError(fail("updateComment"))),
293
294 submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
295
296 replyToThread: (input) =>
297 cli
298 .replyToDiscussion({
299 cwd: input.cwd,
300 repository: input.repository,
301 number: input.number,
302 discussionId: input.threadId,
303 body: input.body,
304 })
305 .pipe(Effect.mapError(fail("replyToThread"))),
306
307 setReaction: (input) =>
308 cli
309 .setReaction({
310 cwd: input.cwd,
311 repository: input.repository,
312 number: input.number,
313 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
314 content: input.content,
315 reacted: input.reacted,
316 })
317 .pipe(Effect.mapError(fail("setReaction"))),
318
319 setThreadResolution: (input) =>
320 cli
321 .setDiscussionResolution({
322 cwd: input.cwd,
323 repository: input.repository,
324 number: input.number,
325 discussionId: input.threadId,
326 resolved: input.resolved,
327 })
328 .pipe(Effect.mapError(fail("setThreadResolution"))),
329 };
330
331 return provider;
332});