feat(prs): navigate, merge and rebase GitHub stacks (#10875)
This commit is contained in:
1 parent
f0401c6290
commit
de37964db2
53 files changed
+3106
-466
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -9,14 +10,22 @@ import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";
|
||||
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
|
||||
import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";
|
||||
|
||||
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
const mockedExecute = vi.fn<GitHubCli.GitHubCli["Service"]["execute"]>();
|
||||
const mockedStackMemberships = vi.fn<GitHubCli.GitHubCli["Service"]["execute"]>(() =>
|
||||
Effect.succeed(output('{"data":{}}')),
|
||||
);
|
||||
const mockedGetPullRequest = vi.fn<GitHubCli.GitHubCli["Service"]["getPullRequest"]>();
|
||||
|
||||
const layer = it.layer(
|
||||
GitHubPullRequestCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(GitHubCli.GitHubCli)({
|
||||
execute: mockedExecute,
|
||||
execute: (input) =>
|
||||
input.args.some((arg) => arg.includes("query PullRequestStackMemberships"))
|
||||
? mockedStackMemberships(input)
|
||||
: mockedExecute(input),
|
||||
getPullRequest: mockedGetPullRequest,
|
||||
}),
|
||||
),
|
||||
@@ -179,6 +188,7 @@ function searchQueryOfCall(index: number): string | undefined {
|
||||
|
||||
afterEach(() => {
|
||||
mockedExecute.mockReset();
|
||||
mockedStackMemberships.mockReset();
|
||||
mockedGetPullRequest.mockReset();
|
||||
});
|
||||
|
||||
@@ -320,6 +330,51 @@ layer("GitHubPullRequestCli.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fetches layer titles only when the caller asks for stack details", () =>
|
||||
Effect.gen(function* () {
|
||||
const minimal = {
|
||||
url: "https://api.github.com/repos/acme/web/stacks/3",
|
||||
number: 3,
|
||||
base: { ref: "main" },
|
||||
pull_requests: [
|
||||
{ number: 7, head: { ref: "feat/two", sha: "abc123" }, state: "open", merged_at: null },
|
||||
],
|
||||
};
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(JSON.stringify([minimal]))));
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
output(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
...minimal,
|
||||
pull_requests: [{ ...minimal.pull_requests[0], title: "Second layer", draft: false }],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
|
||||
const stack = yield* cli.getPullRequestStack({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
number: 7,
|
||||
includeDetails: true,
|
||||
});
|
||||
expect(stack?.layers[0]).toMatchObject({
|
||||
title: "Second layer",
|
||||
headSha: "abc123",
|
||||
isDraft: false,
|
||||
});
|
||||
expect(callAt(1).args).toEqual([
|
||||
"api",
|
||||
"--hostname",
|
||||
"github.com",
|
||||
"repos/acme/web/stacks/3",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads an empty stacks listing as not stacked", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
@@ -715,6 +770,127 @@ layer("GitHubPullRequestCli.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("enriches only the visible fallback rows after filtering and widening", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
Effect.succeed(output(pullRequests(3, 1, () => ({ isDraft: true })))),
|
||||
);
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
Effect.succeed(output(pullRequests(6, 1, (number) => ({ isDraft: number < 4 })))),
|
||||
);
|
||||
mockedStackMemberships.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
output(
|
||||
encodeJson({
|
||||
data: {
|
||||
s0: {
|
||||
pullRequest: {
|
||||
stack: { number: 3, size: 2, baseRefName: "main" },
|
||||
stackEntry: { position: 1 },
|
||||
},
|
||||
},
|
||||
s1: { pullRequest: { stack: null, stackEntry: null } },
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
|
||||
const batch = yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "bilal",
|
||||
limit: 2,
|
||||
filters: { draft: "hide" },
|
||||
});
|
||||
expect(batch.items.map((item) => item.number)).toEqual([4, 5]);
|
||||
expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
|
||||
expect(batch.items[1]?.stack).toBeUndefined();
|
||||
expect(batch.truncated).toBe(true);
|
||||
expect(batch.continues).toBe(false);
|
||||
expect(mockedStackMemberships).toHaveBeenCalledTimes(1);
|
||||
const query = mockedStackMemberships.mock.calls[0]?.[0].args.at(-1) ?? "";
|
||||
expect(query).toContain("pullRequest(number: 4)");
|
||||
expect(query).toContain("pullRequest(number: 5)");
|
||||
expect(query).not.toContain("pullRequest(number: 1)");
|
||||
expect(query).not.toContain("pullRequest(number: 6)");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("batches membership reads and keeps successful rows when one chunk fails", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(27, 1))));
|
||||
mockedStackMemberships.mockImplementation((input) =>
|
||||
input.args.at(-1)?.includes("pullRequest(number: 26)")
|
||||
? Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
command: "gh",
|
||||
cwd: "/w",
|
||||
cause: new Error("HTTP 502"),
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(
|
||||
output(
|
||||
encodeJson({
|
||||
data: {
|
||||
s0: {
|
||||
pullRequest: {
|
||||
stack: { number: 3, size: 2, baseRefName: "main" },
|
||||
stackEntry: { position: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
|
||||
const batch = yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "bilal",
|
||||
limit: 26,
|
||||
});
|
||||
expect(batch.items.map((item) => item.number)).toEqual(
|
||||
Array.from({ length: 26 }, (_, i) => i + 1),
|
||||
);
|
||||
expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
|
||||
expect(batch.items[25]?.stack).toBeUndefined();
|
||||
expect(batch.truncated).toBe(true);
|
||||
expect(batch.continues).toBe(true);
|
||||
expect(mockedStackMemberships).toHaveBeenCalledTimes(2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips membership enrichment for empty pages and enterprise hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 7))));
|
||||
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
|
||||
const input = {
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
state: "open" as const,
|
||||
involvement: "all" as const,
|
||||
viewer: "bilal",
|
||||
limit: 2,
|
||||
};
|
||||
const empty = yield* cli.listPullRequests({ ...input, host: "github.com" });
|
||||
const enterprise = yield* cli.listPullRequests({ ...input, host: "github.acme.test" });
|
||||
expect(empty.items).toEqual([]);
|
||||
expect(enterprise.items.map((item) => item.number)).toEqual([7]);
|
||||
expect(mockedStackMemberships).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads the line counts in chunks, and files them back by position", () =>
|
||||
Effect.gen(function* () {
|
||||
const changeRequests = Array.from({ length: 26 }, (_, index) => ({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { runGitHubStackAction, type GitHubStackActionError } from "./githubStackActions.ts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -6,6 +7,7 @@ import * as Schema from "effect/Schema";
|
||||
import {
|
||||
resolvePullRequestAuthorFilter,
|
||||
type PullRequestAction,
|
||||
type PullRequestStackHead,
|
||||
type PullRequestActor,
|
||||
type PullRequestInvolvement,
|
||||
type PullRequestListFilters,
|
||||
@@ -51,6 +53,8 @@ import {
|
||||
decodeReviewThreadCommentsJson,
|
||||
decodeReviewThreadsJson,
|
||||
buildPullRequestStatsGraphQlQuery,
|
||||
buildPullRequestStackMembershipsGraphQlQuery,
|
||||
decodePullRequestStackMembershipsJson,
|
||||
encodeGraphQlRequestJson,
|
||||
pullRequestSearchGraphQlQuery,
|
||||
PULL_REQUEST_SEARCH_MAX_ROWS,
|
||||
@@ -334,6 +338,7 @@ export class GitHubWorkflowApprovalHeadChangedError extends Schema.TaggedError<G
|
||||
}
|
||||
|
||||
export type GitHubPullRequestCliError =
|
||||
| GitHubStackActionError
|
||||
| GitHubCli.GitHubCliError
|
||||
| GitHubPullRequestReadError
|
||||
| GitHubDiffCursorError
|
||||
@@ -488,6 +493,7 @@ export class GitHubPullRequestCli extends Context.Service<
|
||||
*/
|
||||
readonly getPullRequestStack: (input: {
|
||||
readonly cwd: string;
|
||||
readonly includeDetails?: boolean;
|
||||
readonly repository: string;
|
||||
readonly host: string;
|
||||
readonly number: number;
|
||||
@@ -627,6 +633,8 @@ export class GitHubPullRequestCli extends Context.Service<
|
||||
readonly host: string;
|
||||
readonly number: number;
|
||||
readonly action: PullRequestAction;
|
||||
readonly stackNumber?: number;
|
||||
readonly expectedStackHeads?: ReadonlyArray<PullRequestStackHead>;
|
||||
readonly mergeMethod?: PullRequestMergeMethod;
|
||||
readonly updateMethod?: PullRequestUpdateMethod;
|
||||
}) => Effect.Effect<void, GitHubPullRequestCliError>;
|
||||
@@ -1557,6 +1565,47 @@ export const make = Effect.gen(function* () {
|
||||
? read(false)
|
||||
: Effect.succeed(batch),
|
||||
),
|
||||
Effect.flatMap((batch) => {
|
||||
// Match the search query's host support, and enrich only rows that survived paging.
|
||||
if (input.host !== "github.com" || batch.items.length === 0) return Effect.succeed(batch);
|
||||
const chunks: Array<ReadonlyArray<GitHubPullRequestListItem>> = [];
|
||||
for (let start = 0; start < batch.items.length; start += STAT_ALIASES_PER_REQUEST) {
|
||||
chunks.push(batch.items.slice(start, start + STAT_ALIASES_PER_REQUEST));
|
||||
}
|
||||
return Effect.forEach(
|
||||
chunks,
|
||||
(chunk) => {
|
||||
const query = buildPullRequestStackMembershipsGraphQlQuery(
|
||||
input.repository,
|
||||
chunk.map((item) => item.number),
|
||||
);
|
||||
if (query === null) return Effect.succeed(chunk);
|
||||
return graphqlRead({
|
||||
cwd: input.cwd,
|
||||
host: input.host,
|
||||
operation: "listPullRequestStackMemberships",
|
||||
query,
|
||||
decode: decodePullRequestStackMembershipsJson,
|
||||
}).pipe(
|
||||
Effect.map((memberships) =>
|
||||
chunk.map((item, index) => {
|
||||
const stack = memberships.get(index);
|
||||
return stack === undefined ? item : { ...item, stack };
|
||||
}),
|
||||
),
|
||||
// Optional badges must not take down a listing that already read successfully.
|
||||
Effect.catch(() =>
|
||||
Effect.logWarning("Pull request stack membership enrichment failed", {
|
||||
operation: "listPullRequestStackMemberships",
|
||||
host: input.host,
|
||||
rows: chunk.length,
|
||||
}).pipe(Effect.as(chunk)),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: STAT_REQUEST_CONCURRENCY },
|
||||
).pipe(Effect.map((chunks) => ({ ...batch, items: chunks.flat() })));
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1581,7 +1630,7 @@ export const make = Effect.gen(function* () {
|
||||
operation: "searchPullRequests",
|
||||
// The reader's own words are in the query, so it travels over stdin rather than in argv.
|
||||
privateVariables: { q: query },
|
||||
query: pullRequestSearchGraphQlQuery(rows),
|
||||
query: pullRequestSearchGraphQlQuery(rows, input.host === "github.com"),
|
||||
decode: decodePullRequestSearchJson,
|
||||
}).pipe(
|
||||
Effect.map((batch) => ({
|
||||
@@ -1709,6 +1758,34 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
}),
|
||||
Effect.flatMap((stack) => {
|
||||
if (!input.includeDetails || stack === null) return Effect.succeed(stack);
|
||||
return github
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
`repos/${owner}/${name}/stacks/${stack.number}`,
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const decoded = decodePullRequestStacksJson(`[${result.stdout.trim()}]`);
|
||||
return Result.isSuccess(decoded)
|
||||
? Effect.succeed(decoded.success)
|
||||
: Effect.fail(
|
||||
new GitHubPullRequestReadError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
operation: "getPullRequestStack",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Hosts without the stacks preview return 404. Other failures must preserve the
|
||||
// previously synced stack and let the caller retry.
|
||||
Effect.catchTags({
|
||||
@@ -2109,6 +2186,10 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
|
||||
runPullRequestAction: (input) => {
|
||||
if (input.stackNumber !== undefined)
|
||||
return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe(
|
||||
Effect.provideService(GitHubCli.GitHubCli, github),
|
||||
);
|
||||
if (input.action === "revert") {
|
||||
return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe(
|
||||
Effect.flatMap((pullRequestId) =>
|
||||
|
||||
@@ -130,6 +130,7 @@ describe("gitHubViewerPermissions", () => {
|
||||
],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
stackRebase: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
requestReviewers: true,
|
||||
labels: true,
|
||||
|
||||
@@ -48,6 +48,7 @@ const CAPABILITIES: PullRequestCapabilities = {
|
||||
reviewers: { request: true, listCandidates: true },
|
||||
edit: { changeRequest: true, comment: true },
|
||||
stacks: true,
|
||||
stackActions: true,
|
||||
labels: true,
|
||||
};
|
||||
|
||||
@@ -70,6 +71,7 @@ const CAPABILITIES: PullRequestCapabilities = {
|
||||
*/
|
||||
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
|
||||
return {
|
||||
...(access.canWrite ? { stackRebase: true } : {}),
|
||||
actions: [
|
||||
// Arming a merge and taking the arming back are the merge, deferred: whoever may not
|
||||
// merge here may not leave an instruction to merge later either.
|
||||
@@ -558,6 +560,10 @@ export const make = Effect.gen(function* () {
|
||||
host: input.host,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
|
||||
...(input.expectedStackHeads === undefined
|
||||
? {}
|
||||
: { expectedStackHeads: input.expectedStackHeads }),
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
|
||||
})
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestStackMembership,
|
||||
PullRequestAction,
|
||||
PullRequestStackHead,
|
||||
PullRequestActor,
|
||||
PullRequestBaseComparison,
|
||||
PullRequestCapabilities,
|
||||
@@ -65,6 +67,7 @@ export interface PullRequestProviderFailure {
|
||||
|
||||
/** A change request as the provider sees it, before the service attaches project context. */
|
||||
export interface ProviderChangeRequest {
|
||||
readonly stack?: PullRequestStackMembership;
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
@@ -115,6 +118,9 @@ export interface ProviderChangeRequestSummary {
|
||||
|
||||
/** One layer of a host-native stack, bottom to top order is the array's. */
|
||||
export interface ProviderChangeRequestStackLayer {
|
||||
readonly title?: string;
|
||||
readonly isDraft?: boolean;
|
||||
readonly headSha?: string;
|
||||
readonly number: number;
|
||||
readonly headBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
@@ -364,7 +370,7 @@ export interface PullRequestProviderApi {
|
||||
* because most hosts have no such object; the service derives chains from base branches there.
|
||||
*/
|
||||
readonly getChangeRequestStack?: (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
input: ProviderRepositoryRef & { readonly includeDetails?: boolean; readonly number: number },
|
||||
) => Effect.Effect<ProviderChangeRequestStack | null, PullRequestProviderError>;
|
||||
|
||||
/** Comments, line threads, and commits, kept off the critical path for the core detail. */
|
||||
@@ -426,6 +432,8 @@ export interface PullRequestProviderApi {
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly action: PullRequestAction;
|
||||
readonly stackNumber?: number;
|
||||
readonly expectedStackHeads?: ReadonlyArray<PullRequestStackHead>;
|
||||
/** Meaningful for `merge` and `enable-auto-merge`; absent takes the host's own default. */
|
||||
readonly mergeMethod?: PullRequestMergeMethod;
|
||||
/** Only meaningful for `update-branch`; absent takes the host's own default. */
|
||||
|
||||
@@ -1564,6 +1564,48 @@ it.effect("refuses a repository that does not belong to the requested project",
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("caches stack membership separately from action details", () =>
|
||||
Effect.gen(function* () {
|
||||
const reads: Array<boolean> = [];
|
||||
const service = yield* makeService({
|
||||
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
|
||||
providers: [
|
||||
fakeProvider("github", {
|
||||
getChangeRequestStack: (input) =>
|
||||
Effect.sync(() => {
|
||||
reads.push(input.includeDetails === true);
|
||||
return {
|
||||
id: "9",
|
||||
number: 3,
|
||||
url: "https://github.com/acme/web/stacks/3",
|
||||
base: "main",
|
||||
layers: [
|
||||
{
|
||||
number: 7,
|
||||
headBranch: "a",
|
||||
state: "open" as const,
|
||||
...(input.includeDetails ? { title: "First layer", headSha: "abc" } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}),
|
||||
}),
|
||||
],
|
||||
});
|
||||
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 7 };
|
||||
yield* service.stack(reference, { includeDetails: false });
|
||||
yield* service.stack(reference, { includeDetails: false });
|
||||
const detail = yield* service.stack(reference);
|
||||
yield* service.stack(reference);
|
||||
assert.deepStrictEqual(reads, [false, true]);
|
||||
assert.strictEqual(detail?.layers[0]?.headSha, "abc");
|
||||
yield* service.invalidate({ reference });
|
||||
yield* service.stack(reference, { includeDetails: false });
|
||||
yield* service.stack(reference);
|
||||
assert.deepStrictEqual(reads, [false, true, false, true]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads a host-native stack through the provider and null where it has none", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* makeService({
|
||||
@@ -3997,6 +4039,91 @@ it.effect('resolves an author filter of "me" to the viewer before narrowing a ho
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("authorizes stack rebases independently of whether the selected layer is behind", () =>
|
||||
Effect.gen(function* () {
|
||||
let taken = 0;
|
||||
let summaryReads = 0;
|
||||
let mutationFails = false;
|
||||
let stackRebase = true;
|
||||
let stackActions = true;
|
||||
const capabilities = {
|
||||
diff: true,
|
||||
comment: true,
|
||||
actions: ["update-branch"] as const,
|
||||
mergeMethods: ["merge"] as const,
|
||||
updateMethods: ["rebase"] as const,
|
||||
get stackActions() {
|
||||
return stackActions;
|
||||
},
|
||||
search: true,
|
||||
reactions: true,
|
||||
review: FULL_REVIEW,
|
||||
reviewers: FULL_REVIEWERS,
|
||||
};
|
||||
const service = yield* makeService({
|
||||
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
|
||||
providers: [
|
||||
fakeProvider("github", {
|
||||
capabilities,
|
||||
getViewerPermissions: () =>
|
||||
Effect.succeed({
|
||||
actions: [],
|
||||
stackRebase,
|
||||
comment: true,
|
||||
resolve: false,
|
||||
verdicts: [],
|
||||
requestReviewers: false,
|
||||
}),
|
||||
getChangeRequestSummary: () =>
|
||||
Effect.sync(() => {
|
||||
summaryReads++;
|
||||
return changeRequest(8, "2026-07-01T00:00:00Z");
|
||||
}),
|
||||
runAction: () =>
|
||||
Effect.gen(function* () {
|
||||
taken++;
|
||||
if (mutationFails) return yield* requestFailed;
|
||||
}),
|
||||
}),
|
||||
],
|
||||
});
|
||||
const input = {
|
||||
projectId: "p1" as ProjectId,
|
||||
repository: "acme/web",
|
||||
number: 3,
|
||||
action: "update-branch" as const,
|
||||
updateMethod: "rebase" as const,
|
||||
stackNumber: 50,
|
||||
expectedStackHeads: [{ number: 3, headSha: "ccc" }],
|
||||
};
|
||||
yield* service.runAction(input);
|
||||
assert.strictEqual(taken, 1);
|
||||
const unrelated = { ...input, number: 8 };
|
||||
yield* service.summary(unrelated);
|
||||
assert.strictEqual(summaryReads, 1);
|
||||
stackRebase = false;
|
||||
assert.strictEqual(
|
||||
(yield* Effect.flip(service.runAction(input)))._tag,
|
||||
"PullRequestOperationError",
|
||||
);
|
||||
stackRebase = true;
|
||||
stackActions = false;
|
||||
assert.strictEqual(
|
||||
(yield* Effect.flip(service.runAction(input)))._tag,
|
||||
"PullRequestOperationError",
|
||||
);
|
||||
assert.strictEqual(taken, 1);
|
||||
yield* service.summary(unrelated);
|
||||
assert.strictEqual(summaryReads, 1);
|
||||
stackActions = true;
|
||||
mutationFails = true;
|
||||
yield* Effect.flip(service.runAction(input));
|
||||
assert.strictEqual(taken, 2);
|
||||
yield* service.summary(unrelated);
|
||||
assert.strictEqual(summaryReads, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a way of updating a branch that the host or the viewer does not allow", () =>
|
||||
Effect.gen(function* () {
|
||||
let taken: string | null = null;
|
||||
|
||||
@@ -155,6 +155,7 @@ export class PullRequestService extends Context.Service<
|
||||
*/
|
||||
readonly stack: (
|
||||
input: PullRequestRef,
|
||||
options?: { readonly includeDetails?: boolean },
|
||||
) => Effect.Effect<PullRequestStack | null, PullRequestError>;
|
||||
readonly subscribeMerges: Effect.Effect<
|
||||
Stream.Stream<PullRequestMergeEvent>,
|
||||
@@ -907,6 +908,7 @@ export const make = Effect.gen(function* () {
|
||||
}): PullRequestListEntry => {
|
||||
const viewer = input.viewer.toLowerCase();
|
||||
return {
|
||||
...(input.item.stack === undefined ? {} : { stack: input.item.stack }),
|
||||
provider: input.project.api.kind,
|
||||
host: input.project.host,
|
||||
projectId: input.project.project.id,
|
||||
@@ -1331,7 +1333,7 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const stackUncached: PullRequestService["Service"]["stack"] = (input) =>
|
||||
const stackUncached: PullRequestService["Service"]["stack"] = (input, options) =>
|
||||
requireProject(input).pipe(
|
||||
Effect.flatMap((project) => {
|
||||
const read = project.api.getChangeRequestStack;
|
||||
@@ -1341,6 +1343,7 @@ export const make = Effect.gen(function* () {
|
||||
repository: project.repository,
|
||||
host: project.host,
|
||||
number: input.number,
|
||||
includeDetails: options?.includeDetails !== false,
|
||||
}).pipe(
|
||||
Effect.mapError(toPullRequestError("stack")),
|
||||
Effect.map((stack): PullRequestStack | null =>
|
||||
@@ -1352,6 +1355,7 @@ export const make = Effect.gen(function* () {
|
||||
url: stack.url,
|
||||
base: stack.base,
|
||||
layers: stack.layers.map((layer) => ({
|
||||
...layer,
|
||||
number: layer.number,
|
||||
headBranch: layer.headBranch,
|
||||
state: layer.state,
|
||||
@@ -1531,6 +1535,20 @@ export const make = Effect.gen(function* () {
|
||||
const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>
|
||||
requireProject(input).pipe(
|
||||
Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {
|
||||
if (
|
||||
input.stackNumber !== undefined &&
|
||||
(project.api.capabilities.stackActions !== true ||
|
||||
!["merge", "update-branch"].includes(input.action) ||
|
||||
input.expectedStackHeads === undefined ||
|
||||
(input.action === "update-branch" && input.updateMethod !== "rebase"))
|
||||
) {
|
||||
return Effect.fail(
|
||||
new PullRequestOperationError({
|
||||
operation: "runAction",
|
||||
detail: "This stack action is not supported or has no expected head revision.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
// The surface hides what a host cannot do, and this refuses it as well: a request that
|
||||
// reached here anyway must not be handed to a provider that never claimed the action.
|
||||
if (!project.api.capabilities.actions.includes(input.action)) {
|
||||
@@ -1573,7 +1591,10 @@ export const make = Effect.gen(function* () {
|
||||
// above do not.
|
||||
return viewerPermissionsOf(project, input, "runAction").pipe(
|
||||
Effect.flatMap((viewer): Effect.Effect<string, PullRequestError> => {
|
||||
if (!viewer.actions.includes(input.action)) {
|
||||
const stackRebase = input.stackNumber !== undefined && input.action === "update-branch";
|
||||
if (
|
||||
stackRebase ? viewer.stackRebase !== true : !viewer.actions.includes(input.action)
|
||||
) {
|
||||
return Effect.fail(
|
||||
new PullRequestOperationError({
|
||||
operation: "runAction",
|
||||
@@ -1582,6 +1603,7 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
if (
|
||||
!stackRebase &&
|
||||
input.updateMethod !== undefined &&
|
||||
!(viewer.updateMethods ?? []).includes(input.updateMethod)
|
||||
) {
|
||||
@@ -1599,10 +1621,17 @@ export const make = Effect.gen(function* () {
|
||||
host: project.host,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
|
||||
...(input.expectedStackHeads === undefined
|
||||
? {}
|
||||
: { expectedStackHeads: input.expectedStackHeads }),
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
|
||||
})
|
||||
.pipe(
|
||||
// Once the authorized provider action starts, a failure may leave partial
|
||||
// remote updates. Validation and permission failures above changed nothing.
|
||||
Effect.ensuring(input.stackNumber === undefined ? Effect.void : refreshAfterTurn),
|
||||
Effect.mapError(toPullRequestError("runAction")),
|
||||
Effect.as(
|
||||
project.api.kind === "azure-devops"
|
||||
@@ -2327,12 +2356,18 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
};
|
||||
|
||||
const stackCache = yield* Cache.makeWith((key: string) => stackUncached(refOfCacheKey(key)), {
|
||||
capacity: DETAIL_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? SUMMARY_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const stack: PullRequestService["Service"]["stack"] = (input) =>
|
||||
Cache.get(stackCache, refCacheKey(input));
|
||||
const stackCache = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const [referenceKey, includeDetails] = JSON.parse(key) as [string, boolean];
|
||||
return stackUncached(refOfCacheKey(referenceKey), { includeDetails });
|
||||
},
|
||||
{
|
||||
capacity: DETAIL_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? SUMMARY_CACHE_TTL : Duration.zero),
|
||||
},
|
||||
);
|
||||
const stack: PullRequestService["Service"]["stack"] = (input, options) =>
|
||||
Cache.get(stackCache, JSON.stringify([refCacheKey(input), options?.includeDetails !== false]));
|
||||
|
||||
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
|
||||
// of in-flight state: concurrent identical reads coalesce on the key into one host request.
|
||||
|
||||
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildReviewSubmissionJson,
|
||||
buildPullRequestStackMembershipsGraphQlQuery,
|
||||
decodePullRequestStackMembershipsJson,
|
||||
buildReviewerRequestJson,
|
||||
decodeBaseComparisonJson,
|
||||
decodePullRequestActivityJson,
|
||||
@@ -21,6 +23,7 @@ import {
|
||||
decodeWorkflowRunApprovalsJson,
|
||||
reviewThreadConversation,
|
||||
REVIEW_THREADS_GRAPHQL_QUERY,
|
||||
pullRequestSearchGraphQlQuery,
|
||||
} from "./gitHubPullRequestJson.ts";
|
||||
|
||||
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
|
||||
@@ -165,6 +168,17 @@ describe("pull request search decoding", () => {
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps stack membership beside search results without extra per-PR reads", () => {
|
||||
const raw = JSON.parse(searchJson(["SUCCESS", null]));
|
||||
raw.data.search.nodes[0].stack = { number: 3, size: 2, baseRefName: "main" };
|
||||
raw.data.search.nodes[0].stackEntry = { position: 1 };
|
||||
const batch = expectSuccess(decodePullRequestSearchJson(JSON.stringify(raw)));
|
||||
expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, position: 1, base: "main" });
|
||||
expect(batch.items[1]?.stack).toBeUndefined();
|
||||
expect(pullRequestSearchGraphQlQuery(20, true)).toContain("stackEntry");
|
||||
expect(pullRequestSearchGraphQlQuery(20)).not.toContain("stackEntry");
|
||||
});
|
||||
|
||||
it("maps the rollup enum the search answers with onto the same three words", () => {
|
||||
// The search asks GitHub for the verdict rather than the checks behind it, so this path sees
|
||||
// one enum where the listing sees an array.
|
||||
@@ -1548,6 +1562,32 @@ describe("host-native stack decoding", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("retains the detailed layer titles, draft state and expected revision", () => {
|
||||
expect(
|
||||
expectStack({
|
||||
pull_requests: [
|
||||
{
|
||||
number: 11,
|
||||
title: "Second layer",
|
||||
draft: true,
|
||||
head: { ref: "feat/two", sha: "abc123" },
|
||||
state: "open",
|
||||
merged_at: null,
|
||||
},
|
||||
],
|
||||
}).layers,
|
||||
).toEqual([
|
||||
{
|
||||
number: 11,
|
||||
title: "Second layer",
|
||||
isDraft: true,
|
||||
headSha: "abc123",
|
||||
headBranch: "feat/two",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts a base named as a bare branch, which is what the preview started out sending", () => {
|
||||
expect(expectStack({ base: "develop" }).base).toBe("develop");
|
||||
});
|
||||
@@ -1579,3 +1619,38 @@ describe("host-native stack decoding", () => {
|
||||
expect(Result.isSuccess(decodePullRequestStacksJson("{"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pull request stack membership batches", () => {
|
||||
it("maps aliases while skipping missing pull requests and incomplete memberships", () => {
|
||||
const memberships = expectSuccess(
|
||||
decodePullRequestStackMembershipsJson(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
s0: {
|
||||
pullRequest: {
|
||||
stack: { number: 3, size: 2, baseRefName: "main" },
|
||||
stackEntry: { position: 1 },
|
||||
},
|
||||
},
|
||||
s1: null,
|
||||
s2: { pullRequest: null },
|
||||
s3: { pullRequest: { stack: null, stackEntry: null } },
|
||||
s4: { pullRequest: { stack: { number: 3, size: 2, baseRefName: "main" } } },
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect([...memberships]).toEqual([[0, { number: 3, size: 2, base: "main", position: 1 }]]);
|
||||
});
|
||||
|
||||
it("refuses malformed responses and unsafe query selectors", () => {
|
||||
expect(Result.isFailure(decodePullRequestStackMembershipsJson('{"errors":[]}'))).toBe(true);
|
||||
expect(buildPullRequestStackMembershipsGraphQlQuery('acme/web") { x } #', [1])).toBeNull();
|
||||
expect(buildPullRequestStackMembershipsGraphQlQuery("acme/web", [0])).toBeNull();
|
||||
expect(buildPullRequestStackMembershipsGraphQlQuery("acme/web", [1.5])).toBeNull();
|
||||
expect(buildPullRequestStackMembershipsGraphQlQuery("acme/web", [])).toBeNull();
|
||||
expect(buildPullRequestStackMembershipsGraphQlQuery("acme/web", [7, 8])).toContain(
|
||||
"pullRequest(number: 8)",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import * as Exit from "effect/Exit";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestStackMembership,
|
||||
PullRequestActor,
|
||||
PullRequestCheck,
|
||||
PullRequestCheckStatus,
|
||||
@@ -111,12 +112,22 @@ const RawListItemSchema = Schema.Struct({
|
||||
statusCheckRollup: Schema.optional(Schema.NullOr(Schema.Array(RawCheckSchema))),
|
||||
});
|
||||
|
||||
const RawStackMembershipSchema = Schema.Struct({
|
||||
stack: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({ number: Schema.Int, size: Schema.Int, baseRefName: Schema.String }),
|
||||
),
|
||||
),
|
||||
stackEntry: Schema.optional(Schema.NullOr(Schema.Struct({ position: Schema.Int }))),
|
||||
});
|
||||
|
||||
/**
|
||||
* A search's own answer, which is the listing's row one connection deeper: `gh pr list --json`
|
||||
* flattens reviewers and labels, and GraphQL does not. Everything below the row is optional
|
||||
* because a node that is not a pull request decodes as an empty object, which is skipped.
|
||||
*/
|
||||
const RawSearchItemSchema = Schema.Struct({
|
||||
...RawStackMembershipSchema.fields,
|
||||
number: Schema.Int,
|
||||
title: Schema.String,
|
||||
url: Schema.String,
|
||||
@@ -221,6 +232,13 @@ const RawStatsSchema = Schema.Struct({
|
||||
),
|
||||
});
|
||||
|
||||
const RawStackMembershipsSchema = Schema.Struct({
|
||||
data: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.NullOr(Schema.Struct({ pullRequest: Schema.NullOr(RawStackMembershipSchema) })),
|
||||
),
|
||||
});
|
||||
|
||||
/** How many of a reaction's people the hover names before it counts the rest. */
|
||||
const REACTORS_PER_GROUP = 10;
|
||||
|
||||
@@ -648,12 +666,13 @@ export const PULL_REQUEST_SEARCH_MAX_ROWS = GRAPHQL_PAGE_SIZE;
|
||||
* than twenty labels shows twenty, and one that has asked more than twenty people for a review
|
||||
* is already past what a row can say.
|
||||
*/
|
||||
export function pullRequestSearchGraphQlQuery(rows: number): string {
|
||||
export function pullRequestSearchGraphQlQuery(rows: number, includeStacks = false): string {
|
||||
return `query($q: String!) {
|
||||
search(query: $q, type: ISSUE, first: ${Math.min(Math.max(Math.trunc(rows), 1), PULL_REQUEST_SEARCH_MAX_ROWS)}) {
|
||||
pageInfo { hasNextPage }
|
||||
nodes {
|
||||
... on PullRequest {
|
||||
${includeStacks ? "stack { number size baseRefName } stackEntry { position }" : ""}
|
||||
number
|
||||
title
|
||||
url
|
||||
@@ -1019,6 +1038,7 @@ export const REPOSITORY_ACCESS_JSON_FIELDS =
|
||||
"mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed,viewerPermission";
|
||||
|
||||
export interface GitHubPullRequestListItem {
|
||||
readonly stack?: PullRequestStackMembership;
|
||||
/** The author's node id, kept so a batch can resolve the avatar the listing does not carry. */
|
||||
readonly authorId: string | null;
|
||||
readonly number: number;
|
||||
@@ -1526,6 +1546,7 @@ export function decodePullRequestSearchJson(
|
||||
const node = decodedNode.value;
|
||||
const repository = trimmed(node.repository?.nameWithOwner);
|
||||
if (repository === null) continue;
|
||||
const stack = toStackMembership(node);
|
||||
items.push({
|
||||
...toListItem({
|
||||
...node,
|
||||
@@ -1541,6 +1562,7 @@ export function decodePullRequestSearchJson(
|
||||
return state === null ? [] : [{ state }];
|
||||
}),
|
||||
}),
|
||||
...(stack === undefined ? {} : { stack }),
|
||||
repository,
|
||||
});
|
||||
}
|
||||
@@ -1551,6 +1573,19 @@ export function decodePullRequestSearchJson(
|
||||
});
|
||||
}
|
||||
|
||||
function toStackMembership(
|
||||
raw: Schema.Schema.Type<typeof RawStackMembershipSchema>,
|
||||
): PullRequestStackMembership | undefined {
|
||||
return raw.stack && raw.stackEntry
|
||||
? {
|
||||
number: raw.stack.number,
|
||||
size: raw.stack.size,
|
||||
base: raw.stack.baseRefName,
|
||||
position: raw.stackEntry.position,
|
||||
}
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** What a repository selector may hold before it is written into a GraphQL document unquoted. */
|
||||
const REPOSITORY_PART = /^[A-Za-z0-9._-]+$/;
|
||||
|
||||
@@ -1581,6 +1616,42 @@ export function buildPullRequestStatsGraphQlQuery(
|
||||
return `query {\n${selections.join("\n")}\n}`;
|
||||
}
|
||||
|
||||
/** Stack membership for the visible rows of a per-repository listing. */
|
||||
export function buildPullRequestStackMembershipsGraphQlQuery(
|
||||
repository: string,
|
||||
numbers: ReadonlyArray<number>,
|
||||
): string | null {
|
||||
if (numbers.length === 0) return null;
|
||||
const [owner, name, ...rest] = repository.trim().split("/");
|
||||
if (rest.length > 0 || owner === undefined || name === undefined) return null;
|
||||
if (!REPOSITORY_PART.test(owner) || !REPOSITORY_PART.test(name)) return null;
|
||||
const selections: string[] = [];
|
||||
for (const [index, number] of numbers.entries()) {
|
||||
if (!Number.isSafeInteger(number) || number <= 0) return null;
|
||||
selections.push(
|
||||
` s${index}: repository(owner: "${owner}", name: "${name}") { pullRequest(number: ${number}) { stack { number size baseRefName } stackEntry { position } } }`,
|
||||
);
|
||||
}
|
||||
return `query PullRequestStackMemberships {\n${selections.join("\n")}\n}`;
|
||||
}
|
||||
|
||||
const decodeStackMemberships = decodeJsonResult(RawStackMembershipsSchema);
|
||||
|
||||
export function decodePullRequestStackMembershipsJson(
|
||||
raw: string,
|
||||
): Result.Result<ReadonlyMap<number, PullRequestStackMembership>, DecodeFailure> {
|
||||
const decoded = decodeStackMemberships(raw);
|
||||
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
|
||||
const memberships = new Map<number, PullRequestStackMembership>();
|
||||
for (const [alias, value] of Object.entries(decoded.success.data)) {
|
||||
const index = /^s(\d+)$/.exec(alias)?.[1];
|
||||
if (index === undefined || value?.pullRequest == null) continue;
|
||||
const stack = toStackMembership(value.pullRequest);
|
||||
if (stack !== undefined) memberships.set(Number(index), stack);
|
||||
}
|
||||
return Result.succeed(memberships);
|
||||
}
|
||||
|
||||
/**
|
||||
* The counts by the position they were asked in. A repository or a pull request GitHub answered
|
||||
* nothing for is simply absent, which leaves the row with whatever it already had.
|
||||
@@ -2448,8 +2519,10 @@ export function decodePullRequestFilesJson(
|
||||
|
||||
/** One pull request as the stacks API lists it: a number, a head, and whether it is done. */
|
||||
const RawStackPullRequestSchema = Schema.Struct({
|
||||
title: Schema.optional(Schema.String),
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
number: Schema.Int,
|
||||
head: Schema.Struct({ ref: Schema.String }),
|
||||
head: Schema.Struct({ ref: Schema.String, sha: Schema.optional(Schema.String) }),
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
@@ -2473,6 +2546,9 @@ const RawStackSchema = Schema.Struct({
|
||||
const decodeStacks = decodeJsonResult(Schema.Array(RawStackSchema));
|
||||
|
||||
export interface GitHubPullRequestStackLayer {
|
||||
readonly title?: string;
|
||||
readonly isDraft?: boolean;
|
||||
readonly headSha?: string;
|
||||
readonly number: number;
|
||||
readonly headBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
@@ -2505,6 +2581,9 @@ export function decodePullRequestStacksJson(
|
||||
url: trimmed(stack.html_url) ?? stack.url,
|
||||
base: typeof stack.base === "string" ? stack.base : stack.base.ref,
|
||||
layers: stack.pull_requests.map((pullRequest) => ({
|
||||
...(pullRequest.title === undefined ? {} : { title: pullRequest.title }),
|
||||
...(pullRequest.draft === undefined ? {} : { isDraft: pullRequest.draft }),
|
||||
...(pullRequest.head.sha === undefined ? {} : { headSha: pullRequest.head.sha }),
|
||||
number: pullRequest.number,
|
||||
headBranch: pullRequest.head.ref,
|
||||
state: toState({ state: pullRequest.state, mergedAt: pullRequest.merged_at }),
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
|
||||
|
||||
const runGitHubStackAction = (
|
||||
execute: GitHubCli.GitHubCli["Service"]["execute"],
|
||||
input: Parameters<typeof runStackAction>[0],
|
||||
) => runStackAction(input).pipe(Effect.provide(Layer.mock(GitHubCli.GitHubCli)({ execute })));
|
||||
|
||||
const stack = [
|
||||
{
|
||||
number: 50,
|
||||
url: "https://api.github.com/repos/acme/web/stacks/50",
|
||||
base: { ref: "main" },
|
||||
pull_requests: [
|
||||
{
|
||||
number: 1,
|
||||
title: "Base",
|
||||
head: { ref: "base", sha: "aaa" },
|
||||
state: "closed",
|
||||
merged_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 2,
|
||||
title: "Middle",
|
||||
head: { ref: "middle", sha: "bbb" },
|
||||
state: "open",
|
||||
draft: false,
|
||||
},
|
||||
{ number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
|
||||
],
|
||||
},
|
||||
];
|
||||
const input = {
|
||||
cwd: "/repo",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
number: 3,
|
||||
stackNumber: 50,
|
||||
expectedStackHeads: [
|
||||
{ number: 2, headSha: "bbb" },
|
||||
{ number: 3, headSha: "ccc" },
|
||||
],
|
||||
action: "merge" as const,
|
||||
};
|
||||
const access = {
|
||||
data: {
|
||||
repository: {
|
||||
pr2: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
|
||||
pr3: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
|
||||
data: {
|
||||
processed: processed.map((headRefOid) => ({ headRefOid })),
|
||||
repository: {
|
||||
pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
const rebased = {
|
||||
data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
|
||||
};
|
||||
const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
|
||||
|
||||
function fake(responses: readonly unknown[]) {
|
||||
const calls: ReadonlyArray<string>[] = [];
|
||||
const execute: GitHubCli.GitHubCli["Service"]["execute"] = (request) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(request.args);
|
||||
const value = responses[calls.length - 1];
|
||||
if (value === undefined) throw new Error("Unexpected GitHub request");
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
stdout: JSON.stringify(value),
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
};
|
||||
});
|
||||
return { execute, calls };
|
||||
}
|
||||
|
||||
it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack, { status: "enqueued", details: {} }]);
|
||||
yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
|
||||
expect(api.calls).toHaveLength(2);
|
||||
expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
|
||||
expect(api.calls[1]).toContain("sha=ccc");
|
||||
expect(api.calls[1]).toContain("merge_action=default");
|
||||
expect(api.calls[1]).toContain("merge_method=squash");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("merges through the selected layer without including later draft layers", () =>
|
||||
Effect.gen(function* () {
|
||||
const fiveLayers = [
|
||||
{
|
||||
...stack[0],
|
||||
pull_requests: Array.from({ length: 5 }, (_, index) => ({
|
||||
number: index + 1,
|
||||
head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
|
||||
state: "open",
|
||||
draft: index >= 3,
|
||||
})),
|
||||
},
|
||||
];
|
||||
const api = fake([fiveLayers, { status: "merged", details: {} }]);
|
||||
yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
number: 3,
|
||||
expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
|
||||
});
|
||||
expect(api.calls).toHaveLength(2);
|
||||
expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
|
||||
expect(api.calls[1]).toContain("sha=sha-3");
|
||||
expect(api.calls[1]).toContain("merge_action=default");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects stale reviewed heads below a selected middle layer", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
number: 2,
|
||||
expectedStackHeads: [{ number: 2, headSha: "old-head" }],
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
|
||||
expect(api.calls).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not merge from an already merged layer", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
number: 1,
|
||||
expectedStackHeads: [],
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackUnsupportedError" },
|
||||
});
|
||||
expect(api.calls).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("polls an accepted merge and reports a later rule rejection", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
{ status: "pending", details: { uuid: "operation" } },
|
||||
{ status: "failed", details: { message: "Required checks have not passed" } },
|
||||
]);
|
||||
const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
|
||||
Effect.result,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* TestClock.adjust("1 second");
|
||||
const result = yield* Fiber.join(fiber);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackMergeRejectedError" },
|
||||
});
|
||||
expect(api.calls[2]).toContain("repos/acme/web/pulls/3/merge-async/operation");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains stack identity and a rejection response without a message", () =>
|
||||
Effect.gen(function* () {
|
||||
const rejection = { status: "failed", details: {} };
|
||||
const api = fake([stack, rejection]);
|
||||
const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: {
|
||||
_tag: "GitHubStackMergeRejectedError",
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
stackNumber: input.stackNumber,
|
||||
cause: rejection,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a changed stack before performing any mutation", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
expectedStackHeads: [
|
||||
{ number: 2, headSha: "old" },
|
||||
{ number: 3, headSha: "ccc" },
|
||||
],
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
|
||||
expect(api.calls).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rebases unmerged layers bottom to top without local git commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack, access, ...rebaseResponses]);
|
||||
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
|
||||
const mutations = api.calls.filter((args) =>
|
||||
args.some((arg) => arg.startsWith("query=mutation")),
|
||||
);
|
||||
expect(mutations).toHaveLength(2);
|
||||
expect(mutations[0]).toContain("id=PR_2");
|
||||
expect(mutations[0]).toContain("sha=bbb");
|
||||
expect(mutations[1]).toContain("id=PR_3");
|
||||
expect(mutations[1]).toContain("sha=ccc");
|
||||
expect(api.calls.every((args) => args[0] === "api")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not update later layers after a rebase failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack, access, branch(2, "bbb")]);
|
||||
const execute: typeof api.execute = (request) =>
|
||||
!request.args.some((arg) => arg.startsWith("query=mutation"))
|
||||
? api.execute(request)
|
||||
: Effect.fail(
|
||||
new GitHubCli.GitHubCliAuthenticationError({
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
cause: new Error("denied"),
|
||||
}),
|
||||
);
|
||||
const result = yield* runGitHubStackAction(execute, { ...input, action: "update-branch" }).pipe(
|
||||
Effect.result,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackRebaseFailedError", number: 2, completed: 0 },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
{
|
||||
data: {
|
||||
repository: {
|
||||
...access.data.repository,
|
||||
pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
action: "update-branch",
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackPermissionError" },
|
||||
});
|
||||
expect(api.calls).toHaveLength(2);
|
||||
expect(api.calls.every((args) => args[0] === "api")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows a fork that explicitly permits maintainer updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
{
|
||||
data: {
|
||||
repository: {
|
||||
...access.data.repository,
|
||||
pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
...rebaseResponses,
|
||||
]);
|
||||
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
|
||||
expect(api.calls.at(-1)).toContain("id=PR_3");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds polling and reports a still-running merge without claiming success", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
...Array.from({ length: 40 }, () => ({ status: "pending", details: { uuid: "operation" } })),
|
||||
]);
|
||||
const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
|
||||
Effect.result,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* TestClock.adjust("6 minutes");
|
||||
expect(yield* Fiber.join(fiber)).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackMergePendingError" },
|
||||
});
|
||||
expect(api.calls.length).toBeLessThan(40);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a push after preflight without rebasing the new revision", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack, access, branch(2, "new-head")]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
action: "update-branch",
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackChangedError", number: 2, completed: 0 },
|
||||
});
|
||||
expect(api.calls).toHaveLength(3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips current layers without submitting a rebase mutation", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([stack, access, branch(2, "bbb", 0), branch(3, "ccc", 0, ["bbb"])]);
|
||||
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
|
||||
expect(api.calls.some((args) => args.some((arg) => arg.startsWith("query=mutation")))).toBe(
|
||||
false,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps earlier progress and stops after a later layer fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
access,
|
||||
branch(2, "bbb"),
|
||||
rebased,
|
||||
branch(3, "ccc", 1, ["rebased-sha"]),
|
||||
{ data: { updatePullRequestBranch: null } },
|
||||
]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
action: "update-branch",
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackRebaseFailedError", number: 3, completed: 1 },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports partial progress when a later head changes during the rebase", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
access,
|
||||
branch(2, "bbb"),
|
||||
rebased,
|
||||
branch(3, "concurrent-head", 1, ["rebased-sha"]),
|
||||
]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
action: "update-branch",
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackChangedError", number: 3, completed: 1 },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
expect(result.failure.message).toContain("Earlier updates remain on GitHub");
|
||||
}
|
||||
expect(
|
||||
api.calls.filter((args) => args.some((arg) => arg.startsWith("query=mutation"))),
|
||||
).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each([false, true])("rejects a push to a processed layer, rebased=%s", (rebasedParent) =>
|
||||
Effect.gen(function* () {
|
||||
const api = fake([
|
||||
stack,
|
||||
access,
|
||||
branch(2, "bbb", rebasedParent ? 1 : 0),
|
||||
...(rebasedParent ? [rebased] : []),
|
||||
branch(3, "ccc", 1, ["concurrent-parent-head"]),
|
||||
]);
|
||||
const result = yield* runGitHubStackAction(api.execute, {
|
||||
...input,
|
||||
action: "update-branch",
|
||||
}).pipe(Effect.result);
|
||||
expect(result).toMatchObject({
|
||||
_tag: "Failure",
|
||||
failure: { _tag: "GitHubStackChangedError", number: 2, completed: 1 },
|
||||
});
|
||||
expect(api.calls.at(-1)?.some((arg) => arg.includes('processed:nodes(ids:["PR_2"])'))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
api.calls.filter((args) => args.some((arg) => arg.startsWith("query=mutation"))),
|
||||
).toHaveLength(rebasedParent ? 1 : 0);
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,418 @@
|
||||
import type {
|
||||
PullRequestAction,
|
||||
PullRequestMergeMethod,
|
||||
PullRequestStackHead,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import { decodePullRequestStacksJson } from "./gitHubPullRequestJson.ts";
|
||||
|
||||
const stackErrorIdentity = {
|
||||
repository: Schema.String,
|
||||
number: Schema.Int,
|
||||
stackNumber: Schema.Int,
|
||||
};
|
||||
|
||||
export class GitHubStackChangedError extends Schema.TaggedError<GitHubStackChangedError>()(
|
||||
"GitHubStackChangedError",
|
||||
{ ...stackErrorIdentity, completed: Schema.Int },
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.completed > 0
|
||||
? `The stack changed at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub. Refresh it before trying again.`
|
||||
: "The stack changed. Refresh it before trying again.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackUnsupportedError extends Schema.TaggedError<GitHubStackUnsupportedError>()(
|
||||
"GitHubStackUnsupportedError",
|
||||
stackErrorIdentity,
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "This operation is not supported for this stack.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackResponseInvalidError extends Schema.TaggedError<GitHubStackResponseInvalidError>()(
|
||||
"GitHubStackResponseInvalidError",
|
||||
{ ...stackErrorIdentity, cause: Schema.optional(Schema.Defect()) },
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "GitHub returned an unreadable stack operation response.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackMergeRejectedError extends Schema.TaggedError<GitHubStackMergeRejectedError>()(
|
||||
"GitHubStackMergeRejectedError",
|
||||
{ ...stackErrorIdentity, cause: Schema.Defect() },
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "GitHub refused the stack merge. Check the stack's branch rules and merge requirements.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackMergePendingError extends Schema.TaggedError<GitHubStackMergePendingError>()(
|
||||
"GitHubStackMergePendingError",
|
||||
stackErrorIdentity,
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "The merge is still running on GitHub. Check its status there before submitting another request.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackPermissionError extends Schema.TaggedError<GitHubStackPermissionError>()(
|
||||
"GitHubStackPermissionError",
|
||||
stackErrorIdentity,
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "You cannot update every branch in this stack. Check write access and fork maintainer permissions before retrying.";
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubStackRebaseFailedError extends Schema.TaggedError<GitHubStackRebaseFailedError>()(
|
||||
"GitHubStackRebaseFailedError",
|
||||
{ ...stackErrorIdentity, completed: Schema.Int, cause: Schema.Defect() },
|
||||
) {
|
||||
get detail(): string {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Stack rebase stopped at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub; resolve the failing layer before retrying.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type GitHubStackActionError =
|
||||
| GitHubStackChangedError
|
||||
| GitHubStackUnsupportedError
|
||||
| GitHubStackResponseInvalidError
|
||||
| GitHubStackMergeRejectedError
|
||||
| GitHubStackMergePendingError
|
||||
| GitHubStackPermissionError
|
||||
| GitHubStackRebaseFailedError;
|
||||
|
||||
const MergeResponse = Schema.Struct({
|
||||
status: Schema.Literals(["pending", "merged", "enqueued", "failed"]),
|
||||
details: Schema.Struct({
|
||||
uuid: Schema.optional(Schema.String),
|
||||
message: Schema.optional(Schema.String),
|
||||
}),
|
||||
});
|
||||
|
||||
const decodeBranchAccess = Schema.decodeEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
data: Schema.Struct({
|
||||
repository: Schema.NullOr(
|
||||
Schema.Record(
|
||||
Schema.String,
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
headRepository: Schema.NullOr(
|
||||
Schema.Struct({ viewerPermission: Schema.NullOr(Schema.String) }),
|
||||
),
|
||||
maintainerCanModify: Schema.Boolean,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const decodeRebaseBranch = Schema.decodeEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
data: Schema.Struct({
|
||||
processed: Schema.optional(
|
||||
Schema.Array(Schema.NullOr(Schema.Struct({ headRefOid: Schema.String }))),
|
||||
),
|
||||
repository: Schema.Struct({
|
||||
pullRequest: Schema.Struct({
|
||||
id: Schema.String,
|
||||
headRefOid: Schema.String,
|
||||
baseRef: Schema.Struct({ compare: Schema.Struct({ behindBy: Schema.Int }) }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const decodeRebaseResponse = Schema.decodeEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
data: Schema.Struct({
|
||||
updatePullRequestBranch: Schema.Struct({
|
||||
pullRequest: Schema.Struct({ headRefOid: Schema.String }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeNodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
|
||||
|
||||
const decodeMergeResponse = Schema.decodeEffect(Schema.fromJsonString(MergeResponse));
|
||||
|
||||
/** Remote-only updates: a stack rebase never switches or rewrites the environment's checkout. */
|
||||
export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* (input: {
|
||||
cwd: string;
|
||||
repository: string;
|
||||
host: string;
|
||||
number: number;
|
||||
stackNumber: number;
|
||||
expectedStackHeads?: ReadonlyArray<PullRequestStackHead>;
|
||||
action: PullRequestAction;
|
||||
mergeMethod?: PullRequestMergeMethod;
|
||||
}) {
|
||||
const github = yield* GitHubCli.GitHubCli;
|
||||
const identity = {
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
stackNumber: input.stackNumber,
|
||||
};
|
||||
if (input.action !== "merge" && input.action !== "update-branch")
|
||||
return yield* new GitHubStackUnsupportedError({ ...identity });
|
||||
const endpoint = `repos/${input.repository}`;
|
||||
const read = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", "--hostname", input.host, `${endpoint}/stacks?pull_request=${input.number}`],
|
||||
});
|
||||
const decoded = decodePullRequestStacksJson(read.stdout);
|
||||
if (Result.isFailure(decoded))
|
||||
return yield* new GitHubStackResponseInvalidError({ ...identity, cause: decoded.failure });
|
||||
const stack = decoded.success;
|
||||
const targetIndex = stack?.layers.findIndex((layer) => layer.number === input.number) ?? -1;
|
||||
const target = stack?.layers[targetIndex];
|
||||
if (
|
||||
stack?.number !== input.stackNumber ||
|
||||
target === undefined ||
|
||||
(input.action === "update-branch" && targetIndex !== stack.layers.length - 1)
|
||||
) {
|
||||
return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 });
|
||||
}
|
||||
const affectedLayers =
|
||||
input.action === "merge" ? stack.layers.slice(0, targetIndex + 1) : stack.layers;
|
||||
const open = affectedLayers.filter((layer) => layer.state !== "merged");
|
||||
if (input.action === "merge" && target.state !== "open")
|
||||
return yield* new GitHubStackUnsupportedError({ ...identity });
|
||||
if (
|
||||
!input.expectedStackHeads ||
|
||||
input.expectedStackHeads.length !== open.length ||
|
||||
new Set(input.expectedStackHeads.map((layer) => layer.number)).size !== open.length ||
|
||||
open.some(
|
||||
(layer) =>
|
||||
!layer.headSha ||
|
||||
!input.expectedStackHeads?.some(
|
||||
(expected) => expected.number === layer.number && expected.headSha === layer.headSha,
|
||||
),
|
||||
)
|
||||
) {
|
||||
return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 });
|
||||
}
|
||||
if (open.length === 0 || open.some((layer) => layer.state !== "open"))
|
||||
return yield* new GitHubStackUnsupportedError({ ...identity });
|
||||
if (input.action === "update-branch") {
|
||||
const [owner, name] = input.repository.split("/");
|
||||
const permissions = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
"graphql",
|
||||
"-f",
|
||||
`owner=${owner}`,
|
||||
"-f",
|
||||
`name=${name}`,
|
||||
"-f",
|
||||
`query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${open
|
||||
.map(
|
||||
(layer) =>
|
||||
`pr${layer.number}:pullRequest(number:${layer.number}){headRepository{viewerPermission} maintainerCanModify}`,
|
||||
)
|
||||
.join(" ")}}}`,
|
||||
],
|
||||
});
|
||||
const access = yield* decodeBranchAccess(permissions.stdout).pipe(
|
||||
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
|
||||
);
|
||||
// viewerCanUpdateBranch is false for an already-current layer, even if rebasing its parent
|
||||
// will make it stale. Check branch write access separately before touching any layer.
|
||||
if (
|
||||
open.some((layer) => {
|
||||
const pr = access.data.repository?.[`pr${layer.number}`];
|
||||
return (
|
||||
!pr?.headRepository ||
|
||||
(!pr.maintainerCanModify &&
|
||||
!["ADMIN", "MAINTAIN", "WRITE"].includes(pr.headRepository.viewerPermission ?? ""))
|
||||
);
|
||||
})
|
||||
)
|
||||
return yield* new GitHubStackPermissionError({ ...identity });
|
||||
const processed: Array<{ id: string; number: number; headSha: string }> = [];
|
||||
for (const [index, layer] of open.entries()) {
|
||||
yield* Effect.gen(function* () {
|
||||
const read = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
"graphql",
|
||||
"-f",
|
||||
`owner=${owner}`,
|
||||
"-f",
|
||||
`name=${name}`,
|
||||
"-F",
|
||||
`number=${layer.number}`,
|
||||
"-f",
|
||||
`sha=${layer.headSha}`,
|
||||
"-f",
|
||||
`query=query($owner:String!,$name:String!,$number:Int!,$sha:String!){${
|
||||
processed.length === 0
|
||||
? ""
|
||||
: `processed:nodes(ids:${encodeNodeIds(processed.map((head) => head.id))}){... on PullRequest{headRefOid}}`
|
||||
} repository(owner:$owner,name:$name){pullRequest(number:$number){id headRefOid baseRef{compare(headRef:$sha){behindBy}}}}}`,
|
||||
],
|
||||
});
|
||||
const {
|
||||
data: {
|
||||
processed: observed,
|
||||
repository: { pullRequest: pr },
|
||||
},
|
||||
} = yield* decodeRebaseBranch(read.stdout);
|
||||
// A push to an earlier layer must not silently become the next layer's new base.
|
||||
const changed = processed.find(
|
||||
(head, index) => observed?.[index]?.headRefOid !== head.headSha,
|
||||
);
|
||||
if (changed !== undefined)
|
||||
return yield* new GitHubStackChangedError({
|
||||
...identity,
|
||||
number: changed.number,
|
||||
completed: index,
|
||||
});
|
||||
if (pr.headRefOid !== layer.headSha)
|
||||
return yield* new GitHubStackChangedError({
|
||||
...identity,
|
||||
number: layer.number,
|
||||
completed: index,
|
||||
});
|
||||
if (pr.baseRef.compare.behindBy === 0) {
|
||||
processed.push({ id: pr.id, number: layer.number, headSha: pr.headRefOid });
|
||||
return;
|
||||
}
|
||||
// Pass the reviewed revision to GitHub, including when a push races this read.
|
||||
const updated = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
"graphql",
|
||||
"-f",
|
||||
`id=${pr.id}`,
|
||||
"-f",
|
||||
`sha=${layer.headSha}`,
|
||||
"-f",
|
||||
"query=mutation($id:ID!,$sha:GitObjectID!){updatePullRequestBranch(input:{pullRequestId:$id,expectedHeadOid:$sha,updateMethod:REBASE}){pullRequest{headRefOid}}}",
|
||||
],
|
||||
});
|
||||
const response = yield* decodeRebaseResponse(updated.stdout);
|
||||
processed.push({
|
||||
id: pr.id,
|
||||
number: layer.number,
|
||||
headSha: response.data.updatePullRequestBranch.pullRequest.headRefOid,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "GitHubStackChangedError"
|
||||
? cause
|
||||
: new GitHubStackRebaseFailedError({
|
||||
...identity,
|
||||
number: layer.number,
|
||||
completed: index,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (open.some((layer) => layer.isDraft))
|
||||
return yield* new GitHubStackUnsupportedError({ ...identity });
|
||||
const decode = (raw: string) =>
|
||||
decodeMergeResponse(raw).pipe(
|
||||
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
|
||||
);
|
||||
const request = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
"--method",
|
||||
"PUT",
|
||||
`${endpoint}/pulls/${input.number}/merge-async`,
|
||||
"-f",
|
||||
`merge_method=${input.mergeMethod ?? "merge"}`,
|
||||
"-f",
|
||||
"merge_action=default",
|
||||
"-f",
|
||||
`sha=${target.headSha}`,
|
||||
],
|
||||
});
|
||||
let result = yield* decode(request.stdout);
|
||||
const deadline = (yield* Clock.currentTimeMillis) + 5 * 60_000;
|
||||
for (
|
||||
let attempt = 0;
|
||||
result.status === "pending" && (yield* Clock.currentTimeMillis) < deadline;
|
||||
attempt++
|
||||
) {
|
||||
const uuid = result.details.uuid;
|
||||
if (!uuid) return yield* new GitHubStackResponseInvalidError({ ...identity });
|
||||
yield* Effect.sleep(Math.min(1_000 * 2 ** attempt, 10_000));
|
||||
const poll = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--hostname",
|
||||
input.host,
|
||||
`${endpoint}/pulls/${input.number}/merge-async/${encodeURIComponent(uuid)}`,
|
||||
],
|
||||
});
|
||||
result = yield* decode(poll.stdout);
|
||||
}
|
||||
if (result.status === "pending") return yield* new GitHubStackMergePendingError({ ...identity });
|
||||
if (result.status === "failed")
|
||||
return yield* new GitHubStackMergeRejectedError({ ...identity, cause: result });
|
||||
});
|
||||
Reference in new issue
Block a user