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