@devries-cameron20 / t3code-1 / commits / 444921eb71
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(gitlab): merge requests can edit their labels (#30483)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Antony committed Nov 6, 2026 at 01:28 UTC 444921eb71dfd1c8d8d2cdb873f2d1ad06b50f5e
7 files changed +471 -63
packages/client-runtime/src/state/pullRequests.test.ts
+1 -1
@@ -2100,7 +2100,7 @@ it.effect("updates cached labels after successful edits without rereading the ho
2100 host: "github.example.com",
2101 },
2102 };
2103 - const detail = atoms.detail(target);
2103 + const detail = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
2104 const candidates = atoms.labelCandidates(target);
2105 registry.mount(detail);
2106 const unmountCandidates = registry.mount(candidates);
packages/client-runtime/src/state/pullRequests.ts
+39 -25
@@ -518,6 +518,16 @@ export function createPullRequestEnvironmentAtoms<R, E>(
518 },
519 ),
520 );
521 + // Pages read the strict detail and other surfaces the default one; patch whichever is loaded
522 + // without starting a read of the other.
523 + const loadedDetails = (
524 + registry: AtomRegistry.AtomRegistry,
525 + target: { readonly environmentId: EnvironmentId; readonly input: PullRequestRef },
526 + ) =>
527 + [
528 + detail({ ...target, input: { ...target.input, allowStale: undefined } }),
529 + detail({ ...target, input: { ...target.input, allowStale: false } }),
530 + ].filter((atom) => registry.getNodes().has(atom));
531 const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
532 Atom.family((answer: ReturnType<typeof detailAnswers>) =>
533 Atom.make((get) => {
@@ -950,15 +960,17 @@ export function createPullRequestEnvironmentAtoms<R, E>(
960 : actors.filter(
961 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
962 );
953 - updateCached(
954 - registry,
955 - detail(target),
956 - (value) => ({
957 - ...value,
958 - reviewers: updateReviewers(value.reviewers),
959 - }),
960 - missingIdentities,
961 - );
963 + for (const atom of loadedDetails(registry, target)) {
964 + updateCached(
965 + registry,
966 + atom,
967 + (value) => ({
968 + ...value,
969 + reviewers: updateReviewers(value.reviewers),
970 + }),
971 + missingIdentities,
972 + );
973 + }
974 updateCached(
975 registry,
976 activity(target),
@@ -1008,22 +1020,24 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1020 names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
1021 ),
1022 }));
1011 - updateCached(registry, detail(target), (value) => ({
1012 - ...value,
1013 - labels: applied
1014 - ? [
1015 - ...value.labels,
1016 - ...labels
1017 - .filter((name) => !value.labels.some((label) => label.name === name))
1018 - .map((name) => ({
1019 - name,
1020 - color:
1021 - candidates?.candidates.find((candidate) => candidate.name === name)
1022 - ?.color ?? null,
1023 - })),
1024 - ]
1025 - : value.labels.filter((label) => !names.has(label.name)),
1026 - }));
1023 + for (const atom of loadedDetails(registry, target)) {
1024 + updateCached(registry, atom, (value) => ({
1025 + ...value,
1026 + labels: applied
1027 + ? [
1028 + ...value.labels,
1029 + ...labels
1030 + .filter((name) => !value.labels.some((label) => label.name === name))
1031 + .map((name) => ({
1032 + name,
1033 + color:
1034 + candidates?.candidates.find((candidate) => candidate.name === name)
1035 + ?.color ?? null,
1036 + })),
1037 + ]
1038 + : value.labels.filter((label) => !names.has(label.name)),
1039 + }));
1040 + }
1041 }),
1042 }),
1043 setThreadResolution: createEnvironmentRpcCommand(runtime, {
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+151 -7
@@ -1,4 +1,5 @@
1 import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2 +import { VcsProcessExitError } from "@t3tools/contracts";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import { ChildProcessSpawner } from "effect/process";
@@ -65,6 +66,11 @@ function notes(count: number, firstId: number): string {
66 }
67
68 const author = { id: 1, username: "bilal" };
69 +const labelPermission = output(
70 + JSON.stringify({
71 + data: { project: { mergeRequest: { userPermissions: { adminMergeRequest: false } } } },
72 + }),
73 +);
74 const reviewer = { id: 5, username: "octocat" };
75
76 function mergeRequestJson(overrides: Record<string, unknown>): string {
@@ -1223,6 +1229,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
1229 ),
1230 ),
1231 )
1232 + .mockReturnValueOnce(Effect.succeed(labelPermission))
1233 .mockReturnValueOnce(
1234 Effect.succeed(
1235 output(
@@ -1252,7 +1259,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
1259 ["Pipeline", "success", "https://gitlab.com/bilal/web/-/pipelines/31"],
1260 ["deploy", "failure", "https://gitlab.com/bilal/web/-/pipelines/32"],
1261 ]);
1255 - expect(argsOfCall(1)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
1262 + expect(argsOfCall(2)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
1263 }),
1264 );
1265
@@ -1264,6 +1271,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
1271 const failedChild = { name: "deploy", downstream_pipeline: { status: "failed" } };
1272 mockedExecute
1273 .mockReturnValueOnce(Effect.succeed(detailOutput))
1274 + .mockReturnValueOnce(Effect.succeed(labelPermission))
1275 .mockReturnValueOnce(
1276 Effect.fail(
1277 new GitLabCli.GitLabCliCommandError({
@@ -1275,6 +1283,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
1283 ),
1284 )
1285 .mockReturnValueOnce(Effect.succeed(detailOutput))
1286 + .mockReturnValueOnce(Effect.succeed(labelPermission))
1287 // A full page may have left out the trigger job whose pipeline failed.
1288 .mockReturnValueOnce(
1289 Effect.succeed(output(JSON.stringify(Array.from({ length: 100 }, () => failedChild)))),
@@ -1295,15 +1304,25 @@ layer("GitLabPullRequestCli.layer", (it) => {
1304 }),
1305 );
1306
1298 - it.effect("reads merge permissions without reading the trigger jobs", () =>
1307 + it.effect.each([
1308 + {
1309 + answer: JSON.stringify({
1310 + data: { project: { mergeRequest: { userPermissions: { adminMergeRequest: true } } } },
1311 + }),
1312 + expected: true,
1313 + },
1314 + { answer: JSON.stringify({ errors: [{ message: "Field unknown" }] }), expected: false },
1315 + ])("reads merge and label permissions without reading the trigger jobs", ({ answer, expected }) =>
1316 Effect.gen(function* () {
1300 - mockedExecute.mockReturnValueOnce(
1317 + mockedExecute.mockImplementation(({ args }) =>
1318 Effect.succeed(
1319 output(
1303 - mergeRequestJson({
1304 - head_pipeline: { id: 31, project_id: 12, status: "success" },
1305 - user: { can_merge: false },
1306 - }),
1320 + args[1] === "graphql"
1321 + ? answer
1322 + : mergeRequestJson({
1323 + head_pipeline: { id: 31, project_id: 12, status: "success" },
1324 + user: { can_merge: false },
1325 + }),
1326 ),
1327 ),
1328 );
@@ -1317,7 +1336,132 @@ layer("GitLabPullRequestCli.layer", (it) => {
1336 });
1337
1338 expect(detail.viewerCanMerge).toBe(false);
1339 + expect(detail.viewerCanEditLabels).toBe(expected);
1340 + expect(mockedExecute).toHaveBeenCalledTimes(2);
1341 + }),
1342 + );
1343 +
1344 + it.effect(
1345 + "offers the project's and its groups' labels, marking those already applied, and keeps an applied label past the page",
1346 + () =>
1347 + Effect.gen(function* () {
1348 + mockedExecute.mockImplementation(({ args }) =>
1349 + Effect.succeed(
1350 + output(
1351 + args[1]?.includes("/labels?")
1352 + ? JSON.stringify([
1353 + { name: "bug", color: "#d9534f", description: "Something is broken" },
1354 + { name: "docs", color: null, description: null },
1355 + { name: "legacy", color: null, description: null, archived: true },
1356 + { name: "wontfix", color: null, description: null, archived: true },
1357 + ])
1358 + : mergeRequestJson({ labels: ["bug", "wontfix", "stale"] }),
1359 + ),
1360 + ),
1361 + );
1362 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1363 +
1364 + const list = yield* cli.listLabelCandidates({
1365 + cwd: "/w",
1366 + repository: "acme/web",
1367 + number: 7,
1368 + });
1369 +
1370 + expect(
1371 + mockedExecute.mock.calls
1372 + .map(([call]) => call.args[1])
1373 + .find((path) => path?.includes("/labels?")),
1374 + ).toBe("projects/acme%2Fweb/labels?per_page=100&include_ancestor_groups=true");
1375 + expect(list).toEqual({
1376 + candidates: [
1377 + { name: "stale", color: null, description: null, isApplied: true },
1378 + { name: "bug", color: "#d9534f", description: "Something is broken", isApplied: true },
1379 + { name: "docs", color: null, description: null, isApplied: false },
1380 + { name: "wontfix", color: null, description: null, isApplied: true },
1381 + ],
1382 + truncated: false,
1383 + });
1384 + }),
1385 + );
1386 +
1387 + it.effect("adds labels the project has in one write", () =>
1388 + Effect.gen(function* () {
1389 + mockedExecute.mockImplementation(({ args }) =>
1390 + Effect.succeed(
1391 + output(
1392 + args.includes("PUT")
1393 + ? "{}"
1394 + : JSON.stringify({
1395 + name: decodeURIComponent(args[1]?.split("/labels/")[1]?.split("?")[0] ?? ""),
1396 + color: null,
1397 + }),
1398 + ),
1399 + ),
1400 + );
1401 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1402 +
1403 + yield* cli.setLabels({
1404 + cwd: "/w",
1405 + repository: "acme/web",
1406 + number: 7,
1407 + labels: ["bug", "docs"],
1408 + applied: true,
1409 + });
1410 +
1411 + const write = mockedExecute.mock.calls.find(([call]) => call.args.includes("PUT"))?.[0];
1412 + assert.isDefined(write);
1413 + expect(write.args[1]).toBe("projects/acme%2Fweb/merge_requests/7");
1414 + expect(JSON.parse(write.stdin ?? "")).toEqual({ add_labels: "bug,docs" });
1415 + expect(argsOfCall(0)[1]).toBe("projects/acme%2Fweb/labels/bug?include_ancestor_groups=true");
1416 + }),
1417 + );
1418 +
1419 + it.effect("refuses to add a label the project lacks, since GitLab would create it", () =>
1420 + Effect.gen(function* () {
1421 + mockedExecute.mockImplementation(() =>
1422 + Effect.fail(
1423 + new GitLabCli.GitLabCliCommandError({
1424 + operation: "execute",
1425 + command: "glab",
1426 + cwd: "/w",
1427 + cause: new VcsProcessExitError({
1428 + operation: "GitLabCli.execute",
1429 + command: "glab",
1430 + cwd: "/w",
1431 + exitCode: 1,
1432 + detail: "404 Label Not Found",
1433 + failureKind: "not-found",
1434 + }),
1435 + }),
1436 + ),
1437 + );
1438 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1439 +
1440 + const result = yield* cli
1441 + .setLabels({ cwd: "/w", repository: "acme/web", number: 7, labels: ["bug"], applied: true })
1442 + .pipe(Effect.flip);
1443 +
1444 + expect(result).toMatchObject({ _tag: "GitLabUnknownLabelError", labels: ["bug"] });
1445 + expect(argsOfCall(0)[1]).toBe("projects/acme%2Fweb/labels/bug?include_ancestor_groups=true");
1446 + expect(mockedExecute.mock.calls.some(([call]) => call.args.includes("PUT"))).toBe(false);
1447 + }),
1448 + );
1449 +
1450 + it.effect("removes labels without looking them up", () =>
1451 + Effect.gen(function* () {
1452 + mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
1453 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
1454 +
1455 + yield* cli.setLabels({
1456 + cwd: "/w",
1457 + repository: "acme/web",
1458 + number: 7,
1459 + labels: ["bug"],
1460 + applied: false,
1461 + });
1462 +
1463 expect(mockedExecute).toHaveBeenCalledTimes(1);
1464 + expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ remove_labels: "bug" });
1465 }),
1466 );
1467
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+177 -23
@@ -14,6 +14,7 @@ import type {
14 PullRequestCommit,
15 PullRequestInvolvement,
16 PullRequestLabel,
17 + PullRequestLabelCandidateList,
18 PullRequestListFilters,
19 PullRequestListState,
20 PullRequestMergeCapabilities,
@@ -36,6 +37,8 @@ import {
37 decodeCommitsJson,
38 decodeDiffRefsJson,
39 decodeDiscussionsJson,
40 + decodeLabelNameJson,
41 + decodeLabelPermissionJson,
42 decodeMergeMessagesJson,
43 decodeMergeRequestDetailJson,
44 decodeMergeRequestDiffsJson,
@@ -53,6 +56,7 @@ import {
56 decodeTriggerJobChecksJson,
57 decodeViewerJson,
58 gitLabAwardName,
59 + LABEL_PERMISSION_GRAPHQL_QUERY,
60 MERGE_MESSAGES_GRAPHQL_QUERY,
61 MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
62 MERGE_REQUEST_STATS_GRAPHQL_QUERY,
@@ -189,9 +193,27 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G
193 }
194 }
195
196 +export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()(
197 + "GitLabUnknownLabelError",
198 + {
199 + command: Schema.Literal("glab"),
200 + cwd: Schema.String,
201 + labels: Schema.Array(Schema.String),
202 + },
203 +) {
204 + get detail(): string {
205 + return `The project has no label named ${this.labels.map((label) => `"${label}"`).join(", ")}.`;
206 + }
207 +
208 + override get message(): string {
209 + return `GitLab CLI failed in setLabels: ${this.detail}`;
210 + }
211 +}
212 +
213 export type GitLabPullRequestCliError =
214 | GitLabCli.GitLabCliError
215 | GitLabMergeRequestReadError
216 + | GitLabUnknownLabelError
217 | GitLabDiffCursorError
218 | GitLabDiffCommitError
219 | GitLabDiffCommitParentUnavailableError
@@ -364,6 +386,22 @@ export class GitLabPullRequestCli extends Context.Service<
386 GitLabPullRequestCliError
387 >;
388
389 + readonly listLabelCandidates: (input: {
390 + readonly cwd: string;
391 + readonly host?: string | undefined;
392 + readonly repository: string;
393 + readonly number: number;
394 + }) => Effect.Effect<PullRequestLabelCandidateList, GitLabPullRequestCliError>;
395 +
396 + readonly setLabels: (input: {
397 + readonly cwd: string;
398 + readonly host?: string | undefined;
399 + readonly repository: string;
400 + readonly number: number;
401 + readonly labels: ReadonlyArray<string>;
402 + readonly applied: boolean;
403 + }) => Effect.Effect<void, GitLabPullRequestCliError>;
404 +
405 readonly listProjectUsers: (input: {
406 readonly cwd: string;
407 readonly host?: string | undefined;
@@ -1150,6 +1188,39 @@ export const make = Effect.gen(function* () {
1188 /** The stats connection hands back one page, so a repository's rows are asked for 100 at a time. */
1189 const STAT_IIDS_PER_REQUEST = 100;
1190
1191 + const projectLabels = (input: {
1192 + readonly cwd: string;
1193 + readonly host?: string | undefined;
1194 + readonly repository: string;
1195 + readonly search?: string | undefined;
1196 + }) =>
1197 + api({
1198 + cwd: input.cwd,
1199 + host: input.host,
1200 + path: `projects/${projectPath(input.repository)}/labels?${query([
1201 + ["per_page", String(MAX_PAGE_SIZE)],
1202 + ["include_ancestor_groups", "true"],
1203 + ...searchParams(input.search),
1204 + ])}`,
1205 + }).pipe(
1206 + Effect.flatMap((result) => {
1207 + const decoded = decodeProjectLabelsJson(result.stdout.trim());
1208 + return Result.isSuccess(decoded)
1209 + ? Effect.succeed({
1210 + labels: decoded.success.labels,
1211 + truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
1212 + })
1213 + : Effect.fail(
1214 + new GitLabMergeRequestReadError({
1215 + command: "glab",
1216 + cwd: input.cwd,
1217 + operation: "listProjectLabels",
1218 + cause: decoded.failure,
1219 + }),
1220 + );
1221 + }),
1222 + );
1223 +
1224 const graphqlRead = <A>(input: {
1225 readonly cwd: string;
1226 readonly host?: string | undefined;
@@ -1180,6 +1251,30 @@ export const make = Effect.gen(function* () {
1251 }),
1252 );
1253
1254 + const labelPermission = (input: {
1255 + readonly cwd: string;
1256 + readonly host?: string | undefined;
1257 + readonly repository: string;
1258 + readonly number: number;
1259 + }) =>
1260 + graphqlRead({
1261 + cwd: input.cwd,
1262 + host: input.host,
1263 + operation: "getLabelPermission",
1264 + query: LABEL_PERMISSION_GRAPHQL_QUERY,
1265 + variables: { fullPath: input.repository, iid: String(input.number) },
1266 + decode: decodeLabelPermissionJson,
1267 + }).pipe(
1268 + // The answer gates one optional control; an unusable CLI or account still surfaces.
1269 + Effect.catchIf(
1270 + (cause) =>
1271 + cause._tag !== "GitLabCliUnavailableError" &&
1272 + cause._tag !== "GitLabCliAuthenticationError" &&
1273 + cause._tag !== "GitLabCliRateLimitError",
1274 + () => Effect.succeed(false),
1275 + ),
1276 + );
1277 +
1278 const mergeRequestStats = (input: {
1279 readonly cwd: string;
1280 readonly host?: string | undefined;
@@ -1367,7 +1462,11 @@ export const make = Effect.gen(function* () {
1462
1463 getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")(
1464 function* (input) {
1370 - const detail = yield* mergeRequestDetail(input);
1465 + const [read, viewerCanEditLabels] = yield* Effect.all(
1466 + [mergeRequestDetail(input), labelPermission(input)],
1467 + { concurrency: 2 },
1468 + );
1469 + const detail = { ...read, viewerCanEditLabels };
1470 if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
1471 const downstream = yield* triggerJobChecks({
1472 cwd: input.cwd,
@@ -1574,31 +1673,86 @@ export const make = Effect.gen(function* () {
1673 ),
1674
1675 listProjectLabels: Effect.fn("GitLabPullRequestCli.listProjectLabels")(function (input) {
1577 - return api({
1676 + return projectLabels(input).pipe(
1677 + Effect.map(({ labels, truncated }) => ({
1678 + items: labels.map(({ name, color }) => ({ name, color })),
1679 + truncated,
1680 + })),
1681 + );
1682 + }),
1683 +
1684 + listLabelCandidates: Effect.fn("GitLabPullRequestCli.listLabelCandidates")(function* (input) {
1685 + const [mergeRequest, project] = yield* Effect.all(
1686 + [mergeRequestDetail(input), projectLabels(input)],
1687 + { concurrency: 2 },
1688 + );
1689 + const applied = new Set(mergeRequest.labels.map((label) => label.name));
1690 + const listed = new Set(project.labels.map((label) => label.name));
1691 + return {
1692 + // GitLab's own picker hides archived labels. Applied ones stay so they can be removed,
1693 + // as do applied labels past the project's first page.
1694 + candidates: [
1695 + ...mergeRequest.labels
1696 + .filter((label) => !listed.has(label.name))
1697 + .map((label) => ({ ...label, description: null, isApplied: true })),
1698 + ...project.labels
1699 + .filter((label) => !label.archived || applied.has(label.name))
1700 + .map(({ archived: _archived, ...label }) => ({
1701 + ...label,
1702 + isApplied: applied.has(label.name),
1703 + })),
1704 + ],
1705 + truncated: project.truncated,
1706 + };
1707 + }),
1708 +
1709 + setLabels: Effect.fn("GitLabPullRequestCli.setLabels")(function* (input) {
1710 + if (input.applied) {
1711 + // GitLab creates any label it is asked to add that the project does not have yet.
1712 + const found = yield* Effect.forEach(
1713 + input.labels,
1714 + (label) =>
1715 + api({
1716 + cwd: input.cwd,
1717 + host: input.host,
1718 + path: `projects/${projectPath(input.repository)}/labels/${encodeURIComponent(label)}?${query(
1719 + [["include_ancestor_groups", "true"]],
1720 + )}`,
1721 + }).pipe(
1722 + // The lookup also matches a numeric id, so the returned name must be the one asked for.
1723 + Effect.map((result) => {
1724 + const decoded = decodeLabelNameJson(result.stdout.trim());
1725 + return Result.isSuccess(decoded) && decoded.success === label;
1726 + }),
1727 + Effect.catchTags({
1728 + GitLabCliCommandError: (error) =>
1729 + isVcsProcessExitError(error.cause) && error.cause.failureKind === "not-found"
1730 + ? Effect.succeed(false)
1731 + : Effect.fail(error),
1732 + }),
1733 + ),
1734 + { concurrency: 4 },
1735 + );
1736 + const unknown = input.labels.filter((_, index) => !found[index]);
1737 + if (unknown.length > 0) {
1738 + return yield* new GitLabUnknownLabelError({
1739 + command: "glab",
1740 + cwd: input.cwd,
1741 + labels: unknown,
1742 + });
1743 + }
1744 + }
1745 + yield* api({
1746 cwd: input.cwd,
1747 host: input.host,
1580 - path: `projects/${projectPath(input.repository)}/labels?${query([
1581 - ["per_page", String(MAX_PAGE_SIZE)],
1582 - ...searchParams(input.search),
1583 - ])}`,
1584 - }).pipe(
1585 - Effect.flatMap((result) => {
1586 - const decoded = decodeProjectLabelsJson(result.stdout.trim());
1587 - return Result.isSuccess(decoded)
1588 - ? Effect.succeed({
1589 - items: decoded.success.labels,
1590 - truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
1591 - })
1592 - : Effect.fail(
1593 - new GitLabMergeRequestReadError({
1594 - command: "glab",
1595 - cwd: input.cwd,
1596 - operation: "listProjectLabels",
1597 - cause: decoded.failure,
1598 - }),
1599 - );
1748 + path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1749 + method: "PUT",
1750 + // GitLab label names cannot contain a comma.
1751 + // @effect-diagnostics-next-line globalJsonInEffect:off
1752 + stdin: JSON.stringify({
1753 + [input.applied ? "add_labels" : "remove_labels"]: input.labels.join(","),
1754 }),
1601 - );
1755 + });
1756 }),
1757
1758 listProjectUsers: Effect.fn("GitLabPullRequestCli.listProjectUsers")(function (input) {
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+19 -4
@@ -42,6 +42,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
42 ],
43 },
44 mergeRequest: {
45 + userPermissions: { adminMergeRequest: true },
46 diffStatsSummary: { fileCount: 1 },
47 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
48 },
@@ -112,7 +113,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
113 yield* provider.searchRepositoryAuthors(reference);
114 yield* provider.runAction({ ...reference, action });
115
115 - expect(readHosts).toEqual(Array(action === "merge" ? 12 : 11).fill(selectedHost));
116 + expect(readHosts).toEqual(Array(action === "merge" ? 14 : 13).fill(selectedHost));
117 expect({ url: detail.url, mutatedHosts: mergedHosts }).toEqual({
118 url: `https://${selectedHost}/acme/web/-/merge_requests/7`,
119 mutatedHosts: [selectedHost],
@@ -122,7 +123,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
123
124 describe("gitLabViewerPermissions", () => {
125 it("offers everything to a viewer GitLab says can merge", () => {
125 - expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
126 + expect(gitLabViewerPermissions({ viewerCanMerge: true, viewerCanEditLabels: true })).toEqual({
127 actions: [
128 "merge",
129 "ready",
@@ -137,6 +138,7 @@ describe("gitLabViewerPermissions", () => {
138 resolve: true,
139 verdicts: ["comment", "approve"],
140 requestReviewers: true,
141 + labels: true,
142 updateMethods: ["rebase"],
143 });
144 });
@@ -148,6 +150,7 @@ describe("gitLabViewerPermissions", () => {
150 resolve: true,
151 verdicts: ["comment", "approve"],
152 requestReviewers: true,
153 + labels: false,
154 });
155 });
156 });
@@ -348,6 +351,7 @@ describe("merge request reads", () => {
351 return { merge: true, squash: true, rebase: true };
352 }),
353 runMergeRequestAction: () => Effect.void,
354 + setLabels: () => Effect.void,
355 }),
356 ),
357 );
@@ -387,12 +391,23 @@ describe("merge request reads", () => {
391 }),
392 );
393
390 - it.effect("reads a merge request again after a write to it", () =>
394 + it.effect.each([
395 + {
396 + write: "runAction",
397 + run: (provider: Effect.Success<typeof make>) =>
398 + provider.runAction({ ...reference, action: "ready" }),
399 + },
400 + {
401 + write: "setLabels",
402 + run: (provider: Effect.Success<typeof make>) =>
403 + provider.setLabels?.({ ...reference, labels: ["bug"], applied: true }) ?? Effect.void,
404 + },
405 + ])("reads a merge request again after $write", ({ run }) =>
406 Effect.gen(function* () {
407 const { provider, checks, calls } = yield* countingProvider;
408
409 yield* provider.getChangeRequest(reference);
395 - yield* provider.runAction({ ...reference, action: "ready" });
410 + yield* run(provider);
411 yield* checks(reference);
412
413 expect(calls.detail).toBe(2);
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+26
@@ -41,6 +41,7 @@ const CAPABILITIES: PullRequestCapabilities = {
41 verdicts: ["comment", "approve"],
42 },
43 reviewers: { request: true, listCandidates: true },
44 + labels: true,
45 edit: { changeRequest: true, comment: true },
46 };
47
@@ -65,6 +66,7 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([
66 /** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
67 export function gitLabViewerPermissions(input: {
68 readonly viewerCanMerge: boolean;
69 + readonly viewerCanEditLabels?: boolean | undefined;
70 }): PullRequestViewerPermissions {
71 return {
72 actions: CAPABILITIES.actions.filter(
@@ -74,6 +76,7 @@ export function gitLabViewerPermissions(input: {
76 resolve: true,
77 verdicts: CAPABILITIES.review.verdicts,
78 requestReviewers: true,
79 + labels: input.viewerCanEditLabels === true,
80 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
81 };
82 }
@@ -412,6 +415,29 @@ export const make = Effect.gen(function* () {
415 })
416 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
417
418 + listLabelCandidates: (input) =>
419 + cli
420 + .listLabelCandidates({
421 + cwd: input.cwd,
422 + host: input.host,
423 + repository: input.repository,
424 + number: input.number,
425 + })
426 + .pipe(Effect.mapError(fail("listLabelCandidates"))),
427 +
428 + setLabels: writing((input) =>
429 + cli
430 + .setLabels({
431 + cwd: input.cwd,
432 + host: input.host,
433 + repository: input.repository,
434 + number: input.number,
435 + labels: input.labels,
436 + applied: input.applied,
437 + })
438 + .pipe(Effect.mapError(fail("setLabels"))),
439 + ),
440 +
441 listRepositoryLabels: (input) =>
442 cli
443 .listProjectLabels({
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+58 -3
@@ -201,6 +201,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
201 readonly reviewers: ReadonlyArray<PullRequestActor>;
202 readonly checks: ReadonlyArray<PullRequestCheck>;
203 readonly viewerCanMerge: boolean;
204 + /** Set by the detail read, which asks GraphQL; REST carries no label permission. */
205 + readonly viewerCanEditLabels?: boolean;
206 readonly reviewerIds: ReadonlyArray<number>;
207 readonly autoMergeEnabled?: boolean;
208 readonly autoMergeMethod?: PullRequestMergeMethod;
@@ -480,11 +482,23 @@ export function decodeProjectUsersJson(
482 const RawLabelSchema = Schema.Struct({
483 name: Schema.String,
484 color: Schema.optional(Schema.NullOr(Schema.String)),
485 + description: Schema.optional(Schema.NullOr(Schema.String)),
486 + archived: Schema.optional(Schema.Boolean),
487 });
488 const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
489 +const decodeLabel = decodeJsonResult(RawLabelSchema);
490 +
491 +export function decodeLabelNameJson(raw: string): Result.Result<string | null, DecodeFailure> {
492 + return Result.map(decodeLabel(raw), (label) => trimmed(label.name));
493 +}
494 +
495 +export interface GitLabProjectLabel extends PullRequestLabel {
496 + readonly description: string | null;
497 + readonly archived: boolean;
498 +}
499
500 export interface GitLabProjectLabels {
487 - readonly labels: ReadonlyArray<PullRequestLabel>;
501 + readonly labels: ReadonlyArray<GitLabProjectLabel>;
502 readonly rawCount: number;
503 }
504
@@ -495,12 +509,19 @@ export function decodeProjectLabelsJson(
509 if (!Result.isSuccess(decoded)) {
510 return Result.fail(decoded.failure);
511 }
498 - const labels: PullRequestLabel[] = [];
512 + const labels: GitLabProjectLabel[] = [];
513 for (const entry of decoded.success) {
514 const label = decodeLabelEntry(entry);
515 if (Exit.isFailure(label)) continue;
516 const name = trimmed(label.value.name);
503 - if (name !== null) labels.push({ name, color: trimmed(label.value.color) });
517 + if (name !== null) {
518 + labels.push({
519 + name,
520 + color: trimmed(label.value.color),
521 + description: trimmed(label.value.description),
522 + archived: label.value.archived === true,
523 + });
524 + }
525 }
526 return Result.succeed({ labels, rawCount: decoded.success.length });
527 }
@@ -1216,6 +1237,40 @@ export function decodeMergeRequestStatsJson(
1237 return Result.succeed(stats);
1238 }
1239
1240 +/** GitLab lets whoever may change a merge request's metadata set its labels. */
1241 +export const LABEL_PERMISSION_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
1242 + project(fullPath: $fullPath) {
1243 + mergeRequest(iid: $iid) {
1244 + userPermissions { adminMergeRequest }
1245 + }
1246 + }
1247 +}`;
1248 +
1249 +const decodeLabelPermission = decodeJsonResult(
1250 + Schema.Struct({
1251 + data: Schema.Struct({
1252 + project: Schema.NullOr(
1253 + Schema.Struct({
1254 + mergeRequest: Schema.NullOr(
1255 + Schema.Struct({
1256 + userPermissions: Schema.Struct({ adminMergeRequest: Schema.Boolean }),
1257 + }),
1258 + ),
1259 + }),
1260 + ),
1261 + }),
1262 + }),
1263 +);
1264 +
1265 +export function decodeLabelPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
1266 + const decoded = decodeLabelPermission(raw);
1267 + return Result.isSuccess(decoded)
1268 + ? Result.succeed(
1269 + decoded.success.data.project?.mergeRequest?.userPermissions.adminMergeRequest === true,
1270 + )
1271 + : Result.fail(decoded.failure);
1272 +}
1273 +
1274 /** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */
1275 export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
1276 project(fullPath: $fullPath) {