Skip to content
TypeScript

fix(pull-requests): list filters narrow on every host that can (#23922)

Julius Marminge7beaa01a32bb
diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.ts
index 1f63a559c89..bf9d359b0e3 100644
--- a/packages/contracts/src/pullRequest.test.ts
+++ b/packages/contracts/src/pullRequest.test.ts
@@ -2,7 +2,12 @@ import { SourceControlProviderKind } from "./sourceControl.ts";
import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
-import { PullRequestDetail, PullRequestListResult, pullRequestHostOf } from "./pullRequest.ts";
+import {
+ PullRequestDetail,
+ PullRequestListResult,
+ pullRequestHostOf,
+ resolvePullRequestAuthorFilter,
+} from "./pullRequest.ts";
const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(PullRequestDetail));
@@ -144,3 +149,20 @@ describe("PullRequestCapabilities", () => {
expect(decoded.title).toBe(detail.title);
});
});
+
+describe("resolvePullRequestAuthorFilter", () => {
+ it("reads me as the signed-in account on the host", () => {
+ expect(resolvePullRequestAuthorFilter("me", "bilal")).toBe("bilal");
+ expect(resolvePullRequestAuthorFilter(" @Me ", "bilal")).toBe("bilal");
+ });
+
+ it("keeps me as a literal login when the host has no viewer", () => {
+ expect(resolvePullRequestAuthorFilter("me", null)).toBe("me");
+ expect(resolvePullRequestAuthorFilter("@me", " ")).toBe("@me");
+ });
+
+ it("passes any other login through trimmed", () => {
+ expect(resolvePullRequestAuthorFilter(" ana ", "bilal")).toBe("ana");
+ expect(resolvePullRequestAuthorFilter("meredith", "bilal")).toBe("meredith");
+ });
+});
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts
index 5e75e6269c9..4b2e46b5a1e 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts
@@ -201,6 +201,27 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
+ it.effect("asks Azure for the author's pull requests by creator", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
+
+ yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "web",
+ state: "open",
+ involvement: "reviewing",
+ viewer: "[email protected]",
+ limit: 10,
+ author: "[email protected]",
+ });
+
+ const args = argsOfCall(0);
+ assert.strictEqual(args[args.indexOf("--creator") + 1], "[email protected]");
+ assert.strictEqual(args[args.indexOf("--reviewer") + 1], "[email protected]");
+ }),
+ );
+
it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
Effect.gen(function* () {
mockedExecute
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
index d0b1a74dc72..cb14afba2bb 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
@@ -150,6 +150,8 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly limit: number;
+ /** Matched by `--creator`, which takes the email a row shows as its login. */
+ readonly author?: string | undefined;
/**
* Where to carry on from. Azure has no date filter for a pull request listing, so the only
* part of a cursor it can use is how many rows have already been handed over.
@@ -403,6 +405,7 @@ export const make = Effect.gen(function* () {
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
+ readonly author?: string | undefined;
readonly limit: number;
readonly skip: number;
readonly cursorAdvance: number;
@@ -429,6 +432,9 @@ export const make = Effect.gen(function* () {
input.repository,
...statusArgs(input.state),
...involvementArgs(input),
+ ...(input.author === undefined || input.involvement === "authored"
+ ? []
+ : ["--creator", input.author]),
"--include-links",
...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
"--top",
@@ -546,6 +552,7 @@ export const make = Effect.gen(function* () {
state: input.state,
involvement: input.involvement,
viewer: input.viewer,
+ author: input.author,
limit: input.limit,
skip: input.cursor?.delivered ?? 0,
cursorAdvance: 0,
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
index fa673261960..ce872c7c165 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
@@ -1,4 +1,4 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
+import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Semaphore from "effect/Semaphore";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
@@ -275,6 +275,10 @@ export const make = Effect.gen(function* () {
viewer: input.viewer,
limit: input.limit,
cursor: input.cursor,
+ author:
+ input.filters?.author === undefined
+ ? undefined
+ : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.test.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.test.ts
index 1dafdb02b24..719c5279238 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.test.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.test.ts
@@ -157,6 +157,25 @@ layer("BitbucketPullRequestApi.layer", (it) => {
}),
);
+ it.effect("narrows by author and draft state in the same query", () =>
+ Effect.gen(function* () {
+ mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
+
+ yield* api.listPullRequests({
+ repository: "acme/web",
+ state: "open",
+ limit: 50,
+ author: 'ana"',
+ draft: false,
+ });
+
+ expect(filterOfCall(0)).toBe(
+ '(author.nickname = "ana\\"" OR author.display_name = "ana\\"") AND draft = false',
+ );
+ }),
+ );
+
it.effect("refuses a repository that is not workspace and slug", () =>
Effect.gen(function* () {
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
index c144424ef22..7958c982904 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
@@ -147,6 +147,9 @@ export class BitbucketPullRequestApi extends Context.Service<
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ /** Matched against the login a row shows, which is the nickname or else the display name. */
+ readonly author?: string | undefined;
+ readonly draft?: boolean | undefined;
}) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
readonly getPullRequest: (input: {
@@ -329,6 +332,11 @@ function searchFilter(query: string): string {
return `(title ~ "${literal}" OR description ~ "${literal}")`;
}
+function authorFilter(login: string): string {
+ const literal = filterLiteral(login);
+ return `(author.nickname = "${literal}" OR author.display_name = "${literal}")`;
+}
+
/**
* The backslash is escaped first, or escaping the quote would only produce a literal
* backslash followed by a live quote.
@@ -565,6 +573,8 @@ export const make = Effect.gen(function* () {
// Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
const predicates = [
...(search.length === 0 ? [] : [searchFilter(search)]),
+ ...(input.author === undefined ? [] : [authorFilter(input.author)]),
+ ...(input.draft === undefined ? [] : [`draft = ${input.draft}`]),
...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
];
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
index a266a328d62..619b138ded5 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
@@ -1,4 +1,4 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
+import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
@@ -158,6 +158,11 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
+ author:
+ input.filters?.author === undefined
+ ? undefined
+ : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
+ draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only",
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
index e8bf016955b..cbcc294ede8 100644
--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
@@ -1,4 +1,4 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
+import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Result from "effect/Result";
@@ -254,13 +254,36 @@ export const make = Effect.gen(function* () {
const offset = input.cursor?.delivered ?? 0;
const items: ReturnType<typeof forgejoChangeRequest>[] = [];
const state = input.state === "merged" ? "closed" : input.state;
- const query = {
- ...input,
- path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,
- };
+ const params = new URLSearchParams({ state, sort: "recentupdate" });
+ const filters = input.filters;
+ // Several `labels` match a pull request holding any of them but list it once per label it
+ // holds, which would throw the row offset off, so one required label is all Forgejo is
+ // asked for. The service narrows the rest.
+ const single = filters?.labels?.find((group) => group.length === 1)?.[0];
+ if (single !== undefined) {
+ const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
+ const label = labels.items.find(
+ (candidate) => candidate.name.toLowerCase() === single.trim().toLowerCase(),
+ );
+ if (label !== undefined) params.set("labels", String(label.id));
+ }
+ if (filters?.author !== undefined)
+ params.set("poster", resolvePullRequestAuthorFilter(filters.author, input.viewer));
+ const query = { ...input, path: `${repoPath(input)}/pulls?${params}` };
// Self-hosted servers may cap pages below 50. Establish their actual page size before
// translating the service's row offset into an API page number.
- const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);
+ const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1).pipe(
+ Effect.catchTags({
+ // Forgejo answers a `poster` naming no account with a 400: nobody to list for.
+ PullRequestProviderError: (error) =>
+ params.has("poster") &&
+ isForgejoCliError(error.cause) &&
+ error.cause.httpStatus === 400
+ ? Effect.succeed(null)
+ : Effect.fail(error),
+ }),
+ );
+ if (first === null) return { items: [], truncated: false, continues: false };
const pageSize = first.rows.length || 50;
const firstIndex = Math.floor(offset / pageSize) + 1;
let consumed = 0;
diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
index af8a4467624..d6ec0221648 100644
--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
@@ -490,6 +490,70 @@ it.effect.each([
},
);
+it.effect("asks Forgejo for one required label by id and the author by login", () => {
+ const paths: Array<string> = [];
+ return Effect.gen(function* () {
+ const provider = yield* ForgejoPullRequestProvider.make;
+ yield* provider.listChangeRequests({
+ cwd: "/repo",
+ repository: "maria/project",
+ host: "forgejo.test",
+ state: "open",
+ involvement: "all",
+ viewer: "maria",
+ limit: 10,
+ filters: { labels: [["size:S", "size:M"], ["Bug"]], author: "@me" },
+ });
+ const listing = paths.find((path) => path.startsWith("repos/maria/project/pulls?"));
+ const params = new URLSearchParams(listing?.split("?")[1]);
+ assert.deepStrictEqual(params.getAll("labels"), ["7"]);
+ assert.strictEqual(params.get("poster"), "maria");
+ }).pipe(
+ Effect.provide(
+ Layer.mock(ForgejoCli.ForgejoCli)({
+ api: (input) => {
+ paths.push(input.path);
+ const response = input.path.startsWith("repos/maria/project/labels")
+ ? [{ id: 7, name: "bug" }]
+ : [];
+ return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
+ },
+ }),
+ ),
+ );
+});
+
+it.effect("lists nothing for an author Forgejo has no account for", () =>
+ Effect.gen(function* () {
+ const provider = yield* ForgejoPullRequestProvider.make;
+ const page = yield* provider.listChangeRequests({
+ cwd: "/repo",
+ repository: "maria/project",
+ host: "forgejo.test",
+ state: "open",
+ involvement: "all",
+ viewer: "maria",
+ limit: 10,
+ filters: { author: "nobody" },
+ });
+ assert.deepStrictEqual(page, { items: [], truncated: false, continues: false });
+ }).pipe(
+ Effect.provide(
+ Layer.mock(ForgejoCli.ForgejoCli)({
+ api: (input) =>
+ Effect.fail(
+ new ForgejoCli.ForgejoCliError({
+ command: "fj",
+ cwd: input.cwd,
+ httpStatus: 400,
+ detail: "Forgejo API request failed (HTTP 400): Poster not found",
+ }),
+ ),
+ }),
+ ),
+ ),
+);
+
it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
Effect.gen(function* () {
const provider = yield* ForgejoSourceControlProvider.make;
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
index 2db12a28406..121876d80dc 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
@@ -418,6 +418,53 @@ describe("GitCafePullRequestProvider", () => {
}).pipe(Effect.provide(server.layer));
});
+ it.effect("narrows a listing on GitCafe by label ids, draft state and the author's actor", () => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/labels": { items: labels, next: null },
+ "GET /users/bob": { actorId: "act_bob", handle: "bob" },
+ "GET /repos/owner/repo/pulls": { items: [pull], next: null },
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ yield* provider.listChangeRequests({
+ ...target,
+ state: "open",
+ involvement: "all",
+ viewer: "alice",
+ limit: 10,
+ filters: {
+ draft: "hide",
+ labels: [["missing"], ["Bug", "docs"]],
+ excludedLabels: ["docs", "missing"],
+ author: "bob",
+ },
+ });
+ const listing = server.sent.at(-1)!;
+ assert.strictEqual(listing.path, "/repos/owner/repo/pulls");
+ assert.strictEqual(listing.query.get("labels"), '["label_bug","label_docs"]');
+ assert.strictEqual(listing.query.get("labelNots"), '["label_docs"]');
+ assert.strictEqual(listing.query.get("stateNots"), '["draft"]');
+ assert.strictEqual(listing.query.get("authors"), '["act_bob"]');
+ }).pipe(Effect.provide(server.layer));
+ });
+
+ it.effect("leaves an author GitCafe has no profile for to be narrowed by login", () => {
+ const server = fakeGitCafe({ "GET /repos/owner/repo/pulls": { items: [pull], next: null } });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const page = yield* provider.listChangeRequests({
+ ...target,
+ state: "open",
+ involvement: "all",
+ viewer: "alice",
+ limit: 10,
+ filters: { author: "synced-only" },
+ });
+ assert.strictEqual(page.items.length, 1);
+ assert.isNull(server.sent.at(-1)!.query.get("authors"));
+ }).pipe(Effect.provide(server.layer));
+ });
+
it.effect("lists nothing for a viewer the token does not belong to", () => {
const server = fakeGitCafe({
"GET /auth/principal": { actorId: "act_two", handle: "bob" },
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
index 60b4e9a183b..4f6294e19ce 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
@@ -5,8 +5,10 @@ import * as Schema from "effect/Schema";
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
import {
NonNegativeInt,
+ resolvePullRequestAuthorFilter,
TrimmedNonEmptyString,
type PullRequestCapabilities,
+ type PullRequestListFilters,
type PullRequestStackHead,
} from "@t3tools/contracts";
import {
@@ -74,6 +76,7 @@ const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
const isId = Schema.is(Id);
const isApiError = Schema.is(GitCafeApi.GitCafeApiError);
const Principal = Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString });
+const User = Schema.Struct({ actorId: TrimmedNonEmptyString });
const Written = Schema.Struct({ id: Id });
const Versioned = Schema.Struct({ version: NonNegativeInt });
const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
@@ -104,7 +107,7 @@ const Listed = Schema.Struct({
items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString })),
next: Schema.NullOr(Schema.String),
});
-const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
+const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
const Snapshot = {
version: NonNegativeInt,
@@ -259,6 +262,68 @@ export const make = Effect.gen(function* () {
return { items, next };
});
+ /**
+ * GitCafe filters by ids, so label names and the author's handle are looked up first. A name it
+ * cannot resolve is left out, and the service narrows the rows by name instead.
+ */
+ const listFilterParams = Effect.fn("GitCafePullRequestProvider.listFilterParams")(function* (
+ input: ProviderRepositoryRef & {
+ readonly filters?: PullRequestListFilters | undefined;
+ readonly authorNarrowed: boolean;
+ readonly viewer: string;
+ },
+ base: string,
+ ) {
+ const filters = input.filters;
+ const params: Array<readonly [string, string]> = [];
+ if (filters === undefined) return params;
+ if (filters.draft !== undefined)
+ params.push([filters.draft === "only" ? "states" : "stateNots", encodeIds(["draft"])]);
+ const groups = filters.labels ?? [];
+ const excluded = filters.excludedLabels ?? [];
+ if (groups.length > 0 || excluded.length > 0) {
+ const labels = yield* readPages(
+ "listChangeRequests",
+ input,
+ `${base}/labels`,
+ Json.GitCafeLabels,
+ );
+ const ids = new Map(labels.items.map((label) => [label.name.toLowerCase(), label.id]));
+ const idsOf = (names: ReadonlyArray<string>) =>
+ names.flatMap((name) => {
+ const id = ids.get(name.trim().toLowerCase());
+ return id === undefined ? [] : [id];
+ });
+ // Several ids in `labels` match a pull request holding any one of them, which is exactly
+ // one group; the remaining groups are the service's to narrow.
+ const group = groups.find((names) => idsOf(names).length === names.length);
+ if (group !== undefined) params.push(["labels", encodeIds(idsOf(group))]);
+ const excludedIds = idsOf(excluded);
+ if (excludedIds.length > 0) params.push(["labelNots", encodeIds(excludedIds)]);
+ }
+ if (filters.author !== undefined && !input.authorNarrowed) {
+ const handle = resolvePullRequestAuthorFilter(filters.author, input.viewer);
+ // A GitHub-synced author with no GitCafe profile has no handle here; their rows are
+ // narrowed by login instead. A profile matches what GitHub sync authored for it too.
+ const user = yield* read(
+ "listChangeRequests",
+ input,
+ { path: `/users/${encodeURIComponent(handle)}` },
+ User,
+ ).pipe(
+ Effect.map(Option.some),
+ Effect.catchTags({
+ PullRequestProviderError: (error) =>
+ error.reason === "unauthenticated" || error.reason === "rate-limited"
+ ? Effect.fail(error)
+ : Effect.succeed(Option.none()),
+ }),
+ );
+ if (Option.isSome(user)) params.push(["authors", encodeIds([user.value.actorId])]);
+ }
+ return params;
+ });
+
const readComments = (operation: string, input: PullRef) =>
pullPath(operation, input).pipe(
Effect.flatMap((path) =>
@@ -570,6 +635,10 @@ export const make = Effect.gen(function* () {
actorId = principal.value.actorId;
}
}
+ const filterParams = yield* listFilterParams(
+ { ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },
+ base,
+ );
const limit = Math.max(1, input.limit);
const items: Array<Json.GitCafePull> = [];
let next: string | null = null;
@@ -580,10 +649,11 @@ export const make = Effect.gen(function* () {
});
if (input.state !== "all") query.set("state", input.state);
if (input.query?.trim()) query.set("q", input.query.trim());
+ for (const [key, value] of filterParams) query.set(key, value);
if (actorId !== undefined)
query.set(
input.involvement === "reviewing" ? "reviewers" : "authors",
- encodeActorIds([actorId]),
+ encodeIds([actorId]),
);
if (next !== null) query.set("after", next);
const page: typeof Json.GitCafePulls.Type = yield* read(
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index 30b9ba9b75c..5feb1290f5a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -146,6 +146,34 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect("asks GitLab for the labels, author and draft state it can filter on", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: {
+ labels: [["bug"], ["size:S", "size:XS"], ["a,b"], ["None"]],
+ excludedLabels: ["wontfix", "stale", "any"],
+ author: "@me",
+ draft: "only",
+ },
+ });
+
+ const params = new URLSearchParams((argsOfCall(0)[1] ?? "").split("?")[1]);
+ expect(params.get("labels")).toBe("bug");
+ expect(params.get("not[labels]")).toBe("wontfix,stale");
+ expect(params.get("author_username")).toBe("bilal");
+ expect(params.get("wip")).toBe("yes");
+ }),
+ );
+
it.effect("carries on from the number of rows already delivered", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(3, 1))));
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index d66992141f9..e4a7937de5a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -3,12 +3,13 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
-import { VcsProcessExitError } from "@t3tools/contracts";
+import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts";
import type {
PullRequestAction,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
+ PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
@@ -223,6 +224,7 @@ export class GitLabPullRequestCli extends Context.Service<
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
readonly getMergeRequestDetail: (input: {
@@ -419,6 +421,41 @@ function involvementParams(input: {
}
}
+/**
+ * GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of
+ * alternatives is left for the service to narrow. A comma would split a name in two, and `None`
+ * and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names.
+ */
+function filterParams(input: {
+ readonly filters?: PullRequestListFilters | undefined;
+ readonly involvement: PullRequestInvolvement;
+ readonly viewer: string;
+}): ReadonlyArray<readonly [string, string]> {
+ const filters = input.filters;
+ if (filters === undefined) return [];
+ const listable = (names: ReadonlyArray<string>) =>
+ names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
+ const required = listable(
+ (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
+ );
+ const excluded = listable(filters.excludedLabels ?? []);
+ return [
+ ...(required.length === 0 ? [] : [["labels", required.join(",")] as const]),
+ ...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]),
+ ...(filters.author === undefined || input.involvement === "authored"
+ ? []
+ : [
+ [
+ "author_username",
+ resolvePullRequestAuthorFilter(filters.author, input.viewer),
+ ] as const,
+ ]),
+ ...(filters.draft === undefined
+ ? []
+ : [["wip", filters.draft === "only" ? "yes" : "no"] as const]),
+ ];
+}
+
function diffCursorPage(cursor: string): number | null {
return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
}
@@ -514,6 +551,7 @@ export const make = Effect.gen(function* () {
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
readonly page: number;
readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
readonly cursorAdvance: number;
@@ -535,6 +573,7 @@ export const make = Effect.gen(function* () {
["state", stateParam(input.state)],
...involvementParams(input),
...searchParams(input.query),
+ ...filterParams(input),
["order_by", "updated_at"],
["sort", "desc"],
["per_page", String(perPage)],
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index 54b9e96c7e4..295960aa407 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -130,6 +130,7 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
+ filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequests")),