Skip to content

Commit 7beaa01

Browse files
fix(pull-requests): list filters narrow on every host that can (pingdotgg#23922)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent cd69df4 commit 7beaa01

14 files changed

Lines changed: 372 additions & 12 deletions

File tree

‎packages/contracts/src/pullRequest.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@ import { SourceControlProviderKind } from "./sourceControl.ts";
22
import * as Schema from "effect/Schema";
33
import { describe, expect, it } from "vite-plus/test";
44

5-
import { PullRequestDetail, PullRequestListResult, pullRequestHostOf } from "./pullRequest.ts";
5+
import {
6+
PullRequestDetail,
7+
PullRequestListResult,
8+
pullRequestHostOf,
9+
resolvePullRequestAuthorFilter,
10+
} from "./pullRequest.ts";
611

712
const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(PullRequestDetail));
813

@@ -144,3 +149,20 @@ describe("PullRequestCapabilities", () => {
144149
expect(decoded.title).toBe(detail.title);
145150
});
146151
});
152+
153+
describe("resolvePullRequestAuthorFilter", () => {
154+
it("reads me as the signed-in account on the host", () => {
155+
expect(resolvePullRequestAuthorFilter("me", "bilal")).toBe("bilal");
156+
expect(resolvePullRequestAuthorFilter(" @Me ", "bilal")).toBe("bilal");
157+
});
158+
159+
it("keeps me as a literal login when the host has no viewer", () => {
160+
expect(resolvePullRequestAuthorFilter("me", null)).toBe("me");
161+
expect(resolvePullRequestAuthorFilter("@me", " ")).toBe("@me");
162+
});
163+
164+
it("passes any other login through trimmed", () => {
165+
expect(resolvePullRequestAuthorFilter(" ana ", "bilal")).toBe("ana");
166+
expect(resolvePullRequestAuthorFilter("meredith", "bilal")).toBe("meredith");
167+
});
168+
});

‎packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,27 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
201201
}),
202202
);
203203

204+
it.effect("asks Azure for the author's pull requests by creator", () =>
205+
Effect.gen(function* () {
206+
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
207+
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
208+
209+
yield* cli.listPullRequests({
210+
cwd: "/w",
211+
repository: "web",
212+
state: "open",
213+
involvement: "reviewing",
214+
viewer: "[email protected]",
215+
limit: 10,
216+
author: "[email protected]",
217+
});
218+
219+
const args = argsOfCall(0);
220+
assert.strictEqual(args[args.indexOf("--creator") + 1], "[email protected]");
221+
assert.strictEqual(args[args.indexOf("--reviewer") + 1], "[email protected]");
222+
}),
223+
);
224+
204225
it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
205226
Effect.gen(function* () {
206227
mockedExecute

‎packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
150150
readonly involvement: PullRequestInvolvement;
151151
readonly viewer: string;
152152
readonly limit: number;
153+
/** Matched by `--creator`, which takes the email a row shows as its login. */
154+
readonly author?: string | undefined;
153155
/**
154156
* Where to carry on from. Azure has no date filter for a pull request listing, so the only
155157
* 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* () {
403405
readonly state: PullRequestListState;
404406
readonly involvement: PullRequestInvolvement;
405407
readonly viewer: string;
408+
readonly author?: string | undefined;
406409
readonly limit: number;
407410
readonly skip: number;
408411
readonly cursorAdvance: number;
@@ -429,6 +432,9 @@ export const make = Effect.gen(function* () {
429432
input.repository,
430433
...statusArgs(input.state),
431434
...involvementArgs(input),
435+
...(input.author === undefined || input.involvement === "authored"
436+
? []
437+
: ["--creator", input.author]),
432438
"--include-links",
433439
...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
434440
"--top",
@@ -546,6 +552,7 @@ export const make = Effect.gen(function* () {
546552
state: input.state,
547553
involvement: input.involvement,
548554
viewer: input.viewer,
555+
author: input.author,
549556
limit: input.limit,
550557
skip: input.cursor?.delivered ?? 0,
551558
cursorAdvance: 0,

‎packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { SourceControlProviderKind } from "@t3tools/contracts";
1+
import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import * as Semaphore from "effect/Semaphore";
44
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
@@ -275,6 +275,10 @@ export const make = Effect.gen(function* () {
275275
viewer: input.viewer,
276276
limit: input.limit,
277277
cursor: input.cursor,
278+
author:
279+
input.filters?.author === undefined
280+
? undefined
281+
: resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
278282
})
279283
.pipe(
280284
Effect.mapError(fail("listChangeRequests")),

‎packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,25 @@ layer("BitbucketPullRequestApi.layer", (it) => {
157157
}),
158158
);
159159

160+
it.effect("narrows by author and draft state in the same query", () =>
161+
Effect.gen(function* () {
162+
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
163+
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
164+
165+
yield* api.listPullRequests({
166+
repository: "acme/web",
167+
state: "open",
168+
limit: 50,
169+
author: 'ana"',
170+
draft: false,
171+
});
172+
173+
expect(filterOfCall(0)).toBe(
174+
'(author.nickname = "ana\\"" OR author.display_name = "ana\\"") AND draft = false',
175+
);
176+
}),
177+
);
178+
160179
it.effect("refuses a repository that is not workspace and slug", () =>
161180
Effect.gen(function* () {
162181
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;

‎packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,9 @@ export class BitbucketPullRequestApi extends Context.Service<
147147
readonly limit: number;
148148
readonly query?: string | undefined;
149149
readonly cursor?: ProviderListCursor | undefined;
150+
/** Matched against the login a row shows, which is the nickname or else the display name. */
151+
readonly author?: string | undefined;
152+
readonly draft?: boolean | undefined;
150153
}) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
151154

152155
readonly getPullRequest: (input: {
@@ -329,6 +332,11 @@ function searchFilter(query: string): string {
329332
return `(title ~ "${literal}" OR description ~ "${literal}")`;
330333
}
331334

335+
function authorFilter(login: string): string {
336+
const literal = filterLiteral(login);
337+
return `(author.nickname = "${literal}" OR author.display_name = "${literal}")`;
338+
}
339+
332340
/**
333341
* The backslash is escaped first, or escaping the quote would only produce a literal
334342
* backslash followed by a live quote.
@@ -565,6 +573,8 @@ export const make = Effect.gen(function* () {
565573
// Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
566574
const predicates = [
567575
...(search.length === 0 ? [] : [searchFilter(search)]),
576+
...(input.author === undefined ? [] : [authorFilter(input.author)]),
577+
...(input.draft === undefined ? [] : [`draft = ${input.draft}`]),
568578
...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
569579
...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
570580
];

‎packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { SourceControlProviderKind } from "@t3tools/contracts";
1+
import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
44

@@ -158,6 +158,11 @@ export const make = Effect.gen(function* () {
158158
limit: input.limit,
159159
query: input.query,
160160
cursor: input.cursor,
161+
author:
162+
input.filters?.author === undefined
163+
? undefined
164+
: resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
165+
draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only",
161166
})
162167
.pipe(
163168
Effect.mapError(fail("listChangeRequests")),

‎packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { SourceControlProviderKind } from "@t3tools/contracts";
1+
import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import * as Schema from "effect/Schema";
44
import * as Result from "effect/Result";
@@ -254,13 +254,36 @@ export const make = Effect.gen(function* () {
254254
const offset = input.cursor?.delivered ?? 0;
255255
const items: ReturnType<typeof forgejoChangeRequest>[] = [];
256256
const state = input.state === "merged" ? "closed" : input.state;
257-
const query = {
258-
...input,
259-
path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,
260-
};
257+
const params = new URLSearchParams({ state, sort: "recentupdate" });
258+
const filters = input.filters;
259+
// Several `labels` match a pull request holding any of them but list it once per label it
260+
// holds, which would throw the row offset off, so one required label is all Forgejo is
261+
// asked for. The service narrows the rest.
262+
const single = filters?.labels?.find((group) => group.length === 1)?.[0];
263+
if (single !== undefined) {
264+
const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);
265+
const label = labels.items.find(
266+
(candidate) => candidate.name.toLowerCase() === single.trim().toLowerCase(),
267+
);
268+
if (label !== undefined) params.set("labels", String(label.id));
269+
}
270+
if (filters?.author !== undefined)
271+
params.set("poster", resolvePullRequestAuthorFilter(filters.author, input.viewer));
272+
const query = { ...input, path: `${repoPath(input)}/pulls?${params}` };
261273
// Self-hosted servers may cap pages below 50. Establish their actual page size before
262274
// translating the service's row offset into an API page number.
263-
const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);
275+
const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1).pipe(
276+
Effect.catchTags({
277+
// Forgejo answers a `poster` naming no account with a 400: nobody to list for.
278+
PullRequestProviderError: (error) =>
279+
params.has("poster") &&
280+
isForgejoCliError(error.cause) &&
281+
error.cause.httpStatus === 400
282+
? Effect.succeed(null)
283+
: Effect.fail(error),
284+
}),
285+
);
286+
if (first === null) return { items: [], truncated: false, continues: false };
264287
const pageSize = first.rows.length || 50;
265288
const firstIndex = Math.floor(offset / pageSize) + 1;
266289
let consumed = 0;

‎packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,70 @@ it.effect.each([
490490
},
491491
);
492492

493+
it.effect("asks Forgejo for one required label by id and the author by login", () => {
494+
const paths: Array<string> = [];
495+
return Effect.gen(function* () {
496+
const provider = yield* ForgejoPullRequestProvider.make;
497+
yield* provider.listChangeRequests({
498+
cwd: "/repo",
499+
repository: "maria/project",
500+
host: "forgejo.test",
501+
state: "open",
502+
involvement: "all",
503+
viewer: "maria",
504+
limit: 10,
505+
filters: { labels: [["size:S", "size:M"], ["Bug"]], author: "@me" },
506+
});
507+
const listing = paths.find((path) => path.startsWith("repos/maria/project/pulls?"));
508+
const params = new URLSearchParams(listing?.split("?")[1]);
509+
assert.deepStrictEqual(params.getAll("labels"), ["7"]);
510+
assert.strictEqual(params.get("poster"), "maria");
511+
}).pipe(
512+
Effect.provide(
513+
Layer.mock(ForgejoCli.ForgejoCli)({
514+
api: (input) => {
515+
paths.push(input.path);
516+
const response = input.path.startsWith("repos/maria/project/labels")
517+
? [{ id: 7, name: "bug" }]
518+
: [];
519+
return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
520+
},
521+
}),
522+
),
523+
);
524+
});
525+
526+
it.effect("lists nothing for an author Forgejo has no account for", () =>
527+
Effect.gen(function* () {
528+
const provider = yield* ForgejoPullRequestProvider.make;
529+
const page = yield* provider.listChangeRequests({
530+
cwd: "/repo",
531+
repository: "maria/project",
532+
host: "forgejo.test",
533+
state: "open",
534+
involvement: "all",
535+
viewer: "maria",
536+
limit: 10,
537+
filters: { author: "nobody" },
538+
});
539+
assert.deepStrictEqual(page, { items: [], truncated: false, continues: false });
540+
}).pipe(
541+
Effect.provide(
542+
Layer.mock(ForgejoCli.ForgejoCli)({
543+
api: (input) =>
544+
Effect.fail(
545+
new ForgejoCli.ForgejoCliError({
546+
command: "fj",
547+
cwd: input.cwd,
548+
httpStatus: 400,
549+
detail: "Forgejo API request failed (HTTP 400): Poster not found",
550+
}),
551+
),
552+
}),
553+
),
554+
),
555+
);
556+
493557
it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
494558
Effect.gen(function* () {
495559
const provider = yield* ForgejoSourceControlProvider.make;

‎packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,53 @@ describe("GitCafePullRequestProvider", () => {
418418
}).pipe(Effect.provide(server.layer));
419419
});
420420

421+
it.effect("narrows a listing on GitCafe by label ids, draft state and the author's actor", () => {
422+
const server = fakeGitCafe({
423+
"GET /repos/owner/repo/labels": { items: labels, next: null },
424+
"GET /users/bob": { actorId: "act_bob", handle: "bob" },
425+
"GET /repos/owner/repo/pulls": { items: [pull], next: null },
426+
});
427+
return Effect.gen(function* () {
428+
const provider = yield* GitCafePullRequestProvider.make;
429+
yield* provider.listChangeRequests({
430+
...target,
431+
state: "open",
432+
involvement: "all",
433+
viewer: "alice",
434+
limit: 10,
435+
filters: {
436+
draft: "hide",
437+
labels: [["missing"], ["Bug", "docs"]],
438+
excludedLabels: ["docs", "missing"],
439+
author: "bob",
440+
},
441+
});
442+
const listing = server.sent.at(-1)!;
443+
assert.strictEqual(listing.path, "/repos/owner/repo/pulls");
444+
assert.strictEqual(listing.query.get("labels"), '["label_bug","label_docs"]');
445+
assert.strictEqual(listing.query.get("labelNots"), '["label_docs"]');
446+
assert.strictEqual(listing.query.get("stateNots"), '["draft"]');
447+
assert.strictEqual(listing.query.get("authors"), '["act_bob"]');
448+
}).pipe(Effect.provide(server.layer));
449+
});
450+
451+
it.effect("leaves an author GitCafe has no profile for to be narrowed by login", () => {
452+
const server = fakeGitCafe({ "GET /repos/owner/repo/pulls": { items: [pull], next: null } });
453+
return Effect.gen(function* () {
454+
const provider = yield* GitCafePullRequestProvider.make;
455+
const page = yield* provider.listChangeRequests({
456+
...target,
457+
state: "open",
458+
involvement: "all",
459+
viewer: "alice",
460+
limit: 10,
461+
filters: { author: "synced-only" },
462+
});
463+
assert.strictEqual(page.items.length, 1);
464+
assert.isNull(server.sent.at(-1)!.query.get("authors"));
465+
}).pipe(Effect.provide(server.layer));
466+
});
467+
421468
it.effect("lists nothing for a viewer the token does not belong to", () => {
422469
const server = fakeGitCafe({
423470
"GET /auth/principal": { actorId: "act_two", handle: "bob" },

0 commit comments

Comments
 (0)