Skip to content
TypeScript

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

Antony444921eb71df
diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts
index 37ba0225340..f4571c44b03 100644
--- a/packages/client-runtime/src/state/pullRequests.test.ts
+++ b/packages/client-runtime/src/state/pullRequests.test.ts
@@ -2100,7 +2100,7 @@ it.effect("updates cached labels after successful edits without rereading the ho
host: "github.example.com",
},
};
- const detail = atoms.detail(target);
+ const detail = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
const candidates = atoms.labelCandidates(target);
registry.mount(detail);
const unmountCandidates = registry.mount(candidates);
diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts
index 3dc2710d96f..0669421585e 100644
--- a/packages/client-runtime/src/state/pullRequests.ts
+++ b/packages/client-runtime/src/state/pullRequests.ts
@@ -518,6 +518,16 @@ export function createPullRequestEnvironmentAtoms<R, E>(
},
),
);
+ // Pages read the strict detail and other surfaces the default one; patch whichever is loaded
+ // without starting a read of the other.
+ const loadedDetails = (
+ registry: AtomRegistry.AtomRegistry,
+ target: { readonly environmentId: EnvironmentId; readonly input: PullRequestRef },
+ ) =>
+ [
+ detail({ ...target, input: { ...target.input, allowStale: undefined } }),
+ detail({ ...target, input: { ...target.input, allowStale: false } }),
+ ].filter((atom) => registry.getNodes().has(atom));
const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
Atom.family((answer: ReturnType<typeof detailAnswers>) =>
Atom.make((get) => {
@@ -950,15 +960,17 @@ export function createPullRequestEnvironmentAtoms<R, E>(
: actors.filter(
(actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
);
- updateCached(
- registry,
- detail(target),
- (value) => ({
- ...value,
- reviewers: updateReviewers(value.reviewers),
- }),
- missingIdentities,
- );
+ for (const atom of loadedDetails(registry, target)) {
+ updateCached(
+ registry,
+ atom,
+ (value) => ({
+ ...value,
+ reviewers: updateReviewers(value.reviewers),
+ }),
+ missingIdentities,
+ );
+ }
updateCached(
registry,
activity(target),
@@ -1008,22 +1020,24 @@ export function createPullRequestEnvironmentAtoms<R, E>(
names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
),
}));
- updateCached(registry, detail(target), (value) => ({
- ...value,
- labels: applied
- ? [
- ...value.labels,
- ...labels
- .filter((name) => !value.labels.some((label) => label.name === name))
- .map((name) => ({
- name,
- color:
- candidates?.candidates.find((candidate) => candidate.name === name)
- ?.color ?? null,
- })),
- ]
- : value.labels.filter((label) => !names.has(label.name)),
- }));
+ for (const atom of loadedDetails(registry, target)) {
+ updateCached(registry, atom, (value) => ({
+ ...value,
+ labels: applied
+ ? [
+ ...value.labels,
+ ...labels
+ .filter((name) => !value.labels.some((label) => label.name === name))
+ .map((name) => ({
+ name,
+ color:
+ candidates?.candidates.find((candidate) => candidate.name === name)
+ ?.color ?? null,
+ })),
+ ]
+ : value.labels.filter((label) => !names.has(label.name)),
+ }));
+ }
}),
}),
setThreadResolution: createEnvironmentRpcCommand(runtime, {
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index 231cb8db3cb..cefa878781a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -1,4 +1,5 @@
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
+import { VcsProcessExitError } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ChildProcessSpawner } from "effect/process";
@@ -65,6 +66,11 @@ function notes(count: number, firstId: number): string {
}
const author = { id: 1, username: "bilal" };
+const labelPermission = output(
+ JSON.stringify({
+ data: { project: { mergeRequest: { userPermissions: { adminMergeRequest: false } } } },
+ }),
+);
const reviewer = { id: 5, username: "octocat" };
function mergeRequestJson(overrides: Record<string, unknown>): string {
@@ -1223,6 +1229,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
),
),
)
+ .mockReturnValueOnce(Effect.succeed(labelPermission))
.mockReturnValueOnce(
Effect.succeed(
output(
@@ -1252,7 +1259,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
["Pipeline", "success", "https://gitlab.com/bilal/web/-/pipelines/31"],
["deploy", "failure", "https://gitlab.com/bilal/web/-/pipelines/32"],
]);
- expect(argsOfCall(1)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
+ expect(argsOfCall(2)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
}),
);
@@ -1264,6 +1271,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
const failedChild = { name: "deploy", downstream_pipeline: { status: "failed" } };
mockedExecute
.mockReturnValueOnce(Effect.succeed(detailOutput))
+ .mockReturnValueOnce(Effect.succeed(labelPermission))
.mockReturnValueOnce(
Effect.fail(
new GitLabCli.GitLabCliCommandError({
@@ -1275,6 +1283,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
),
)
.mockReturnValueOnce(Effect.succeed(detailOutput))
+ .mockReturnValueOnce(Effect.succeed(labelPermission))
// A full page may have left out the trigger job whose pipeline failed.
.mockReturnValueOnce(
Effect.succeed(output(JSON.stringify(Array.from({ length: 100 }, () => failedChild)))),
@@ -1295,15 +1304,25 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
- it.effect("reads merge permissions without reading the trigger jobs", () =>
+ it.effect.each([
+ {
+ answer: JSON.stringify({
+ data: { project: { mergeRequest: { userPermissions: { adminMergeRequest: true } } } },
+ }),
+ expected: true,
+ },
+ { answer: JSON.stringify({ errors: [{ message: "Field unknown" }] }), expected: false },
+ ])("reads merge and label permissions without reading the trigger jobs", ({ answer, expected }) =>
Effect.gen(function* () {
- mockedExecute.mockReturnValueOnce(
+ mockedExecute.mockImplementation(({ args }) =>
Effect.succeed(
output(
- mergeRequestJson({
- head_pipeline: { id: 31, project_id: 12, status: "success" },
- user: { can_merge: false },
- }),
+ args[1] === "graphql"
+ ? answer
+ : mergeRequestJson({
+ head_pipeline: { id: 31, project_id: 12, status: "success" },
+ user: { can_merge: false },
+ }),
),
),
);
@@ -1317,7 +1336,132 @@ layer("GitLabPullRequestCli.layer", (it) => {
});
expect(detail.viewerCanMerge).toBe(false);
+ expect(detail.viewerCanEditLabels).toBe(expected);
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
+ }),
+ );
+
+ it.effect(
+ "offers the project's and its groups' labels, marking those already applied, and keeps an applied label past the page",
+ () =>
+ Effect.gen(function* () {
+ mockedExecute.mockImplementation(({ args }) =>
+ Effect.succeed(
+ output(
+ args[1]?.includes("/labels?")
+ ? JSON.stringify([
+ { name: "bug", color: "#d9534f", description: "Something is broken" },
+ { name: "docs", color: null, description: null },
+ { name: "legacy", color: null, description: null, archived: true },
+ { name: "wontfix", color: null, description: null, archived: true },
+ ])
+ : mergeRequestJson({ labels: ["bug", "wontfix", "stale"] }),
+ ),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const list = yield* cli.listLabelCandidates({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ });
+
+ expect(
+ mockedExecute.mock.calls
+ .map(([call]) => call.args[1])
+ .find((path) => path?.includes("/labels?")),
+ ).toBe("projects/acme%2Fweb/labels?per_page=100&include_ancestor_groups=true");
+ expect(list).toEqual({
+ candidates: [
+ { name: "stale", color: null, description: null, isApplied: true },
+ { name: "bug", color: "#d9534f", description: "Something is broken", isApplied: true },
+ { name: "docs", color: null, description: null, isApplied: false },
+ { name: "wontfix", color: null, description: null, isApplied: true },
+ ],
+ truncated: false,
+ });
+ }),
+ );
+
+ it.effect("adds labels the project has in one write", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockImplementation(({ args }) =>
+ Effect.succeed(
+ output(
+ args.includes("PUT")
+ ? "{}"
+ : JSON.stringify({
+ name: decodeURIComponent(args[1]?.split("/labels/")[1]?.split("?")[0] ?? ""),
+ color: null,
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.setLabels({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ labels: ["bug", "docs"],
+ applied: true,
+ });
+
+ const write = mockedExecute.mock.calls.find(([call]) => call.args.includes("PUT"))?.[0];
+ assert.isDefined(write);
+ expect(write.args[1]).toBe("projects/acme%2Fweb/merge_requests/7");
+ expect(JSON.parse(write.stdin ?? "")).toEqual({ add_labels: "bug,docs" });
+ expect(argsOfCall(0)[1]).toBe("projects/acme%2Fweb/labels/bug?include_ancestor_groups=true");
+ }),
+ );
+
+ it.effect("refuses to add a label the project lacks, since GitLab would create it", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockImplementation(() =>
+ Effect.fail(
+ new GitLabCli.GitLabCliCommandError({
+ operation: "execute",
+ command: "glab",
+ cwd: "/w",
+ cause: new VcsProcessExitError({
+ operation: "GitLabCli.execute",
+ command: "glab",
+ cwd: "/w",
+ exitCode: 1,
+ detail: "404 Label Not Found",
+ failureKind: "not-found",
+ }),
+ }),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const result = yield* cli
+ .setLabels({ cwd: "/w", repository: "acme/web", number: 7, labels: ["bug"], applied: true })
+ .pipe(Effect.flip);
+
+ expect(result).toMatchObject({ _tag: "GitLabUnknownLabelError", labels: ["bug"] });
+ expect(argsOfCall(0)[1]).toBe("projects/acme%2Fweb/labels/bug?include_ancestor_groups=true");
+ expect(mockedExecute.mock.calls.some(([call]) => call.args.includes("PUT"))).toBe(false);
+ }),
+ );
+
+ it.effect("removes labels without looking them up", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.setLabels({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ labels: ["bug"],
+ applied: false,
+ });
+
expect(mockedExecute).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ remove_labels: "bug" });
}),
);
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index 7c386760b7a..7546e3ad532 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -14,6 +14,7 @@ import type {
PullRequestCommit,
PullRequestInvolvement,
PullRequestLabel,
+ PullRequestLabelCandidateList,
PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
@@ -36,6 +37,8 @@ import {
decodeCommitsJson,
decodeDiffRefsJson,
decodeDiscussionsJson,
+ decodeLabelNameJson,
+ decodeLabelPermissionJson,
decodeMergeMessagesJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
@@ -53,6 +56,7 @@ import {
decodeTriggerJobChecksJson,
decodeViewerJson,
gitLabAwardName,
+ LABEL_PERMISSION_GRAPHQL_QUERY,
MERGE_MESSAGES_GRAPHQL_QUERY,
MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
MERGE_REQUEST_STATS_GRAPHQL_QUERY,
@@ -189,9 +193,27 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G
}
}
+export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLabelError>()(
+ "GitLabUnknownLabelError",
+ {
+ command: Schema.Literal("glab"),
+ cwd: Schema.String,
+ labels: Schema.Array(Schema.String),
+ },
+) {
+ get detail(): string {
+ return `The project has no label named ${this.labels.map((label) => `"${label}"`).join(", ")}.`;
+ }
+
+ override get message(): string {
+ return `GitLab CLI failed in setLabels: ${this.detail}`;
+ }
+}
+
export type GitLabPullRequestCliError =
| GitLabCli.GitLabCliError
| GitLabMergeRequestReadError
+ | GitLabUnknownLabelError
| GitLabDiffCursorError
| GitLabDiffCommitError
| GitLabDiffCommitParentUnavailableError
@@ -364,6 +386,22 @@ export class GitLabPullRequestCli extends Context.Service<
GitLabPullRequestCliError
>;
+ readonly listLabelCandidates: (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ readonly repository: string;
+ readonly number: number;
+ }) => Effect.Effect<PullRequestLabelCandidateList, GitLabPullRequestCliError>;
+
+ readonly setLabels: (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ readonly repository: string;
+ readonly number: number;
+ readonly labels: ReadonlyArray<string>;
+ readonly applied: boolean;
+ }) => Effect.Effect<void, GitLabPullRequestCliError>;
+
readonly listProjectUsers: (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1150,6 +1188,39 @@ export const make = Effect.gen(function* () {
/** The stats connection hands back one page, so a repository's rows are asked for 100 at a time. */
const STAT_IIDS_PER_REQUEST = 100;
+ const projectLabels = (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ readonly repository: string;
+ readonly search?: string | undefined;
+ }) =>
+ api({
+ cwd: input.cwd,
+ host: input.host,
+ path: `projects/${projectPath(input.repository)}/labels?${query([
+ ["per_page", String(MAX_PAGE_SIZE)],
+ ["include_ancestor_groups", "true"],
+ ...searchParams(input.search),
+ ])}`,
+ }).pipe(
+ Effect.flatMap((result) => {
+ const decoded = decodeProjectLabelsJson(result.stdout.trim());
+ return Result.isSuccess(decoded)
+ ? Effect.succeed({
+ labels: decoded.success.labels,
+ truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
+ })
+ : Effect.fail(
+ new GitLabMergeRequestReadError({
+ command: "glab",
+ cwd: input.cwd,
+ operation: "listProjectLabels",
+ cause: decoded.failure,
+ }),
+ );
+ }),
+ );
+
const graphqlRead = <A>(input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1180,6 +1251,30 @@ export const make = Effect.gen(function* () {
}),
);
+ const labelPermission = (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ readonly repository: string;
+ readonly number: number;
+ }) =>
+ graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "getLabelPermission",
+ query: LABEL_PERMISSION_GRAPHQL_QUERY,
+ variables: { fullPath: input.repository, iid: String(input.number) },
+ decode: decodeLabelPermissionJson,
+ }).pipe(
+ // The answer gates one optional control; an unusable CLI or account still surfaces.
+ Effect.catchIf(
+ (cause) =>
+ cause._tag !== "GitLabCliUnavailableError" &&
+ cause._tag !== "GitLabCliAuthenticationError" &&
+ cause._tag !== "GitLabCliRateLimitError",
+ () => Effect.succeed(false),
+ ),
+ );
+
const mergeRequestStats = (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1367,7 +1462,11 @@ export const make = Effect.gen(function* () {
getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")(
function* (input) {
- const detail = yield* mergeRequestDetail(input);
+ const [read, viewerCanEditLabels] = yield* Effect.all(
+ [mergeRequestDetail(input), labelPermission(input)],
+ { concurrency: 2 },
+ );
+ const detail = { ...read, viewerCanEditLabels };
if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
const downstream = yield* triggerJobChecks({
cwd: input.cwd,
@@ -1574,31 +1673,86 @@ export const make = Effect.gen(function* () {
),
listProjectLabels: Effect.fn("GitLabPullRequestCli.listProjectLabels")(function (input) {
- return api({
+ return projectLabels(input).pipe(
+ Effect.map(({ labels, truncated }) => ({
+ items: labels.map(({ name, color }) => ({ name, color })),
+ truncated,
+ })),
+ );
+ }),
+
+ listLabelCandidates: Effect.fn("GitLabPullRequestCli.listLabelCandidates")(function* (input) {
+ const [mergeRequest, project] = yield* Effect.all(
+ [mergeRequestDetail(input), projectLabels(input)],
+ { concurrency: 2 },
+ );
+ const applied = new Set(mergeRequest.labels.map((label) => label.name));
+ const listed = new Set(project.labels.map((label) => label.name));
+ return {
+ // GitLab's own picker hides archived labels. Applied ones stay so they can be removed,
+ // as do applied labels past the project's first page.
+ candidates: [
+ ...mergeRequest.labels
+ .filter((label) => !listed.has(label.name))
+ .map((label) => ({ ...label, description: null, isApplied: true })),
+ ...project.labels
+ .filter((label) => !label.archived || applied.has(label.name))
+ .map(({ archived: _archived, ...label }) => ({
+ ...label,
+ isApplied: applied.has(label.name),
+ })),
+ ],
+ truncated: project.truncated,
+ };
+ }),
+
+ setLabels: Effect.fn("GitLabPullRequestCli.setLabels")(function* (input) {
+ if (input.applied) {
+ // GitLab creates any label it is asked to add that the project does not have yet.
+ const found = yield* Effect.forEach(
+ input.labels,
+ (label) =>
+ api({
+ cwd: input.cwd,
+ host: input.host,
+ path: `projects/${projectPath(input.repository)}/labels/${encodeURIComponent(label)}?${query(
+ [["include_ancestor_groups", "true"]],
+ )}`,
+ }).pipe(
+ // The lookup also matches a numeric id, so the returned name must be the one asked for.
+ Effect.map((result) => {
+ const decoded = decodeLabelNameJson(result.stdout.trim());
+ return Result.isSuccess(decoded) && decoded.success === label;
+ }),
+ Effect.catchTags({
+ GitLabCliCommandError: (error) =>
+ isVcsProcessExitError(error.cause) && error.cause.failureKind === "not-found"
+ ? Effect.succeed(false)
+ : Effect.fail(error),
+ }),
+ ),
+ { concurrency: 4 },
+ );
+ const unknown = input.labels.filter((_, index) => !found[index]);
+ if (unknown.length > 0) {
+ return yield* new GitLabUnknownLabelError({
+ command: "glab",
+ cwd: input.cwd,
+ labels: unknown,
+ });
+ }
+ }
+ yield* api({
cwd: input.cwd,
host: input.host,
- path: `projects/${projectPath(input.repository)}/labels?${query([
- ["per_page", String(MAX_PAGE_SIZE)],
- ...searchParams(input.search),
- ])}`,
- }).pipe(
- Effect.flatMap((result) => {
- const decoded = decodeProjectLabelsJson(result.stdout.trim());
- return Result.isSuccess(decoded)
- ? Effect.succeed({
- items: decoded.success.labels,
- truncated: decoded.success.rawCount >= MAX_PAGE_SIZE,
- })
- : Effect.fail(
- new GitLabMergeRequestReadError({
- command: "glab",
- cwd: input.cwd,
- operation: "listProjectLabels",
- cause: decoded.failure,
- }),
- );
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
+ method: "PUT",
+ // GitLab label names cannot contain a comma.
+ // @effect-diagnostics-next-line globalJsonInEffect:off
+ stdin: JSON.stringify({
+ [input.applied ? "add_labels" : "remove_labels"]: input.labels.join(","),
}),
- );
+ });
}),
listProjectUsers: Effect.fn("GitLabPullRequestCli.listProjectUsers")(function (input) {
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
index 7e687619963..d36565839a1 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
@@ -42,6 +42,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
],
},
mergeRequest: {
+ userPermissions: { adminMergeRequest: true },
diffStatsSummary: { fileCount: 1 },
diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
},
@@ -112,7 +113,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
yield* provider.searchRepositoryAuthors(reference);
yield* provider.runAction({ ...reference, action });
- expect(readHosts).toEqual(Array(action === "merge" ? 12 : 11).fill(selectedHost));
+ expect(readHosts).toEqual(Array(action === "merge" ? 14 : 13).fill(selectedHost));
expect({ url: detail.url, mutatedHosts: mergedHosts }).toEqual({
url: `https://${selectedHost}/acme/web/-/merge_requests/7`,
mutatedHosts: [selectedHost],
@@ -122,7 +123,7 @@ it.effect.each(["merge", "disable-auto-merge"] as const)(
describe("gitLabViewerPermissions", () => {
it("offers everything to a viewer GitLab says can merge", () => {
- expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
+ expect(gitLabViewerPermissions({ viewerCanMerge: true, viewerCanEditLabels: true })).toEqual({
actions: [
"merge",
"ready",
@@ -137,6 +138,7 @@ describe("gitLabViewerPermissions", () => {
resolve: true,
verdicts: ["comment", "approve"],
requestReviewers: true,
+ labels: true,
updateMethods: ["rebase"],
});
});
@@ -148,6 +150,7 @@ describe("gitLabViewerPermissions", () => {
resolve: true,
verdicts: ["comment", "approve"],
requestReviewers: true,
+ labels: false,
});
});
});
@@ -348,6 +351,7 @@ describe("merge request reads", () => {
return { merge: true, squash: true, rebase: true };
}),
runMergeRequestAction: () => Effect.void,
+ setLabels: () => Effect.void,
}),
),
);
@@ -387,12 +391,23 @@ describe("merge request reads", () => {
}),
);
- it.effect("reads a merge request again after a write to it", () =>
+ it.effect.each([
+ {
+ write: "runAction",
+ run: (provider: Effect.Success<typeof make>) =>
+ provider.runAction({ ...reference, action: "ready" }),
+ },
+ {
+ write: "setLabels",
+ run: (provider: Effect.Success<typeof make>) =>
+ provider.setLabels?.({ ...reference, labels: ["bug"], applied: true }) ?? Effect.void,
+ },
+ ])("reads a merge request again after $write", ({ run }) =>
Effect.gen(function* () {
const { provider, checks, calls } = yield* countingProvider;
yield* provider.getChangeRequest(reference);
- yield* provider.runAction({ ...reference, action: "ready" });
+ yield* run(provider);
yield* checks(reference);
expect(calls.detail).toBe(2);
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index 82712a2c5ef..6a7212bd45c 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -41,6 +41,7 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve"],
},
reviewers: { request: true, listCandidates: true },
+ labels: true,
edit: { changeRequest: true, comment: true },
};
@@ -65,6 +66,7 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([
/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
export function gitLabViewerPermissions(input: {
readonly viewerCanMerge: boolean;
+ readonly viewerCanEditLabels?: boolean | undefined;
}): PullRequestViewerPermissions {
return {
actions: CAPABILITIES.actions.filter(
@@ -74,6 +76,7 @@ export function gitLabViewerPermissions(input: {
resolve: true,
verdicts: CAPABILITIES.review.verdicts,
requestReviewers: true,
+ labels: input.viewerCanEditLabels === true,
...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -412,6 +415,29 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("listReviewerCandidates"))),
+ listLabelCandidates: (input) =>
+ cli
+ .listLabelCandidates({
+ cwd: input.cwd,
+ host: input.host,
+ repository: input.repository,
+ number: input.number,
+ })
+ .pipe(Effect.mapError(fail("listLabelCandidates"))),
+
+ setLabels: writing((input) =>
+ cli
+ .setLabels({
+ cwd: input.cwd,
+ host: input.host,
+ repository: input.repository,
+ number: input.number,
+ labels: input.labels,
+ applied: input.applied,
+ })
+ .pipe(Effect.mapError(fail("setLabels"))),
+ ),
+
listRepositoryLabels: (input) =>
cli
.listProjectLabels({
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 3f492bf20ee..b514b018e84 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -201,6 +201,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly reviewers: ReadonlyArray<PullRequestActor>;
readonly checks: ReadonlyArray<PullRequestCheck>;
readonly viewerCanMerge: boolean;
+ /** Set by the detail read, which asks GraphQL; REST carries no label permission. */
+ readonly viewerCanEditLabels?: boolean;
readonly reviewerIds: ReadonlyArray<number>;
readonly autoMergeEnabled?: boolean;
readonly autoMergeMethod?: PullRequestMergeMethod;
@@ -480,11 +482,23 @@ export function decodeProjectUsersJson(
const RawLabelSchema = Schema.Struct({
name: Schema.String,
color: Schema.optional(Schema.NullOr(Schema.String)),
+ description: Schema.optional(Schema.NullOr(Schema.String)),
+ archived: Schema.optional(Schema.Boolean),
});
const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
+const decodeLabel = decodeJsonResult(RawLabelSchema);
+
+export function decodeLabelNameJson(raw: string): Result.Result<string | null, DecodeFailure> {
+ return Result.map(decodeLabel(raw), (label) => trimmed(label.name));
+}
+
+export interface GitLabProjectLabel extends PullRequestLabel {
+ readonly description: string | null;
+ readonly archived: boolean;
+}
export interface GitLabProjectLabels {
- readonly labels: ReadonlyArray<PullRequestLabel>;
+ readonly labels: ReadonlyArray<GitLabProjectLabel>;
readonly rawCount: number;
}
@@ -495,12 +509,19 @@ export function decodeProjectLabelsJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
- const labels: PullRequestLabel[] = [];
+ const labels: GitLabProjectLabel[] = [];
for (const entry of decoded.success) {
const label = decodeLabelEntry(entry);
if (Exit.isFailure(label)) continue;
const name = trimmed(label.value.name);
- if (name !== null) labels.push({ name, color: trimmed(label.value.color) });
+ if (name !== null) {
+ labels.push({
+ name,
+ color: trimmed(label.value.color),
+ description: trimmed(label.value.description),
+ archived: label.value.archived === true,
+ });
+ }
}
return Result.succeed({ labels, rawCount: decoded.success.length });
}
@@ -1216,6 +1237,40 @@ export function decodeMergeRequestStatsJson(
return Result.succeed(stats);
}
+/** GitLab lets whoever may change a merge request's metadata set its labels. */
+export const LABEL_PERMISSION_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
+ project(fullPath: $fullPath) {
+ mergeRequest(iid: $iid) {
+ userPermissions { adminMergeRequest }
+ }
+ }
+}`;
+
+const decodeLabelPermission = decodeJsonResult(
+ Schema.Struct({
+ data: Schema.Struct({
+ project: Schema.NullOr(
+ Schema.Struct({
+ mergeRequest: Schema.NullOr(
+ Schema.Struct({
+ userPermissions: Schema.Struct({ adminMergeRequest: Schema.Boolean }),
+ }),
+ ),
+ }),
+ ),
+ }),
+ }),
+);
+
+export function decodeLabelPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
+ const decoded = decodeLabelPermission(raw);
+ return Result.isSuccess(decoded)
+ ? Result.succeed(
+ decoded.success.data.project?.mergeRequest?.userPermissions.adminMergeRequest === true,
+ )
+ : Result.fail(decoded.failure);
+}
+
/** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */
export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
project(fullPath: $fullPath) {