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