fix(pull-requests): missing features & better behaviour (#9188)

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-02 20:00:27 -04:00
1 parent 4ba39a6f40
commit 443b4ebfe8
34 files changed
+2241 -205

No files matched your search

@@ -414,7 +414,7 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
);
it.effect.each([
{ action: "enable-auto-merge", expected: ["--auto-complete", "true", "--squash", "false"] },
{ action: "enable-auto-merge", expected: ["--auto-complete", "true"] },
{ action: "disable-auto-merge", expected: ["--auto-complete", "false"] },
{ action: "draft", expected: ["--draft", "true"] },
{ action: "ready", expected: ["--draft", "false"] },
@@ -224,7 +224,13 @@ function actionArgs(
// Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
// it once its policies pass. The squash choice is stored with it, as it is for a merge now.
case "enable-auto-merge":
return ["--auto-complete", "true", "--squash", mergeMethod === "squash" ? "true" : "false"];
return [
"--auto-complete",
"true",
...(mergeMethod === undefined
? []
: ["--squash", mergeMethod === "squash" ? "true" : "false"]),
];
case "disable-auto-merge":
return ["--auto-complete", "false"];
case "ready":
@@ -238,6 +244,10 @@ function actionArgs(
return [];
case "reopen":
return ["--status", "active"];
// Never reached: this host does not declare the action, so the service refuses it first.
case "revert":
case "approve-workflows":
throw new Error(`Azure DevOps pull request action ${action} is unsupported`);
}
}
@@ -169,6 +169,9 @@ export const make = Effect.gen(function* () {
mergeCapabilities: { merge: true, squash: true, rebase: false },
viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
autoMergeEnabled: pullRequest.autoMergeEnabled,
...(pullRequest.autoMergeMethod === undefined
? {}
: { autoMergeMethod: pullRequest.autoMergeMethod }),
}),
),
),
@@ -1200,6 +1200,389 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("opens a pull request that reverts a merged pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh GraphQL response.
JSON.stringify({
data: { repository: { pullRequest: { id: "PR_7" } } },
}),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "revert",
});
expect(callAt(0).args).toContain("owner=acme");
expect(callAt(0).args).toContain("name=web");
expect(callAt(0).args).toContain("number=7");
expect(callAt(1).args).toEqual([
"api",
"graphql",
"--hostname",
"github.com",
"--input",
"-",
]);
expect(callAt(1).stdin).toContain("revertPullRequest");
expect(callAt(1).stdin).toContain('"pullRequestId":"PR_7"');
}),
);
it.effect("does not approve action-required runs for a same-repository pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify({
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
headRefName: "feat/page",
headRefOid: "abc123",
isCrossRepository: false,
headRepositoryOwner: { login: "acme" },
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "approve-workflows",
});
expect(mockedExecute).toHaveBeenCalledTimes(1);
}),
);
it.effect("finds and approves every workflow waiting on a maintainer", () =>
Effect.gen(function* () {
const detail = output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify({
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
headRefName: "feat/page",
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
}),
);
const heads = output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify([
{
number: 7,
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
},
]),
);
const runs = output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify([
{ databaseId: 10, workflowName: "build", url: "https://example.com/10" },
{ databaseId: 11, workflowName: "test", url: "https://example.com/11" },
]),
);
for (const result of [
detail,
heads,
runs,
detail,
heads,
runs,
output(""),
detail,
heads,
runs,
output(""),
]) {
mockedExecute.mockReturnValueOnce(Effect.succeed(result));
}
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "approve-workflows",
});
expect(callAt(1).args).toEqual([
"pr",
"list",
"--repo",
"github.com/acme/web",
"--state",
"open",
"--head",
"feat/page",
"--limit",
"1001",
"--json",
"number,headRefOid,isCrossRepository,headRepositoryOwner",
]);
expect(callAt(2).args).toEqual([
"run",
"list",
"--repo",
"github.com/acme/web",
"--commit",
"abc123",
"--branch",
"feat/page",
"--event",
"pull_request",
"--status",
"action_required",
"--limit",
"1001",
"--json",
"databaseId,workflowName,url",
]);
expect([callAt(6).args, callAt(10).args]).toEqual([
[
"api",
"--method",
"POST",
"--hostname",
"github.com",
"repos/acme/web/actions/runs/10/approve",
"--silent",
],
[
"api",
"--method",
"POST",
"--hostname",
"github.com",
"repos/acme/web/actions/runs/11/approve",
"--silent",
],
]);
expect(mockedExecute).toHaveBeenCalledTimes(11);
}),
);
it.effect("refuses a stale workflow approval after the pull request head changes", () =>
Effect.gen(function* () {
const detail = {
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
headRefName: "feat/page",
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
};
for (const value of [
detail,
[
{
number: 7,
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
},
],
[{ databaseId: 10, workflowName: "build", url: "https://example.com/10" }],
{ ...detail, headRefOid: "def456" },
]) {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify(value),
),
),
);
}
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "approve-workflows",
}),
);
expect(error).toMatchObject({
_tag: "GitHubWorkflowApprovalHeadChangedError",
number: 7,
});
expect(mockedExecute).toHaveBeenCalledTimes(4);
}),
);
it.effect("refuses workflow approval when one head belongs to several pull requests", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify(
[7, 8].map((number) => ({
number,
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
})),
),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.listWorkflowRunsRequiringApproval({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
headSha: "abc123",
headBranch: "feat/page",
headRepositoryOwner: "octocat",
isCrossRepository: true,
}),
);
expect(error).toMatchObject({
_tag: "GitHubWorkflowApprovalRefusedError",
reason: "head-not-unique",
number: 7,
observedCount: 2,
limit: 1_000,
});
expect(error.detail).toContain("instead of uniquely matching #7");
expect(mockedExecute).toHaveBeenCalledTimes(1);
}),
);
it.effect("refuses workflow approval when GitHub omits the head repository", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify({
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
headRefName: "feat/page",
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: null,
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "approve-workflows",
}),
);
expect(error).toMatchObject({
_tag: "GitHubWorkflowApprovalHeadUnavailableError",
number: 7,
});
expect(mockedExecute).toHaveBeenCalledTimes(1);
}),
);
it.effect("surfaces a workflow run list beyond the safe approval bound", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify([
{
number: 7,
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { login: "octocat" },
},
]),
),
),
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off - canned gh response.
JSON.stringify(Array.from({ length: 1_001 }, (_, id) => ({ databaseId: id + 1 }))),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.listWorkflowRunsRequiringApproval({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
headSha: "abc123",
headBranch: "feat/page",
headRepositoryOwner: "octocat",
isCrossRepository: true,
}),
);
expect(error).toMatchObject({
_tag: "GitHubWorkflowApprovalRefusedError",
reason: "run-list-truncated",
number: 7,
observedCount: 1_001,
limit: 1_000,
});
expect(error.detail).toContain("more than 1000 workflow runs");
expect(mockedExecute).toHaveBeenCalledTimes(2);
}),
);
it.effect("returns a pull request to draft by undoing ready", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -2136,7 +2519,7 @@ layer("GitHubPullRequestCli.layer", (it) => {
expect(detail.body).toBe("Core body");
expect(activity.author?.login).toBe("octocat");
expect(callAt(0).args.at(-1)).toBe(
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup,body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest",
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup,body,changedFiles,closedAt,isCrossRepository,headRepositoryOwner,headRefOid,autoMergeRequest",
);
expect(callAt(1).args.at(-1)).toBe("author,comments,reviews,commits");
}),
@@ -34,6 +34,7 @@ import {
decodePullRequestActivityJson,
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestHeadsJson,
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
@@ -56,6 +57,7 @@ import {
PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
REMOVE_REACTION_GRAPHQL_MUTATION,
REVERT_PULL_REQUEST_GRAPHQL_MUTATION,
gitHubReactionContent,
REPOSITORY_ACCESS_JSON_FIELDS,
RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
@@ -71,13 +73,16 @@ import {
UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
VIEWER_PERMISSIONS_GRAPHQL_QUERY,
decodeViewerPermissionsJson,
decodeWorkflowRunApprovalsJson,
type GitHubBaseComparison,
type GitHubPullRequestDetail,
type GitHubPullRequestActivity,
type GitHubPullRequestHead,
type GitHubPullRequestListItem,
type GitHubPullRequestSearchItem,
type GitHubReviewThreadComments,
type GitHubRepositoryAccess,
type GitHubWorkflowRunApproval,
type GitHubReviewThreadEntry,
type GitHubReviewThreadPage,
type GitHubViewerAccess,
@@ -259,6 +264,69 @@ export class GitHubSubjectScopeError extends Schema.TaggedErrorClass<GitHubSubje
}
}
/** GitHub answered successfully, but approving every returned workflow would be unsafe. */
export class GitHubWorkflowApprovalRefusedError extends Schema.TaggedErrorClass<GitHubWorkflowApprovalRefusedError>()(
"GitHubWorkflowApprovalRefusedError",
{
command: Schema.Literal("gh"),
cwd: Schema.String,
number: Schema.Int,
reason: Schema.Literals(["head-list-truncated", "head-not-unique", "run-list-truncated"]),
observedCount: Schema.Int,
limit: Schema.Int,
},
) {
get detail(): string {
if (this.reason === "head-list-truncated") {
return `GitHub returned more than ${this.limit} pull requests for this head branch.`;
}
if (this.reason === "head-not-unique") {
return `The head revision matched ${this.observedCount} pull requests instead of uniquely matching #${this.number}.`;
}
return `GitHub returned more than ${this.limit} workflow runs awaiting approval.`;
}
override get message(): string {
return `GitHub CLI refused listWorkflowRunsRequiringApproval: ${this.detail}`;
}
}
/** GitHub omitted the immutable head identity needed to scope an approval safely. */
export class GitHubWorkflowApprovalHeadUnavailableError extends Schema.TaggedErrorClass<GitHubWorkflowApprovalHeadUnavailableError>()(
"GitHubWorkflowApprovalHeadUnavailableError",
{
command: Schema.Literal("gh"),
cwd: Schema.String,
number: Schema.Int,
},
) {
get detail(): string {
return `GitHub did not report a complete head revision for #${this.number}.`;
}
override get message(): string {
return `GitHub CLI refused approve-workflows: ${this.detail}`;
}
}
/** The pull request moved after its approval candidates were read. */
export class GitHubWorkflowApprovalHeadChangedError extends Schema.TaggedErrorClass<GitHubWorkflowApprovalHeadChangedError>()(
"GitHubWorkflowApprovalHeadChangedError",
{
command: Schema.Literal("gh"),
cwd: Schema.String,
number: Schema.Int,
},
) {
get detail(): string {
return `The head revision of #${this.number} changed before its workflows could be approved.`;
}
override get message(): string {
return `GitHub CLI refused approve-workflows: ${this.detail}`;
}
}
export type GitHubPullRequestCliError =
| GitHubCli.GitHubCliError
| GitHubPullRequestReadError
@@ -268,6 +336,9 @@ export type GitHubPullRequestCliError =
| GitHubDiffFileContentsUnavailableError
| GitHubRepositorySelectorError
| GitHubSubjectScopeError
| GitHubWorkflowApprovalRefusedError
| GitHubWorkflowApprovalHeadUnavailableError
| GitHubWorkflowApprovalHeadChangedError
| SourceControlRateLimit.SourceControlRateLimitPausedError
| GitHubViewerLoginUnavailableError
| GitHubPullRequestUpdatedAtUnavailableError;
@@ -405,6 +476,17 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
}) => Effect.Effect<GitHubPullRequestDetail, GitHubPullRequestCliError>;
readonly listWorkflowRunsRequiringApproval: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly headSha: string;
readonly headBranch: string;
readonly headRepositoryOwner: string;
readonly isCrossRepository: true;
}) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestCliError>;
/**
* How far the branch trails its base, and whether this viewer may update it. Its own read
* because the comparison needs the head ref the detail answers with — a fork's branch is not
@@ -864,6 +946,12 @@ function actionArgs(
return ["close"];
case "reopen":
return ["reopen"];
case "revert":
throw new Error("Revert requires a GraphQL mutation");
// Handled separately because it may approve several workflow runs rather than mutate the
// pull request itself.
case "approve-workflows":
throw new Error("Workflow approval requires run discovery");
}
}
@@ -1194,6 +1282,158 @@ export const make = Effect.gen(function* () {
return { oldContents, newContents };
});
const getPullRequestDetail: GitHubPullRequestCli["Service"]["getPullRequestDetail"] = (input) =>
github
.execute({
cwd: input.cwd,
args: [
"pr",
"view",
String(input.number),
...repositoryArgs(input),
"--json",
PULL_REQUEST_DETAIL_JSON_FIELDS,
],
})
.pipe(
Effect.flatMap((result) => {
const decoded = decodePullRequestDetailJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestDetail",
cause: decoded.failure,
}),
);
}),
);
const workflowApprovalLimit = 1_000;
const workflowApprovalProbeLimit = String(workflowApprovalLimit + 1);
const workflowApprovalReadError = (cwd: string, cause: unknown) =>
new GitHubPullRequestReadError({
command: "gh",
cwd,
operation: "listWorkflowRunsRequiringApproval",
cause,
});
const listWorkflowRunsRequiringApproval: GitHubPullRequestCli["Service"]["listWorkflowRunsRequiringApproval"] =
(input) =>
github
.execute({
cwd: input.cwd,
args: [
"pr",
"list",
...repositoryArgs(input),
"--state",
"open",
"--head",
input.headBranch,
"--limit",
workflowApprovalProbeLimit,
"--json",
"number,headRefOid,isCrossRepository,headRepositoryOwner",
],
})
.pipe(
Effect.flatMap(
(
result,
): Effect.Effect<
GitHubPullRequestHead,
GitHubPullRequestReadError | GitHubWorkflowApprovalRefusedError
> => {
const decoded = decodePullRequestHeadsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(workflowApprovalReadError(input.cwd, decoded.failure));
}
const exactHeads = decoded.success.filter(
(pullRequest) =>
pullRequest.headSha === input.headSha &&
pullRequest.isCrossRepository === true &&
pullRequest.headRepositoryOwner?.toLowerCase() ===
input.headRepositoryOwner.toLowerCase(),
);
if (decoded.success.length > workflowApprovalLimit) {
return Effect.fail(
new GitHubWorkflowApprovalRefusedError({
command: "gh",
cwd: input.cwd,
number: input.number,
reason: "head-list-truncated",
observedCount: decoded.success.length,
limit: workflowApprovalLimit,
}),
);
}
if (exactHeads.length !== 1 || exactHeads[0]?.number !== input.number) {
return Effect.fail(
new GitHubWorkflowApprovalRefusedError({
command: "gh",
cwd: input.cwd,
number: input.number,
reason: "head-not-unique",
observedCount: exactHeads.length,
limit: workflowApprovalLimit,
}),
);
}
return Effect.succeed(exactHeads[0]);
},
),
Effect.flatMap(() =>
github.execute({
cwd: input.cwd,
args: [
"run",
"list",
...repositoryArgs(input),
"--commit",
input.headSha,
"--branch",
input.headBranch,
"--event",
"pull_request",
"--status",
"action_required",
"--limit",
workflowApprovalProbeLimit,
"--json",
"databaseId,workflowName,url",
],
}),
),
Effect.flatMap(
(
result,
): Effect.Effect<
ReadonlyArray<GitHubWorkflowRunApproval>,
GitHubPullRequestReadError | GitHubWorkflowApprovalRefusedError
> => {
const decoded = decodeWorkflowRunApprovalsJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(workflowApprovalReadError(input.cwd, decoded.failure));
}
return decoded.success.length > workflowApprovalLimit
? Effect.fail(
new GitHubWorkflowApprovalRefusedError({
command: "gh",
cwd: input.cwd,
number: input.number,
reason: "run-list-truncated",
observedCount: decoded.success.length,
limit: workflowApprovalLimit,
}),
)
: Effect.succeed(decoded.success);
},
),
);
return GitHubPullRequestCli.of({
getViewerLogin: (input) =>
github.execute({ cwd: input.cwd, args: ["api", "user", "--jq", ".login"] }).pipe(
@@ -1393,34 +1633,8 @@ export const make = Effect.gen(function* () {
),
),
getPullRequestDetail: (input) =>
github
.execute({
cwd: input.cwd,
args: [
"pr",
"view",
String(input.number),
...repositoryArgs(input),
"--json",
PULL_REQUEST_DETAIL_JSON_FIELDS,
],
})
.pipe(
Effect.flatMap((result) => {
const decoded = decodePullRequestDetailJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestDetail",
cause: decoded.failure,
}),
);
}),
),
getPullRequestDetail,
listWorkflowRunsRequiringApproval,
getPullRequestBaseComparison: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
@@ -1764,6 +1978,106 @@ export const make = Effect.gen(function* () {
},
runPullRequestAction: (input) => {
if (input.action === "revert") {
return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe(
Effect.flatMap((pullRequestId) =>
graphql({
cwd: input.cwd,
host: input.host,
query: REVERT_PULL_REQUEST_GRAPHQL_MUTATION,
variables: { pullRequestId },
}),
),
);
}
if (input.action === "approve-workflows") {
const { owner, name } = parseRepositorySelector(input.repository);
return getPullRequestDetail(input).pipe(
Effect.flatMap((detail) => {
if (detail.isCrossRepository !== true) return Effect.void;
if (detail.headSha == null || detail.headRepositoryOwner == null) {
return Effect.fail(
new GitHubWorkflowApprovalHeadUnavailableError({
command: "gh",
cwd: input.cwd,
number: input.number,
}),
);
}
const expectedHeadSha = detail.headSha;
const expectedHeadBranch = detail.headBranch;
const expectedHeadRepositoryOwner = detail.headRepositoryOwner;
return listWorkflowRunsRequiringApproval({
...input,
headSha: expectedHeadSha,
headBranch: expectedHeadBranch,
headRepositoryOwner: expectedHeadRepositoryOwner,
isCrossRepository: true,
}).pipe(
Effect.flatMap((runs) =>
Effect.forEach(
runs,
(run) =>
getPullRequestDetail(input).pipe(
Effect.flatMap((current) => {
if (current.headSha == null || current.headRepositoryOwner == null) {
return Effect.fail(
new GitHubWorkflowApprovalHeadUnavailableError({
command: "gh",
cwd: input.cwd,
number: input.number,
}),
);
}
if (
current.isCrossRepository !== true ||
current.headSha !== expectedHeadSha ||
current.headBranch !== expectedHeadBranch ||
current.headRepositoryOwner.toLowerCase() !==
expectedHeadRepositoryOwner.toLowerCase()
) {
return Effect.fail(
new GitHubWorkflowApprovalHeadChangedError({
command: "gh",
cwd: input.cwd,
number: input.number,
}),
);
}
return listWorkflowRunsRequiringApproval({
...input,
headSha: current.headSha,
headBranch: current.headBranch,
headRepositoryOwner: current.headRepositoryOwner,
isCrossRepository: true,
});
}),
Effect.flatMap((currentRuns) =>
currentRuns.some((current) => current.id === run.id)
? github
.execute({
cwd: input.cwd,
args: [
"api",
"--method",
"POST",
"--hostname",
input.host,
`repos/${owner}/${name}/actions/runs/${run.id}/approve`,
"--silent",
],
})
.pipe(Effect.asVoid)
: Effect.void,
),
),
{ concurrency: 1, discard: true },
),
),
);
}),
);
}
const [subcommand, ...flags] = actionArgs(
input.action,
input.mergeMethod,
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { PullRequestReaction } from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
@@ -52,6 +53,8 @@ describe("gitHubViewerPermissions", () => {
"merge",
"enable-auto-merge",
"disable-auto-merge",
"revert",
"approve-workflows",
"ready",
"draft",
"close",
@@ -108,6 +111,13 @@ describe("gitHubViewerPermissions", () => {
verdicts: ["comment", "approve", "request-changes"],
requestReviewers: false,
});
expect(detail.workflowApprovalsRequired).toBeUndefined();
expect(detail.checks).toContainEqual({
name: "Workflow approval status",
status: "action-required",
description: "GitHub could not determine whether workflows are awaiting approval.",
url: null,
});
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
@@ -118,6 +128,7 @@ describe("gitHubViewerPermissions", () => {
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
isCrossRepository: true,
headRepositoryOwner: null,
headBranch: "feat/page",
baseBranch: "main",
@@ -152,39 +163,254 @@ describe("gitHubViewerPermissions", () => {
),
),
);
it.effect("keeps fork workflows awaiting approval out of the passing state", () =>
Effect.gen(function* () {
const provider = yield* make;
const detail = yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(detail.workflowApprovalsRequired).toBe(1);
expect(detail.checks).toEqual([
{
name: "manual gate",
status: "action-required",
description: null,
url: "https://example.com/manual-gate",
},
{
name: "build",
status: "success",
description: null,
url: null,
},
{
name: "contributor tests",
status: "action-required",
description: "A maintainer must approve this workflow before it can run.",
url: "https://github.com/acme/web/actions/runs/123",
},
]);
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () =>
Effect.succeed({
authorId: null,
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
isCrossRepository: true,
headRepositoryOwner: "octocat",
headSha: "abc123",
headBranch: "feat/page",
baseBranch: "main",
state: "open",
isDraft: false,
mergeability: "mergeable",
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: "passing",
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
checks: [
{
name: "manual gate",
status: "action-required",
description: null,
url: "https://example.com/manual-gate",
},
{ name: "build", status: "success", description: null, url: null },
],
comments: [],
commits: [],
}),
listWorkflowRunsRequiringApproval: () =>
Effect.succeed([
{
id: 123,
name: "contributor tests",
url: "https://github.com/acme/web/actions/runs/123",
},
]),
getPullRequestBaseComparison: () =>
Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
getRepositoryAccess: () =>
Effect.succeed({
canWrite: true,
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
});
describe("getViewerPermissions", () => {
const openDetail = {
authorId: null,
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
headRepositoryOwner: "acme",
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
checks: [],
comments: [],
commits: [],
};
const openDetail = {
authorId: null,
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
isCrossRepository: true,
headRepositoryOwner: "acme",
headSha: "abc123",
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
checks: [],
comments: [],
commits: [],
};
it.effect("does not classify same-repository gates as fork workflow approvals", () =>
Effect.gen(function* () {
const provider = yield* make;
const detail = yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(detail.workflowApprovalsRequired).toBe(0);
expect(detail.checks).toEqual([]);
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
listWorkflowRunsRequiringApproval: () =>
Effect.die("same-repository pull requests must not probe fork workflow approvals"),
getRepositoryAccess: () =>
Effect.succeed({
canWrite: true,
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
Effect.gen(function* () {
const provider = yield* make;
const detail = yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(detail.workflowApprovalsRequired).toBeUndefined();
expect(detail.checks).toEqual([
{
name: "Workflow approval status",
status: "action-required",
description: "GitHub could not determine whether workflows are awaiting approval.",
url: null,
},
]);
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
listWorkflowRunsRequiringApproval: () =>
Effect.fail(
new GitHubPullRequestCli.GitHubWorkflowApprovalRefusedError({
command: "gh",
cwd: "/w",
number: 7,
reason: "head-not-unique",
observedCount: 2,
limit: 1_000,
}),
),
getRepositoryAccess: () =>
Effect.succeed({
canWrite: true,
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
it.effect("propagates workflow discovery rate limits", () =>
Effect.gen(function* () {
const provider = yield* make;
const error = yield* provider
.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
})
.pipe(Effect.flip);
expect(error.operation).toBe("getChangeRequest");
expect(error.reason).toBe("rate-limited");
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
listWorkflowRunsRequiringApproval: () =>
Effect.fail(
new GitHubCli.GitHubCliRateLimitError({
command: "gh",
cwd: "/w",
cause: new Error("rate limited"),
}),
),
getRepositoryAccess: () =>
Effect.succeed({
canWrite: true,
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
describe("getViewerPermissions", () => {
const layerWithComparison = (
comparison: Effect.Effect<{
readonly behindBy: number | null;
@@ -5,6 +5,7 @@ import * as Exit from "effect/Exit";
import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestCheck,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
@@ -17,7 +18,7 @@ import {
type ProviderChangeRequestDetail,
type PullRequestProviderApi,
} from "./PullRequestProvider.ts";
import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
import type { GitHubViewerAccess, GitHubWorkflowRunApproval } from "./gitHubPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
@@ -31,6 +32,8 @@ const CAPABILITIES: PullRequestCapabilities = {
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
"revert",
"approve-workflows",
],
mergeMethods: ["merge", "squash", "rebase"],
updateMethods: ["merge", "rebase"],
@@ -68,7 +71,15 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
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.
...(access.canWrite ? (["merge", "enable-auto-merge", "disable-auto-merge"] as const) : []),
...(access.canWrite
? ([
"merge",
"enable-auto-merge",
"disable-auto-merge",
"revert",
"approve-workflows",
] as const)
: []),
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
// Whether this viewer may update the branch is GitHub's own answer, read with the
// comparison; without it the action is offered to nobody rather than to everybody.
@@ -117,6 +128,43 @@ function withAvatar(
return avatarUrl === null ? actor : { ...actor, avatarUrl };
}
function withWorkflowApprovals(
checks: ReadonlyArray<PullRequestCheck>,
runs: ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: boolean,
): ReadonlyArray<PullRequestCheck> {
const representedRunIds = new Set<number>();
for (const check of checks) {
if (check.status !== "action-required" || check.url === null) continue;
const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
if (id !== undefined) representedRunIds.add(Number(id));
}
const approvalChecks = runs
.filter((run) => !representedRunIds.has(run.id))
.map(
(run): PullRequestCheck => ({
name: run.name,
status: "action-required",
description: "A maintainer must approve this workflow before it can run.",
url: run.url,
}),
);
return [
...checks,
...approvalChecks,
...(unavailable
? [
{
name: "Workflow approval status",
status: "action-required" as const,
description: "GitHub could not determine whether workflows are awaiting approval.",
url: null,
},
]
: []),
];
}
/**
* Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
* names no page, and a guessed URL that 404s is worse than the initials it would replace.
@@ -250,20 +298,54 @@ export const make = Effect.gen(function* () {
[
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
// Only an open pull request can be behind anything worth saying so about, and only
// one whose head repository is known can be compared at all. A comparison that
// fails is left unknown: the banner is an offer, never a blocker.
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed({ pullRequest, comparison: null })
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(
Effect.map((comparison) => ({ pullRequest, comparison })),
Effect.orElseSucceed(() => ({ pullRequest, comparison: null })),
),
Effect.all({
// Only an open pull request can be behind anything worth saying so about, and
// only one whose head repository is known can be compared at all.
comparison:
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed(null)
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(Effect.orElseSucceed(() => null)),
// GitHub omits a fork workflow that has not been approved from the normal check
// rollup. Read the action-required runs by head revision so "all passed" cannot
// be shown while a whole workflow is still waiting to start.
workflowApprovals:
pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
? Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: false,
})
: pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
? Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: true,
})
: cli
.listWorkflowRunsRequiringApproval({
...input,
headSha: pullRequest.headSha,
headBranch: pullRequest.headBranch,
headRepositoryOwner: pullRequest.headRepositoryOwner,
isCrossRepository: true,
})
.pipe(
Effect.matchEffect({
onFailure: (error) =>
error._tag === "GitHubCliRateLimitError" ||
error._tag === "SourceControlRateLimitPausedError"
? Effect.fail(error)
: Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: true,
}),
onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
}),
),
}).pipe(Effect.map((extra) => ({ pullRequest, ...extra }))),
),
),
getRepositoryAccess({
@@ -281,6 +363,14 @@ export const make = Effect.gen(function* () {
Effect.map(
([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
...detail.pullRequest,
checks: withWorkflowApprovals(
detail.pullRequest.checks,
detail.workflowApprovals.runs,
detail.workflowApprovals.unavailable,
),
...(detail.workflowApprovals.unavailable
? {}
: { workflowApprovalsRequired: detail.workflowApprovals.runs.length }),
reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
login,
name: null,
@@ -504,6 +504,10 @@ function actionArgs(
return ["rebase"];
case "reopen":
return ["reopen"];
// Never reached: this host does not declare the action, so the service refuses it first.
case "revert":
case "approve-workflows":
throw new Error(`GitLab merge request action ${action} is unsupported`);
}
}
@@ -177,6 +177,10 @@ export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
readonly behindBy?: number;
/** Absent from a host that does not report whether it is armed to merge this on its own. */
readonly autoMergeEnabled?: boolean;
/** The strategy stored with an armed auto-merge, where the host reports it. */
readonly autoMergeMethod?: PullRequestMergeMethod;
/** Workflow runs on this head commit that still need a maintainer's approval. */
readonly workflowApprovalsRequired?: number;
}
/** The conversation-shaped half of a detail, loaded after the core can already render. */
@@ -202,6 +202,9 @@ const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
"You need write access on this repository to have it merged for you once it is ready.",
"disable-auto-merge":
"You need write access on this repository to stop it being merged for you once it is ready.",
revert: "You need write access on this repository to open a revert pull request.",
"approve-workflows":
"You need write access on this repository to approve workflows from a fork pull request.",
};
/**
@@ -1290,6 +1293,12 @@ export const make = Effect.gen(function* () {
...(changeRequest.autoMergeEnabled === undefined
? {}
: { autoMergeEnabled: changeRequest.autoMergeEnabled }),
...(changeRequest.autoMergeMethod === undefined
? {}
: { autoMergeMethod: changeRequest.autoMergeMethod }),
...(changeRequest.workflowApprovalsRequired === undefined
? {}
: { workflowApprovalsRequired: changeRequest.workflowApprovalsRequired }),
}),
),
),
@@ -159,6 +159,34 @@ describe("decodePullRequestJson", () => {
);
});
it("keeps the strategy stored with auto-complete", () => {
const armed = expectSuccess(
decodePullRequestJson(
asJson(
pullRequest({
autoCompleteSetBy: { displayName: "Bilal Hassan" },
completionOptions: { mergeStrategy: "squash" },
}),
),
),
);
expect(armed).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
const unspecified = expectSuccess(
decodePullRequestJson(
asJson(
pullRequest({
autoCompleteSetBy: { displayName: "Bilal Hassan" },
completionOptions: { squashMerge: false },
}),
),
),
);
expect(unspecified?.autoMergeEnabled).toBe(true);
expect(unspecified?.autoMergeMethod).toBeUndefined();
});
it("works out where the conversation lives from what Azure returned", () => {
const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
@@ -5,6 +5,7 @@ import * as Schema from "effect/Schema";
import type {
PullRequestActor,
PullRequestComment,
PullRequestMergeMethod,
PullRequestMergeability,
PullRequestState,
} from "@t3tools/contracts";
@@ -41,6 +42,14 @@ const RawPullRequestSchema = Schema.Struct({
* entirely once nobody has. So its presence is the answer, and there is no third state.
*/
autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
completionOptions: Schema.optional(
Schema.NullOr(
Schema.Struct({
mergeStrategy: Schema.optional(Schema.NullOr(Schema.String)),
squashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
}),
),
),
mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
@@ -132,6 +141,8 @@ export interface AzureDevOpsPullRequest {
readonly threadsUrl: string | null;
/** Whether Azure is set to complete this on its own once its policies pass. */
readonly autoMergeEnabled: boolean;
/** The completion strategy Azure stored with auto-complete, where it reported one. */
readonly autoMergeMethod?: PullRequestMergeMethod;
}
function trimmed(value: string | null | undefined): string | null {
@@ -188,6 +199,23 @@ function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): str
return `${base}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repository)}/pullRequests/${raw.pullRequestId}/threads`;
}
function toAutoMergeMethod(
raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
): PullRequestMergeMethod | undefined {
if (raw.autoCompleteSetBy == null) return undefined;
switch (raw.completionOptions?.mergeStrategy?.trim().toLowerCase()) {
case "squash":
return "squash";
case "rebase":
case "rebasemerge":
return "rebase";
case "nofastforward":
return "merge";
default:
return raw.completionOptions?.squashMerge === true ? "squash" : undefined;
}
}
/**
* Null when Azure said too little to place the pull request: a row with no browser url and no
* branch left after its prefix is dropped cannot be rendered or opened, and the wire contract
@@ -196,6 +224,7 @@ function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): str
function toPullRequest(
raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
): AzureDevOpsPullRequest | null {
const autoMergeMethod = toAutoMergeMethod(raw);
const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
const actor = toActor(reviewer);
return actor === null ? [] : [actor];
@@ -232,6 +261,7 @@ function toPullRequest(
reviewers,
threadsUrl: toThreadsUrl(raw),
autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
};
}
@@ -16,6 +16,7 @@ import {
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
decodeViewerPermissionsJson,
decodeWorkflowRunApprovalsJson,
reviewThreadConversation,
REVIEW_THREADS_GRAPHQL_QUERY,
} from "./gitHubPullRequestJson.ts";
@@ -223,18 +224,56 @@ describe("pull request detail decoding", () => {
]);
});
it("reads an auto-merge request as armed, its null as off and its absence as neither", () => {
it("keeps a workflow waiting for approval out of the passing state", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestDetailJson(
JSON.stringify({
...raw,
statusCheckRollup: [
{ __typename: "CheckRun", name: "build", status: "COMPLETED", conclusion: "SUCCESS" },
{
__typename: "CheckRun",
name: "contributor tests",
status: "COMPLETED",
conclusion: "ACTION_REQUIRED",
},
],
}),
),
);
expect(detail.checks.map((check) => check.status)).toEqual(["success", "action-required"]);
expect(detail.checksState).toBe("pending");
});
it("decodes workflow runs that can be approved", () => {
expect(
expectSuccess(
decodeWorkflowRunApprovalsJson(
JSON.stringify([
{ databaseId: 10, workflowName: "contributor tests", url: "https://example.com/10" },
{ databaseId: 11, workflowName: null, url: null },
]),
),
),
).toEqual([
{ id: 10, name: "contributor tests", url: "https://example.com/10" },
{ id: 11, name: "Workflow run 11", url: null },
]);
});
it("reads an auto-merge request and strategy, its null as off and its absence as neither", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const armed = (entry: Record<string, unknown>) =>
expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })))
.autoMergeEnabled;
expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })));
expect(
armed({ autoMergeRequest: { enabledBy: { login: "octocat" }, mergeMethod: "SQUASH" } }),
).toBe(true);
expect(armed({ autoMergeRequest: null })).toBe(false);
).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
expect(armed({ autoMergeRequest: null }).autoMergeEnabled).toBe(false);
// `gh` not answering for the field at all is not GitHub saying the merge is unarmed.
expect(armed({})).toBeUndefined();
expect(armed({}).autoMergeEnabled).toBeUndefined();
});
it("shows a re-running check once, as the run that is happening now", () => {
@@ -419,6 +458,36 @@ describe("review thread decoding", () => {
]);
});
it("omits misleading line counts from merge commits", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
JSON.stringify({
data: {
repository: {
pullRequest: {
reviewThreads: { totalCount: 0, nodes: [] },
commits: {
nodes: [
{
commit: {
oid: "merge123",
additions: 36_858,
deletions: 12_928,
parents: { totalCount: 2 },
},
},
],
},
},
},
},
}),
),
);
expect([...result.commitStats]).toEqual([]);
});
it("decodes the newest commits off the same connection, oldest to newest", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
@@ -11,6 +11,7 @@ import type {
PullRequestCommit,
PullRequestLabel,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestOmittedFileStat,
PullRequestMergeability,
PullRequestReaction,
@@ -359,17 +360,32 @@ const RawCommitSchema = Schema.Struct({
const RawDetailSchema = Schema.Struct({
...RawListItemSchema.fields,
/** GitHub's explicit distinction between a fork head and a branch in the base repository. */
isCrossRepository: Schema.optional(Schema.Boolean),
/** Names the fork a pull request came from, which is what qualifies its head ref. */
headRepositoryOwner: Schema.optional(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
/** The exact head revision, used to find workflow runs that GitHub has not started yet. */
headRefOid: Schema.optional(Schema.NullOr(Schema.String)),
body: Schema.optional(Schema.String),
changedFiles: Schema.optional(Schema.Int),
closedAt: Schema.optional(Schema.NullOr(Schema.String)),
/**
* The standing instruction to merge once GitHub's own requirements are met, which is an object
* describing who armed it and how, and a JSON null where nobody has. Nothing inside it is read:
* the question the page asks is whether one exists.
*/
autoMergeRequest: Schema.optional(Schema.NullOr(Schema.Unknown)),
/** The standing instruction and strategy GitHub will use once its requirements are met. */
autoMergeRequest: Schema.optional(
Schema.NullOr(Schema.Struct({ mergeMethod: Schema.optional(Schema.NullOr(Schema.String)) })),
),
});
const RawWorkflowRunApprovalSchema = Schema.Struct({
databaseId: Schema.Int,
workflowName: Schema.optional(Schema.NullOr(Schema.String)),
url: Schema.optional(Schema.NullOr(Schema.String)),
});
const RawPullRequestHeadSchema = Schema.Struct({
number: Schema.Int,
headRefOid: Schema.String,
isCrossRepository: Schema.optional(Schema.Boolean),
headRepositoryOwner: Schema.optional(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
});
const RawActivitySchema = Schema.Struct({
@@ -508,6 +524,9 @@ const RawReviewThreadsSchema = Schema.Struct({
committedDate: Schema.optional(Schema.NullOr(Schema.String)),
additions: Schema.optional(Schema.Int),
deletions: Schema.optional(Schema.Int),
parents: Schema.optional(
Schema.NullOr(Schema.Struct({ totalCount: Schema.optional(Schema.Int) })),
),
authors: Schema.optional(
Schema.NullOr(
Schema.Struct({
@@ -599,7 +618,7 @@ export function decodeActorAvatarsJson(
export const PULL_REQUEST_LIST_JSON_FIELDS =
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup";
export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest`;
export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,isCrossRepository,headRepositoryOwner,headRefOid,autoMergeRequest`;
export const PULL_REQUEST_ACTIVITY_JSON_FIELDS = "author,comments,reviews,commits";
/** GitHub's own ceiling on a connection page, which is what both thread reads ask for. */
@@ -731,6 +750,7 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: Strin
committedDate
additions
deletions
parents(first: 1) { totalCount }
authors(first: 3) { nodes { name avatarUrl user { login } } }
}
}
@@ -879,6 +899,13 @@ export const UPDATE_PULL_REQUEST_GRAPHQL_MUTATION = `mutation($pullRequestId: ID
}
}`;
/** Creates a new pull request that reverses a merged pull request. */
export const REVERT_PULL_REQUEST_GRAPHQL_MUTATION = `mutation($pullRequestId: ID!) {
revertPullRequest(input: { pullRequestId: $pullRequestId }) {
revertPullRequest { id }
}
}`;
/**
* The two comment mutations name their comment differently. The variable is spelled the same in
* both, so a rewrite sends one set of variables whichever kind of remark it is.
@@ -1016,8 +1043,11 @@ export interface GitHubPullRequestListItem {
}
export interface GitHubPullRequestDetail extends GitHubPullRequestListItem {
/** True only when GitHub says the head belongs to another repository. */
readonly isCrossRepository?: boolean;
/** The owner of the head branch's repository; null where `gh` did not say. */
readonly headRepositoryOwner: string | null;
readonly headSha?: string | null;
readonly body: string;
readonly changedFiles: number;
readonly mergedAt: string | null;
@@ -1025,6 +1055,21 @@ export interface GitHubPullRequestDetail extends GitHubPullRequestListItem {
readonly checks: ReadonlyArray<PullRequestCheck>;
/** Absent where `gh` did not answer for auto-merge at all, which is not the same as off. */
readonly autoMergeEnabled?: boolean;
/** Absent where auto-merge is off or GitHub did not report the stored strategy. */
readonly autoMergeMethod?: PullRequestMergeMethod;
}
export interface GitHubWorkflowRunApproval {
readonly id: number;
readonly name: string;
readonly url: string | null;
}
export interface GitHubPullRequestHead {
readonly number: number;
readonly headSha: string;
readonly isCrossRepository?: boolean;
readonly headRepositoryOwner: string | null;
}
export interface GitHubPullRequestActivity {
@@ -1114,6 +1159,19 @@ function toMergeability(value: string | null | undefined): PullRequestMergeabili
}
}
function toMergeMethod(value: string | null | undefined): PullRequestMergeMethod | undefined {
switch (value?.trim().toUpperCase()) {
case "MERGE":
return "merge";
case "SQUASH":
return "squash";
case "REBASE":
return "rebase";
default:
return undefined;
}
}
function toReviewDecision(value: string | null | undefined): PullRequestReviewDecision | null {
switch (value?.trim().toUpperCase()) {
case "APPROVED":
@@ -1169,12 +1227,12 @@ function toCheckStatus(raw: Schema.Schema.Type<typeof RawCheckSchema>): PullRequ
switch ((raw.conclusion ?? raw.state)?.trim().toUpperCase()) {
case "SUCCESS":
return "success";
case "ACTION_REQUIRED":
return "action-required";
case "FAILURE":
case "ERROR":
case "TIMED_OUT":
case "STARTUP_FAILURE":
// A completed check asking for manual intervention is blocking, not neutral.
case "ACTION_REQUIRED":
return "failure";
case "CANCELLED":
return "cancelled";
@@ -1253,7 +1311,7 @@ function rollupChecksState(
];
if (statuses.length === 0) return null;
if (statuses.includes("failure")) return "failing";
if (statuses.includes("pending")) return "pending";
if (statuses.includes("pending") || statuses.includes("action-required")) return "pending";
return statuses.includes("success") ? "passing" : null;
}
@@ -1361,9 +1419,14 @@ function toListItem(raw: Schema.Schema.Type<typeof RawListItemSchema>): GitHubPu
}
function toDetail(raw: Schema.Schema.Type<typeof RawDetailSchema>): GitHubPullRequestDetail {
const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod);
return {
...toListItem(raw),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
headRepositoryOwner: trimmed(raw.headRepositoryOwner?.login),
headSha: trimmed(raw.headRefOid),
body: raw.body ?? "",
changedFiles: raw.changedFiles ?? 0,
mergedAt: trimmed(raw.mergedAt),
@@ -1374,6 +1437,7 @@ function toDetail(raw: Schema.Schema.Type<typeof RawDetailSchema>): GitHubPullRe
...(raw.autoMergeRequest === undefined
? {}
: { autoMergeEnabled: raw.autoMergeRequest !== null }),
...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
};
}
@@ -1391,6 +1455,8 @@ const decodeSearch = decodeJsonResult(RawSearchSchema);
const decodeSearchItem = Schema.decodeUnknownExit(RawSearchItemSchema);
const decodeStats = decodeJsonResult(RawStatsSchema);
const decodeDetail = decodeJsonResult(RawDetailSchema);
const decodeWorkflowRunApprovals = decodeJsonResult(Schema.Array(RawWorkflowRunApprovalSchema));
const decodePullRequestHeads = decodeJsonResult(Schema.Array(RawPullRequestHeadSchema));
const decodeActivity = decodeJsonResult(RawActivitySchema);
const decodeFileEntry = Schema.decodeUnknownExit(RawPullRequestFileSchema);
const decodeRepositoryAccess = decodeJsonResult(RawRepositoryAccessSchema);
@@ -1551,6 +1617,37 @@ export function decodePullRequestDetailJson(
: Result.fail(decoded.failure);
}
export function decodeWorkflowRunApprovalsJson(
raw: string,
): Result.Result<ReadonlyArray<GitHubWorkflowRunApproval>, DecodeFailure> {
const decoded = decodeWorkflowRunApprovals(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
return Result.succeed(
decoded.success.map((run) => ({
id: run.databaseId,
name: trimmed(run.workflowName) ?? `Workflow run ${run.databaseId}`,
url: trimmed(run.url),
})),
);
}
export function decodePullRequestHeadsJson(
raw: string,
): Result.Result<ReadonlyArray<GitHubPullRequestHead>, DecodeFailure> {
const decoded = decodePullRequestHeads(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
return Result.succeed(
decoded.success.map((pullRequest) => ({
number: pullRequest.number,
headSha: pullRequest.headRefOid,
...(typeof pullRequest.isCrossRepository === "boolean"
? { isCrossRepository: pullRequest.isCrossRepository }
: {}),
headRepositoryOwner: trimmed(pullRequest.headRepositoryOwner?.login),
})),
);
}
export function decodePullRequestActivityJson(
raw: string,
): Result.Result<GitHubPullRequestActivity, DecodeFailure> {
@@ -1788,7 +1885,14 @@ export function decodeReviewThreadsJson(
const commit = node.commit;
const oid = trimmed(commit.oid);
if (oid === null) continue;
if (commit.additions !== undefined && commit.deletions !== undefined) {
// GitHub measures a merge commit against its first parent, so merging the base into the head
// reports every upstream change as if it belonged to the pull request. There is no useful
// per-commit stat to show for that integration commit without another comparison request.
if (
(commit.parents?.totalCount ?? 1) <= 1 &&
commit.additions !== undefined &&
commit.deletions !== undefined
) {
commitStats.set(oid, {
additions: Math.max(0, commit.additions),
deletions: Math.max(0, commit.deletions),
@@ -192,6 +192,28 @@ describe("decodeMergeRequestDetailJson", () => {
expect(armed({})).toBeUndefined();
});
it("keeps the squash choice stored with auto-merge", () => {
expect(
expectSuccess(
decodeMergeRequestDetailJson(
detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
),
),
).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
expect(
expectSuccess(
decodeMergeRequestDetailJson(
detailJson({
auto_merge_enabled: true,
squash: true,
squash_on_merge: false,
}),
),
).autoMergeMethod,
).toBeUndefined();
});
it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
const behind = (entry: Record<string, unknown>) =>
expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
@@ -11,6 +11,7 @@ import type {
PullRequestLabel,
PullRequestMergeability,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewThread,
@@ -80,6 +81,9 @@ const RawMergeRequestSchema = Schema.Struct({
*/
merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
/** The merge request's stored squash choice, including project-policy overrides. */
squash_on_merge: Schema.optional(Schema.NullOr(Schema.Boolean)),
squash: Schema.optional(Schema.NullOr(Schema.Boolean)),
/**
* How far the target branch has moved on since this one left it, which is the same number
* GitLab's own "out of date" wording counts. It costs a walk of the two branches, so GitLab
@@ -228,6 +232,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly reviewerIds: ReadonlyArray<number>;
/** Absent where GitLab named neither auto-merge field, which is not the same as off. */
readonly autoMergeEnabled?: boolean;
/** GitLab only exposes the stored strategy separately when that strategy is squash. */
readonly autoMergeMethod?: PullRequestMergeMethod;
/**
* Absent where GitLab did not count, which is not the same as a branch that has nothing behind
* it: an install too old to answer must not be read as saying the branch is current.
@@ -379,6 +385,9 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
reviewer.id === undefined ? [] : [reviewer.id],
),
...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
...(autoMerge === true && raw.squash_on_merge === true
? { autoMergeMethod: "squash" as const }
: {}),
...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
};
}