fix(pull-requests): missing features & better behaviour (#9188)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
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 }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ function ChecksBody({ checks }: { checks: ReadonlyArray<PullRequestCheck> }) {
|
||||
<TooltipPopup side="top">{check.description ?? check.name}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{pullRequestCheckStatusLabel(check.status)}
|
||||
{pullRequestCheckStatusLabel(check)}
|
||||
</span>
|
||||
{check.url === null ? null : (
|
||||
<button
|
||||
@@ -112,6 +112,7 @@ export function PullRequestChecksPopover({
|
||||
not valid inside one. The click is stopped here so opening the checks does not also
|
||||
select the row it sits on. */}
|
||||
<PopoverTrigger
|
||||
nativeButton={false}
|
||||
render={
|
||||
<span
|
||||
role="button"
|
||||
|
||||
@@ -33,7 +33,9 @@ import {
|
||||
MoreHorizontalIcon,
|
||||
PanelRightIcon,
|
||||
PencilIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
ServerIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
@@ -118,6 +120,7 @@ import {
|
||||
pullRequestFindingKey,
|
||||
pullRequestHandoffLabels,
|
||||
readableFailure,
|
||||
resolvePullRequestPrimaryControl,
|
||||
resolveBaseFreshness,
|
||||
type PullRequestFinding,
|
||||
shouldRefreshPullRequestActivity,
|
||||
@@ -154,6 +157,8 @@ const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
|
||||
"enable-auto-merge":
|
||||
"Auto-merge turned on — merges as soon as this is ready, sooner if it already is",
|
||||
"disable-auto-merge": "Auto-merge turned off",
|
||||
revert: "Revert pull request opened",
|
||||
"approve-workflows": "Workflows approved",
|
||||
};
|
||||
|
||||
const MERGE_METHOD_LABELS: Record<PullRequestMergeMethod, string> = {
|
||||
@@ -172,6 +177,8 @@ const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
|
||||
"update-branch": "Could not update this branch",
|
||||
"enable-auto-merge": "Could not turn on auto-merge",
|
||||
"disable-auto-merge": "Could not turn off auto-merge",
|
||||
revert: "Could not open a revert pull request",
|
||||
"approve-workflows": "Could not approve workflows",
|
||||
};
|
||||
|
||||
/** What to try, for the times the host says only that it refused. */
|
||||
@@ -193,6 +200,10 @@ const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
|
||||
"The host refused it. Check that this repository allows auto-merge, that you have write access, and that there is something left for it to wait on.",
|
||||
"disable-auto-merge":
|
||||
"The host refused it. Check that you have write access, and that the merge has not already happened.",
|
||||
revert:
|
||||
"The host refused it. Check that you have write access and that this pull request was merged on the host.",
|
||||
"approve-workflows":
|
||||
"The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -518,10 +529,18 @@ export function PullRequestDetailPanel({
|
||||
compensationRef.current = null;
|
||||
if (scroller) scroller.scrollTop = Math.max(0, scroller.scrollTop + delta);
|
||||
}, [condensed]);
|
||||
const [mergeMethod, setMergeMethod] = useState<PullRequestMergeMethod>("merge");
|
||||
const [mergeMethodSelection, setMergeMethodSelection] = useState<{
|
||||
readonly pullRequestKey: string;
|
||||
readonly method: PullRequestMergeMethod;
|
||||
}>(() => ({ pullRequestKey, method: "merge" }));
|
||||
const mergeMethod =
|
||||
mergeMethodSelection.pullRequestKey === pullRequestKey ? mergeMethodSelection.method : "merge";
|
||||
const setMergeMethod = (method: PullRequestMergeMethod) => {
|
||||
setMergeMethodSelection({ pullRequestKey, method });
|
||||
};
|
||||
const [confirmation, setConfirmation] = useState<{
|
||||
readonly open: boolean;
|
||||
readonly action: "merge" | "close" | "enable-auto-merge";
|
||||
readonly action: "merge" | "close" | "enable-auto-merge" | "revert" | "approve-workflows";
|
||||
}>({ open: false, action: "merge" });
|
||||
const confirmAction = confirmation.action;
|
||||
// Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
|
||||
@@ -558,6 +577,9 @@ export function PullRequestDetailPanel({
|
||||
},
|
||||
[activity, coreDetail],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (detail?.autoMergeMethod !== undefined) setMergeMethod(detail.autoMergeMethod);
|
||||
}, [detail?.autoMergeMethod, pullRequestKey]);
|
||||
const repositoryUrl = detail === null ? null : changeRequestRepositoryUrl(detail.url);
|
||||
const checkoutCommand = detail
|
||||
? pullRequestCheckoutCommand(
|
||||
@@ -636,6 +658,7 @@ export function PullRequestDetailPanel({
|
||||
void refreshFromHost();
|
||||
}, [forcedRefreshToken, refreshFromHost]);
|
||||
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
|
||||
const postComment = useAtomCommand(pullRequestEnvironment.comment, { reportFailure: false });
|
||||
// Which action is in flight, not merely that one is: every control here is disabled while any
|
||||
// of them runs, but only the button that was pressed may say what it is doing.
|
||||
const [pendingAction, setPendingAction] = useState<PullRequestAction | null>(null);
|
||||
@@ -689,13 +712,11 @@ export function PullRequestDetailPanel({
|
||||
cwd: acting?.workspaceRoot ?? detail?.workspaceRoot ?? null,
|
||||
});
|
||||
|
||||
const perform = async (
|
||||
const finishAction = async (
|
||||
action: PullRequestAction,
|
||||
method?: PullRequestMergeMethod,
|
||||
updateMethod?: PullRequestUpdateMethod,
|
||||
) => {
|
||||
if (pendingAction !== null) return;
|
||||
setPendingAction(action);
|
||||
const result = await runAction({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -723,7 +744,7 @@ export function PullRequestDetailPanel({
|
||||
title: ACTION_FAILURE_LABELS[action],
|
||||
description: readableFailure(failure, hint),
|
||||
});
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
|
||||
// A branch update moves the head commit, which leaves the diff atom pointed at a comparison
|
||||
@@ -737,6 +758,36 @@ export function PullRequestDetailPanel({
|
||||
refreshDetail();
|
||||
}
|
||||
onActed?.();
|
||||
return true;
|
||||
};
|
||||
|
||||
const perform = async (
|
||||
action: PullRequestAction,
|
||||
method?: PullRequestMergeMethod,
|
||||
updateMethod?: PullRequestUpdateMethod,
|
||||
) => {
|
||||
if (pendingAction !== null) return false;
|
||||
setPendingAction(action);
|
||||
return finishAction(action, method, updateMethod);
|
||||
};
|
||||
|
||||
const performCommentAction = async (body: string, action: "close" | "reopen") => {
|
||||
if (pendingAction !== null) return { commentPosted: false };
|
||||
setPendingAction(action);
|
||||
const commentResult = await postComment({
|
||||
environmentId,
|
||||
input: { ...reference, body },
|
||||
});
|
||||
if (commentResult._tag === "Failure") {
|
||||
setPendingAction(null);
|
||||
toastManager.add({ type: "error", title: "Could not post the comment" });
|
||||
return { commentPosted: false };
|
||||
}
|
||||
const actionSucceeded = await finishAction(action);
|
||||
// The comment is durable even if the state change was refused, so make it visible while the
|
||||
// shared action failure explains why the pull request stayed where it was.
|
||||
if (!actionSucceeded) refreshDetail();
|
||||
return { commentPosted: true };
|
||||
};
|
||||
|
||||
const saveTitle = async (next: string) => {
|
||||
@@ -1094,10 +1145,17 @@ export function PullRequestDetailPanel({
|
||||
? mergeMethod
|
||||
: (allowedMergeMethods[0] ?? "merge");
|
||||
const selectedMergeMethodLabel = MERGE_METHOD_LABELS[selectedMergeMethod];
|
||||
const pendingAutoMergeLabel = `Auto-merge (${selectedMergeMethodLabel.toLowerCase()})`;
|
||||
const conflicting = detail?.state === "open" && detail.mergeability === "conflicting";
|
||||
// Only an outright yes arms it. A host that reports nothing has not said the merge is already
|
||||
// spoken for, and an off switch for something that may not be on says the wrong thing twice.
|
||||
const autoMergeArmed = detail?.state === "open" && detail.autoMergeEnabled === true;
|
||||
const armedMergeMethod = detail?.autoMergeMethod;
|
||||
const armedAutoMergeLabel = armedMergeMethod
|
||||
? `Auto-merge (${MERGE_METHOD_LABELS[armedMergeMethod].toLowerCase()})`
|
||||
: "Auto-merge";
|
||||
const workflowApprovalsRequired =
|
||||
detail?.state === "open" ? (detail.workflowApprovalsRequired ?? 0) : 0;
|
||||
// Out of date with the base, and still cleanly mergeable — the one pairing an update button
|
||||
// exists for. Null everywhere else, including hosts that cannot compare at all.
|
||||
const freshness = detail === null ? null : resolveBaseFreshness(detail);
|
||||
@@ -1118,20 +1176,22 @@ export function PullRequestDetailPanel({
|
||||
const can = (action: PullRequestAction) =>
|
||||
detail?.capabilities.actions.includes(action) === true &&
|
||||
detail.viewerPermissions.actions.includes(action);
|
||||
// One live action holds the slot. Conflicts take priority because every other completion action
|
||||
// depends on resolving them first, even for a reader who cannot merge on the host themselves.
|
||||
const primaryAction =
|
||||
detail === null || detail.state !== "open"
|
||||
? null
|
||||
: conflicting
|
||||
? "resolve"
|
||||
: detail.isDraft && can("ready")
|
||||
? "ready"
|
||||
: !can("merge")
|
||||
? null
|
||||
: allowedMergeMethods.length > 0
|
||||
? "merge"
|
||||
: null;
|
||||
const checksState = detail ? pullRequestChecksState(detail.checks) : null;
|
||||
// The merge state remains in one stable slot from waiting through completion. Conflicts take
|
||||
// the slot while they need a person; the armed badge remains beside them so that state is not lost.
|
||||
const primaryAction = detail
|
||||
? resolvePullRequestPrimaryControl({
|
||||
state: detail.state,
|
||||
isDraft: detail.isDraft,
|
||||
mergeability: detail.mergeability,
|
||||
checksState,
|
||||
autoMergeEnabled: detail.autoMergeEnabled,
|
||||
hasMergeMethod: allowedMergeMethods.length > 0,
|
||||
canMerge: can("merge"),
|
||||
canMarkReady: can("ready"),
|
||||
canEnableAutoMerge: can("enable-auto-merge"),
|
||||
})
|
||||
: null;
|
||||
// What the menu's action group holds. Named once so the separators around it are drawn from
|
||||
// the same answer as its contents, rather than on the assumption that it has any.
|
||||
const showsDraftToggle =
|
||||
@@ -1142,10 +1202,18 @@ export function PullRequestDetailPanel({
|
||||
detail?.state === "open" &&
|
||||
((autoMergeArmed && can("disable-auto-merge")) ||
|
||||
(!autoMergeArmed &&
|
||||
primaryAction !== "enable-auto-merge" &&
|
||||
!detail.isDraft &&
|
||||
!conflicting &&
|
||||
can("enable-auto-merge") &&
|
||||
allowedMergeMethods.length > 0));
|
||||
const showsMergeNow =
|
||||
detail?.state === "open" &&
|
||||
(primaryAction === "enable-auto-merge" || primaryAction === "auto-merge-armed") &&
|
||||
can("merge") &&
|
||||
!detail.isDraft &&
|
||||
!conflicting &&
|
||||
allowedMergeMethods.length > 0;
|
||||
const showsMergeMethods =
|
||||
detail?.state === "open" &&
|
||||
can("merge") &&
|
||||
@@ -1158,7 +1226,6 @@ export function PullRequestDetailPanel({
|
||||
? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft })
|
||||
: null;
|
||||
const checksSummary = detail ? summarizePullRequestChecks(detail.checks) : null;
|
||||
const checksState = detail ? pullRequestChecksState(detail.checks) : null;
|
||||
// Approvals that still stand, and only those. A superseded one is dimmed beside the reviewer
|
||||
// who gave it, so counting it here would have the header assert in a number what the row next
|
||||
// to it has just qualified.
|
||||
@@ -1335,18 +1402,28 @@ export function PullRequestDetailPanel({
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
) : null}
|
||||
{workflowApprovalsRequired > 0 && can("approve-workflows") ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="warning-outline"
|
||||
disabled={actionPending}
|
||||
onClick={() => setConfirmation({ open: true, action: "approve-workflows" })}
|
||||
>
|
||||
<PlayIcon className="size-3.5" />
|
||||
{pendingAction === "approve-workflows"
|
||||
? "Approving..."
|
||||
: "Approve workflows to run"}
|
||||
</Button>
|
||||
) : null}
|
||||
{/* Said where the Merge button is, because it is the answer to why nobody has
|
||||
pressed it: the merge is already asked for, and the host is holding it. */}
|
||||
{autoMergeArmed ? (
|
||||
{autoMergeArmed && primaryAction !== "auto-merge-armed" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Badge
|
||||
variant="info"
|
||||
className="h-5 shrink-0 gap-1 rounded px-1.5 text-[10px]"
|
||||
>
|
||||
<GitMergeIcon aria-hidden className="size-3" />
|
||||
Auto-merge
|
||||
<Badge size="control" variant="info">
|
||||
<GitMergeIcon aria-hidden className="size-3.5" />
|
||||
{armedAutoMergeLabel}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
@@ -1369,6 +1446,29 @@ export function PullRequestDetailPanel({
|
||||
<Button size="xs" disabled={actionPending} onClick={() => void perform("ready")}>
|
||||
Ready for review
|
||||
</Button>
|
||||
) : primaryAction === "enable-auto-merge" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
disabled={actionPending}
|
||||
onClick={() => setConfirmation({ open: true, action: "enable-auto-merge" })}
|
||||
>
|
||||
<GitMergeIcon className="size-3.5" />
|
||||
{pendingAction === "enable-auto-merge" ? "Enabling..." : pendingAutoMergeLabel}
|
||||
</Button>
|
||||
) : primaryAction === "auto-merge-armed" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Badge size="control" variant="info">
|
||||
<GitMergeIcon className="size-3.5" />
|
||||
{armedAutoMergeLabel}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">
|
||||
The host will merge this on its own once its requirements are met
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : primaryAction === "merge" ? (
|
||||
<Button
|
||||
size="xs"
|
||||
@@ -1377,6 +1477,12 @@ export function PullRequestDetailPanel({
|
||||
>
|
||||
{pendingAction === "merge" ? "Merging..." : selectedMergeMethodLabel}
|
||||
</Button>
|
||||
) : (primaryAction === "merged" || primaryAction === "closed") &&
|
||||
statePresentation !== null ? (
|
||||
<Badge size="control" variant="outline" className={statePresentation.toneClassName}>
|
||||
<statePresentation.Icon className="size-3.5" />
|
||||
{statePresentation.label}
|
||||
</Badge>
|
||||
) : null}
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
@@ -1447,11 +1553,18 @@ export function PullRequestDetailPanel({
|
||||
{detail.isDraft ? "Ready for review" : "Convert to draft"}
|
||||
</MenuItem>
|
||||
) : null}
|
||||
{/* The same merge, left with the host to carry out once the things it
|
||||
waits on are done. It is offered beside the merge rather than instead
|
||||
of it, because the reader who can wait and the reader who cannot are
|
||||
the same person on different days — and a conflicting branch is neither,
|
||||
since nothing the host waits for will clear it. */}
|
||||
{showsMergeNow ? (
|
||||
<MenuItem
|
||||
disabled={actionPending}
|
||||
onClick={() => setConfirmation({ open: true, action: "merge" })}
|
||||
>
|
||||
<GitMergeIcon className="size-3.5" />
|
||||
Merge now
|
||||
</MenuItem>
|
||||
) : null}
|
||||
{/* The same merge, left with the host to carry out once its requirements
|
||||
pass. A conflicting branch cannot be armed because nothing the host
|
||||
waits for will clear the conflict. */}
|
||||
{autoMergeArmed && can("disable-auto-merge") ? (
|
||||
<MenuItem
|
||||
disabled={actionPending}
|
||||
@@ -1460,11 +1573,7 @@ export function PullRequestDetailPanel({
|
||||
<GitMergeIcon className="size-3.5" />
|
||||
Disable auto-merge
|
||||
</MenuItem>
|
||||
) : !autoMergeArmed &&
|
||||
!detail.isDraft &&
|
||||
!conflicting &&
|
||||
can("enable-auto-merge") &&
|
||||
allowedMergeMethods.length > 0 ? (
|
||||
) : showsAutoMerge ? (
|
||||
<MenuItem
|
||||
disabled={actionPending}
|
||||
onClick={() =>
|
||||
@@ -1485,7 +1594,9 @@ export function PullRequestDetailPanel({
|
||||
{/* Only below the draft control. A host with no draft of its own, or
|
||||
a draft whose control is already the header button, would leave
|
||||
this against the separator that opened the group. */}
|
||||
{showsDraftToggle ? <MenuSeparator /> : null}
|
||||
{showsDraftToggle || showsMergeNow || showsAutoMerge ? (
|
||||
<MenuSeparator />
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={selectedMergeMethod}
|
||||
onValueChange={(method) =>
|
||||
@@ -1507,7 +1618,7 @@ export function PullRequestDetailPanel({
|
||||
) : null}
|
||||
{pullRequestActionMenuHasGroup(
|
||||
showsDraftToggle,
|
||||
showsAutoMerge,
|
||||
showsAutoMerge || showsMergeNow,
|
||||
showsMergeMethods,
|
||||
) ? (
|
||||
<MenuSeparator />
|
||||
@@ -1542,6 +1653,17 @@ export function PullRequestDetailPanel({
|
||||
Reopen pull request
|
||||
</MenuItem>
|
||||
</>
|
||||
) : detail.state === "merged" && can("revert") ? (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
<MenuItem
|
||||
disabled={actionPending}
|
||||
onClick={() => setConfirmation({ open: true, action: "revert" })}
|
||||
>
|
||||
<RotateCcwIcon className="size-3.5" />
|
||||
Revert changes
|
||||
</MenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
@@ -1987,6 +2109,8 @@ export function PullRequestDetailPanel({
|
||||
fixFindingLabel={handoffLabels.fixFinding}
|
||||
fixCheckLabel={handoffLabels.fixCheck}
|
||||
onFixFinding={startFixFinding}
|
||||
actionPending={actionPending}
|
||||
onCommentAction={performCommentAction}
|
||||
onRefresh={refreshDetail}
|
||||
/>
|
||||
</div>
|
||||
@@ -2049,7 +2173,11 @@ export function PullRequestDetailPanel({
|
||||
? "Merge pull request?"
|
||||
: confirmAction === "enable-auto-merge"
|
||||
? "Enable auto-merge?"
|
||||
: "Close pull request?"}
|
||||
: confirmAction === "revert"
|
||||
? "Revert these changes?"
|
||||
: confirmAction === "approve-workflows"
|
||||
? "Approve workflows to run?"
|
||||
: "Close pull request?"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{confirmAction === "merge"
|
||||
@@ -2059,7 +2187,11 @@ export function PullRequestDetailPanel({
|
||||
// may be immediately — there is no telling from here whether anything is
|
||||
// still outstanding.
|
||||
`This merges #${reference.number} using ${selectedMergeMethod} as soon as the host considers it ready, which may be immediately.`
|
||||
: `This closes #${reference.number} without merging it.`}
|
||||
: confirmAction === "revert"
|
||||
? `This opens a new pull request that reverses the changes merged by #${reference.number}.`
|
||||
: confirmAction === "approve-workflows"
|
||||
? `This allows ${workflowApprovalsRequired} ${workflowApprovalsRequired === 1 ? "workflow" : "workflows"} from #${reference.number} to run. Review the code and workflow changes first.`
|
||||
: `This closes #${reference.number} without merging it.`}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -2076,6 +2208,8 @@ export function PullRequestDetailPanel({
|
||||
if (action === "merge") void perform("merge", selectedMergeMethod);
|
||||
if (action === "enable-auto-merge")
|
||||
void perform("enable-auto-merge", selectedMergeMethod);
|
||||
if (action === "revert") void perform("revert");
|
||||
if (action === "approve-workflows") void perform("approve-workflows");
|
||||
if (action === "close") void perform("close");
|
||||
}}
|
||||
>
|
||||
@@ -2083,7 +2217,11 @@ export function PullRequestDetailPanel({
|
||||
? selectedMergeMethodLabel
|
||||
: confirmAction === "enable-auto-merge"
|
||||
? "Enable auto-merge"
|
||||
: "Close"}
|
||||
: confirmAction === "revert"
|
||||
? "Create revert PR"
|
||||
: confirmAction === "approve-workflows"
|
||||
? "Approve and run"
|
||||
: "Close"}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
|
||||
@@ -524,7 +524,7 @@ export function PullRequestFiltersMenu({
|
||||
<ListFilterIcon className="size-4" />
|
||||
<span>Filters</span>
|
||||
{filterCount > 0 ? (
|
||||
<span className="rounded-full bg-primary/10 px-1.5 text-xs text-primary tabular-nums">
|
||||
<span className="rounded-full bg-muted px-1.5 text-xs text-muted-foreground tabular-nums">
|
||||
{filterCount}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
@@ -9,9 +9,11 @@ import {
|
||||
ArrowDownUpIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
GitPullRequestClosedIcon,
|
||||
HammerIcon,
|
||||
MessageSquareIcon,
|
||||
PencilIcon,
|
||||
RotateCcwIcon,
|
||||
SendIcon,
|
||||
TagIcon,
|
||||
UsersIcon,
|
||||
@@ -308,20 +310,43 @@ function Section({
|
||||
function CommentComposer({
|
||||
environmentId,
|
||||
detail,
|
||||
actionPending,
|
||||
onCommentAction,
|
||||
onCommented,
|
||||
}: {
|
||||
environmentId: EnvironmentId;
|
||||
detail: PullRequestDetailView;
|
||||
actionPending: boolean;
|
||||
onCommentAction: (
|
||||
body: string,
|
||||
action: "close" | "reopen",
|
||||
) => Promise<{ readonly commentPosted: boolean }>;
|
||||
onCommented: () => void;
|
||||
}) {
|
||||
const [body, setBody] = useState("");
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [submitting, setSubmitting] = useState<"comment" | "close" | "reopen" | null>(null);
|
||||
const postComment = useAtomCommand(pullRequestEnvironment.comment, { reportFailure: false });
|
||||
const followUpAction =
|
||||
detail.state === "open" &&
|
||||
detail.capabilities.actions.includes("close") &&
|
||||
detail.viewerPermissions.actions.includes("close")
|
||||
? ("close" as const)
|
||||
: detail.state === "closed" &&
|
||||
detail.capabilities.actions.includes("reopen") &&
|
||||
detail.viewerPermissions.actions.includes("reopen")
|
||||
? ("reopen" as const)
|
||||
: null;
|
||||
|
||||
const submit = async () => {
|
||||
const submit = async (action: "comment" | "close" | "reopen") => {
|
||||
const trimmed = body.trim();
|
||||
if (trimmed.length === 0 || posting) return;
|
||||
setPosting(true);
|
||||
if (trimmed.length === 0 || submitting !== null || actionPending) return;
|
||||
setSubmitting(action);
|
||||
if (action !== "comment") {
|
||||
const result = await onCommentAction(trimmed, action);
|
||||
if (result.commentPosted) setBody("");
|
||||
setSubmitting(null);
|
||||
return;
|
||||
}
|
||||
const result = await postComment({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -331,12 +356,13 @@ function CommentComposer({
|
||||
body: trimmed,
|
||||
},
|
||||
});
|
||||
setPosting(false);
|
||||
if (result._tag === "Failure") {
|
||||
setSubmitting(null);
|
||||
toastManager.add({ type: "error", title: "Could not post the comment" });
|
||||
return;
|
||||
}
|
||||
setBody("");
|
||||
setSubmitting(null);
|
||||
onCommented();
|
||||
};
|
||||
|
||||
@@ -345,22 +371,43 @@ function CommentComposer({
|
||||
<Textarea
|
||||
// Locked while posting: the body is cleared on success, which would otherwise throw
|
||||
// away a new draft typed while the request was still in flight.
|
||||
disabled={posting}
|
||||
disabled={submitting !== null || actionPending}
|
||||
value={body}
|
||||
rows={3}
|
||||
placeholder="Leave a comment"
|
||||
aria-label="Comment on this pull request"
|
||||
onChange={(event) => setBody(event.target.value)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end gap-2">
|
||||
{followUpAction === null ? null : (
|
||||
<Button
|
||||
size="xs"
|
||||
variant={followUpAction === "close" ? "destructive-outline" : "outline"}
|
||||
disabled={body.trim().length === 0 || submitting !== null || actionPending}
|
||||
onClick={() => void submit(followUpAction)}
|
||||
>
|
||||
{followUpAction === "close" ? (
|
||||
<GitPullRequestClosedIcon className="size-3.5" />
|
||||
) : (
|
||||
<RotateCcwIcon className="size-3.5" />
|
||||
)}
|
||||
{submitting === followUpAction
|
||||
? followUpAction === "close"
|
||||
? "Closing..."
|
||||
: "Reopening..."
|
||||
: followUpAction === "close"
|
||||
? "Close with comment"
|
||||
: "Reopen with comment"}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={body.trim().length === 0 || posting}
|
||||
onClick={() => void submit()}
|
||||
disabled={body.trim().length === 0 || submitting !== null || actionPending}
|
||||
onClick={() => void submit("comment")}
|
||||
>
|
||||
<SendIcon className="size-3.5" />
|
||||
{posting ? "Posting..." : "Comment"}
|
||||
{submitting === "comment" ? "Posting..." : "Comment"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -383,6 +430,8 @@ export function PullRequestSummaryTab({
|
||||
fixFindingLabel = "Fix in a thread",
|
||||
fixCheckLabel = "Fix",
|
||||
onFixFinding,
|
||||
actionPending,
|
||||
onCommentAction,
|
||||
onRefresh,
|
||||
}: {
|
||||
environmentId: EnvironmentId;
|
||||
@@ -395,6 +444,11 @@ export function PullRequestSummaryTab({
|
||||
fixFindingLabel?: string;
|
||||
fixCheckLabel?: string;
|
||||
onFixFinding?: (finding: PullRequestFinding) => void;
|
||||
actionPending: boolean;
|
||||
onCommentAction: (
|
||||
body: string,
|
||||
action: "close" | "reopen",
|
||||
) => Promise<{ readonly commentPosted: boolean }>;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
// Keyed by the pull request, so opening another one starts at the end of its conversation
|
||||
@@ -718,7 +772,7 @@ export function PullRequestSummaryTab({
|
||||
<PullRequestCheckStatusIcon status={check.status} />
|
||||
<span className="min-w-0 flex-1 truncate">{check.name}</span>
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{pullRequestCheckStatusLabel(check.status)}
|
||||
{pullRequestCheckStatusLabel(check)}
|
||||
</span>
|
||||
</button>
|
||||
{/* Only where there is something to fix. A passing check has no failure to
|
||||
@@ -919,6 +973,8 @@ export function PullRequestSummaryTab({
|
||||
key={`${environmentId}:${detail.projectId}/${detail.repository}#${detail.number}`}
|
||||
environmentId={environmentId}
|
||||
detail={detail}
|
||||
actionPending={actionPending}
|
||||
onCommentAction={onCommentAction}
|
||||
onCommented={onRefresh}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -5,10 +5,17 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
|
||||
import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
|
||||
import { PullRequestRow } from "./PullRequestRow";
|
||||
import { pullRequestChecksState } from "./pullRequestPresentation";
|
||||
import {
|
||||
pullRequestChecksState,
|
||||
pullRequestCheckStatusLabel,
|
||||
summarizePullRequestChecks,
|
||||
} from "./pullRequestPresentation";
|
||||
|
||||
function check(status: PullRequestCheck["status"]): PullRequestCheck {
|
||||
return { name: `check-${status}`, status, description: null, url: null };
|
||||
function check(
|
||||
status: PullRequestCheck["status"],
|
||||
overrides: Partial<PullRequestCheck> = {},
|
||||
): PullRequestCheck {
|
||||
return { name: `check-${status}`, status, description: null, url: null, ...overrides };
|
||||
}
|
||||
|
||||
describe("pullRequestChecksState", () => {
|
||||
@@ -18,11 +25,31 @@ describe("pullRequestChecksState", () => {
|
||||
);
|
||||
expect(pullRequestChecksState([check("success"), check("cancelled")])).toBe("failing");
|
||||
expect(pullRequestChecksState([check("success"), check("pending")])).toBe("pending");
|
||||
expect(pullRequestChecksState([check("success"), check("action-required")])).toBe("pending");
|
||||
expect(pullRequestChecksState([check("success")])).toBe("passing");
|
||||
// Skipped and neutral are neither a pass nor a failure, so they are no verdict at all.
|
||||
expect(pullRequestChecksState([check("skipped"), check("neutral")])).toBe(null);
|
||||
expect(pullRequestChecksState([])).toBe(null);
|
||||
});
|
||||
|
||||
it("names workflow approval instead of claiming every check passed", () => {
|
||||
const workflow = check("action-required", {
|
||||
url: "https://github.com/acme/web/actions/runs/42/job/7",
|
||||
});
|
||||
const manualGate = check("action-required", { url: "https://example.com/manual-gate" });
|
||||
expect(pullRequestCheckStatusLabel(workflow)).toBe("Awaiting approval");
|
||||
expect(pullRequestCheckStatusLabel(manualGate)).toBe("Awaiting action");
|
||||
expect(summarizePullRequestChecks([check("success"), workflow])).toBe(
|
||||
"1 workflow awaiting approval",
|
||||
);
|
||||
expect(summarizePullRequestChecks([check("failure"), workflow])).toBe("1 of 2 failing");
|
||||
expect(summarizePullRequestChecks([check("success"), manualGate])).toBe(
|
||||
"1 check awaiting action",
|
||||
);
|
||||
expect(summarizePullRequestChecks([workflow, manualGate])).toBe(
|
||||
"1 workflow and 1 check awaiting action",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/** Every element of the tree the row returned, so a nested indicator can be looked for. */
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
pullRequestHandoffLabels,
|
||||
pullRequestReviewOutcome,
|
||||
readableFailure,
|
||||
resolvePullRequestPrimaryControl,
|
||||
shouldRefreshPullRequestActivity,
|
||||
resolveBaseFreshness,
|
||||
buildPullRequestTimeline,
|
||||
@@ -146,6 +147,54 @@ describe("pull request action menu", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("pull request primary control", () => {
|
||||
const open = {
|
||||
state: "open" as const,
|
||||
isDraft: false,
|
||||
mergeability: "mergeable" as const,
|
||||
checksState: "passing" as const,
|
||||
autoMergeEnabled: false,
|
||||
hasMergeMethod: true,
|
||||
canMerge: true,
|
||||
canMarkReady: true,
|
||||
canEnableAutoMerge: true,
|
||||
};
|
||||
|
||||
it("moves pending and failing checks to auto-merge", () => {
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, checksState: "pending" })).toBe(
|
||||
"enable-auto-merge",
|
||||
);
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, checksState: "failing" })).toBe(
|
||||
"enable-auto-merge",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer auto-merge while the host state is unknown", () => {
|
||||
expect(
|
||||
resolvePullRequestPrimaryControl({
|
||||
...open,
|
||||
checksState: "pending",
|
||||
autoMergeEnabled: undefined,
|
||||
}),
|
||||
).toBe("merge");
|
||||
});
|
||||
|
||||
it("keeps armed and terminal states in the merge button slot", () => {
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, autoMergeEnabled: true })).toBe(
|
||||
"auto-merge-armed",
|
||||
);
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, state: "merged" })).toBe("merged");
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, state: "closed" })).toBe("closed");
|
||||
});
|
||||
|
||||
it("keeps conflicts and drafts actionable before merge", () => {
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, mergeability: "conflicting" })).toBe(
|
||||
"resolve",
|
||||
);
|
||||
expect(resolvePullRequestPrimaryControl({ ...open, isDraft: true })).toBe("ready");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pull request state description", () => {
|
||||
it("keeps draft and conflicts orthogonal to the terminal states", () => {
|
||||
expect(describePullRequestState("open", true)).toBe("Draft");
|
||||
@@ -1243,7 +1292,9 @@ describe("which actions need the host read again after they run", () => {
|
||||
// Imported from the contract rather than hand-listed, so a new PullRequestAction fails this
|
||||
// test until somebody decides which side of the diff it belongs on.
|
||||
expect(PullRequestAction.literals.map(pullRequestActionNeedsHostRefresh)).toEqual(
|
||||
PullRequestAction.literals.map((action) => action === "update-branch"),
|
||||
PullRequestAction.literals.map(
|
||||
(action) => action === "update-branch" || action === "approve-workflows",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1260,6 +1311,7 @@ describe("which actions need the host read again after they run", () => {
|
||||
"enable-auto-merge",
|
||||
"disable-auto-merge",
|
||||
"merge",
|
||||
"revert",
|
||||
] as const) {
|
||||
expect(pullRequestActionNeedsHostRefresh(action)).toBe(false);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
PullRequestActor,
|
||||
PullRequestBaseComparison,
|
||||
PullRequestCheck,
|
||||
PullRequestChecksState,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestDetailView,
|
||||
@@ -20,6 +21,45 @@ import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/re
|
||||
const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/;
|
||||
const bitbucketRepositoryName = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
|
||||
|
||||
export type PullRequestPrimaryControl =
|
||||
| "resolve"
|
||||
| "ready"
|
||||
| "merge"
|
||||
| "enable-auto-merge"
|
||||
| "auto-merge-armed"
|
||||
| "merged"
|
||||
| "closed"
|
||||
| null;
|
||||
|
||||
/** The one merge-area state shown in the header, including terminal and deferred states. */
|
||||
export function resolvePullRequestPrimaryControl(input: {
|
||||
readonly state: PullRequestState;
|
||||
readonly isDraft: boolean;
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
readonly checksState: PullRequestChecksState | null;
|
||||
readonly autoMergeEnabled: boolean | undefined;
|
||||
readonly hasMergeMethod: boolean;
|
||||
readonly canMerge: boolean;
|
||||
readonly canMarkReady: boolean;
|
||||
readonly canEnableAutoMerge: boolean;
|
||||
}): PullRequestPrimaryControl {
|
||||
if (input.state === "merged") return "merged";
|
||||
if (input.state === "closed") return "closed";
|
||||
if (input.mergeability === "conflicting") return "resolve";
|
||||
if (input.isDraft) return input.canMarkReady ? "ready" : null;
|
||||
if (input.autoMergeEnabled) return "auto-merge-armed";
|
||||
if (!input.hasMergeMethod) return null;
|
||||
if (
|
||||
input.autoMergeEnabled === false &&
|
||||
input.checksState !== null &&
|
||||
input.checksState !== "passing" &&
|
||||
input.canEnableAutoMerge
|
||||
) {
|
||||
return "enable-auto-merge";
|
||||
}
|
||||
return input.canMerge ? "merge" : null;
|
||||
}
|
||||
|
||||
export function pullRequestCheckoutCommand(
|
||||
provider: SourceControlProviderKind,
|
||||
number: number,
|
||||
@@ -949,11 +989,9 @@ export function resolveBaseFreshness(detail: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a completed action leaves the diff atom pointed at a comparison that no longer exists,
|
||||
* the same staleness the manual refresh button fixes. Only `update-branch` moves the head commit;
|
||||
* a merge moves the branch too, but it also closes the pull request, where the diff is no longer
|
||||
* what anyone is looking at. Written as a `Record` so a new `PullRequestAction` fails to compile
|
||||
* here until somebody decides which side of the diff it belongs on.
|
||||
* Whether a completed action needs the uncached host read rather than the cheaper detail refresh.
|
||||
* Updating a branch moves the diff's head. Approving workflows changes data GitHub omits from the
|
||||
* normal pull-request detail. Written as a `Record` so every new action makes that choice here.
|
||||
*/
|
||||
const ACTION_NEEDS_HOST_REFRESH: Record<PullRequestAction, boolean> = {
|
||||
"update-branch": true,
|
||||
@@ -964,6 +1002,8 @@ const ACTION_NEEDS_HOST_REFRESH: Record<PullRequestAction, boolean> = {
|
||||
reopen: false,
|
||||
"enable-auto-merge": false,
|
||||
"disable-auto-merge": false,
|
||||
revert: false,
|
||||
"approve-workflows": true,
|
||||
};
|
||||
|
||||
export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): boolean {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
readPullRequestListSnapshot,
|
||||
writePullRequestListSnapshot,
|
||||
rankPullRequestMatches,
|
||||
rankPullRequestsByMergeReadiness,
|
||||
scorePullRequestMatch,
|
||||
retainVisiblePullRequestStatsBatches,
|
||||
withDiffStat,
|
||||
@@ -29,6 +30,11 @@ import {
|
||||
resolveSelectedEnvironmentId,
|
||||
type EnvironmentPullRequestEntry,
|
||||
} from "./pullRequestList.logic";
|
||||
import {
|
||||
pullRequestListPreferences,
|
||||
readPullRequestListPreferences,
|
||||
writePullRequestListPreferences,
|
||||
} from "./pullRequestListPreferences";
|
||||
|
||||
const VIEWERS = { "github.com": "Bilal" } as const;
|
||||
const NO_VIEWERS = {} as const;
|
||||
@@ -656,6 +662,99 @@ describe("ranking what a search found", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("default merge-readiness ranking", () => {
|
||||
it("puts ready work first, finished work after open work, and every conflict last", () => {
|
||||
const conflict = entry({
|
||||
number: 1,
|
||||
mergeability: "conflicting",
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
updatedAt: "2026-09-01T00:00:00Z",
|
||||
});
|
||||
const other = entry({
|
||||
number: 2,
|
||||
checksState: "pending",
|
||||
updatedAt: "2026-08-01T00:00:00Z",
|
||||
});
|
||||
const green = entry({
|
||||
number: 3,
|
||||
checksState: "passing",
|
||||
reviewDecision: "review-required",
|
||||
updatedAt: "2026-07-01T00:00:00Z",
|
||||
});
|
||||
const approved = entry({
|
||||
number: 4,
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
updatedAt: "2026-06-01T00:00:00Z",
|
||||
});
|
||||
const draft = entry({
|
||||
number: 5,
|
||||
isDraft: true,
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
updatedAt: "2026-09-02T00:00:00Z",
|
||||
});
|
||||
const finished = entry({
|
||||
number: 6,
|
||||
state: "merged",
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
updatedAt: "2026-09-03T00:00:00Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
rankPullRequestsByMergeReadiness([conflict, other, green, approved, draft, finished]).map(
|
||||
(row) => row.number,
|
||||
),
|
||||
).toEqual([4, 3, 5, 2, 6, 1]);
|
||||
});
|
||||
|
||||
it("uses recency inside one readiness tier", () => {
|
||||
const older = entry({ number: 1, checksState: "passing" });
|
||||
const newer = entry({
|
||||
number: 2,
|
||||
checksState: "passing",
|
||||
updatedAt: "2026-08-01T00:00:00Z",
|
||||
});
|
||||
|
||||
expect(rankPullRequestsByMergeReadiness([older, newer]).map((row) => row.number)).toEqual([
|
||||
2, 1,
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts the smallest measured change first inside a readiness tier", () => {
|
||||
const larger = entry({
|
||||
number: 1,
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
additions: 40,
|
||||
deletions: 10,
|
||||
updatedAt: "2026-09-01T00:00:00Z",
|
||||
});
|
||||
const smaller = entry({
|
||||
number: 2,
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
additions: 3,
|
||||
deletions: 2,
|
||||
updatedAt: "2026-08-01T00:00:00Z",
|
||||
});
|
||||
const unknown = entry({
|
||||
number: 3,
|
||||
checksState: "passing",
|
||||
reviewDecision: "approved",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
updatedAt: "2026-09-02T00:00:00Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
rankPullRequestsByMergeReadiness([larger, unknown, smaller]).map((row) => row.number),
|
||||
).toEqual([2, 1, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("line counts that arrive after the rows", () => {
|
||||
const stats = new Map([["env-1 project-1 7", { additions: 42, deletions: 3 }]]);
|
||||
|
||||
@@ -858,6 +957,74 @@ describe("the list snapshot across a reload", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("remembered pull request list controls", () => {
|
||||
const makeStorage = () => {
|
||||
const held = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key: string) => held.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void held.set(key, value),
|
||||
};
|
||||
};
|
||||
|
||||
it("restores every filter and the selected sort", () => {
|
||||
const storage = makeStorage();
|
||||
const preferences = {
|
||||
involvement: "reviewing",
|
||||
state: "merged",
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
projectId: "project-1" as ProjectId,
|
||||
host: "github.com",
|
||||
q: "workflow",
|
||||
draft: "hide",
|
||||
review: "approved",
|
||||
checks: "passing",
|
||||
author: "octocat",
|
||||
labels: ["bug", "priority"],
|
||||
sort: "largest",
|
||||
} as const;
|
||||
|
||||
writePullRequestListPreferences(preferences, storage);
|
||||
expect(readPullRequestListPreferences(storage)).toEqual(preferences);
|
||||
});
|
||||
|
||||
it("omits the default sort from storage", () => {
|
||||
expect(
|
||||
pullRequestListPreferences({
|
||||
involvement: "all",
|
||||
state: "open",
|
||||
sort: "ready",
|
||||
}),
|
||||
).toEqual({ involvement: "all", state: "open" });
|
||||
});
|
||||
|
||||
it("keeps an explicit recency sort", () => {
|
||||
expect(
|
||||
pullRequestListPreferences({ involvement: "all", state: "open", sort: "updated" }),
|
||||
).toEqual({ involvement: "all", state: "open", sort: "updated" });
|
||||
});
|
||||
|
||||
it("falls back to the default controls when storage is corrupt", () => {
|
||||
const storage = makeStorage();
|
||||
storage.setItem("t3.pullRequests.preferences", "{not json");
|
||||
expect(readPullRequestListPreferences(storage)).toEqual({ involvement: "all", state: "open" });
|
||||
});
|
||||
|
||||
it("falls back when browser policy denies storage", () => {
|
||||
const denied = {
|
||||
getItem: () => {
|
||||
throw new Error("storage denied");
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error("storage denied");
|
||||
},
|
||||
};
|
||||
expect(readPullRequestListPreferences(denied)).toEqual({ involvement: "all", state: "open" });
|
||||
expect(() =>
|
||||
writePullRequestListPreferences({ involvement: "all", state: "open" }, denied),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
const ENV_1 = "env-1" as EnvironmentId;
|
||||
const ENV_2 = "env-2" as EnvironmentId;
|
||||
|
||||
|
||||
@@ -985,7 +985,7 @@ export function scorePullRequestMatch(entry: PullRequestListEntry, query: string
|
||||
|
||||
/**
|
||||
* Search results in the order they answer the question, most convincing first, and by recency
|
||||
* among equals. Only for a search: without one, a listing is a timeline and recency is the order.
|
||||
* among equals. Without a search, preserve the host order for the caller's browse-time ranking.
|
||||
*/
|
||||
export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
|
||||
entries: ReadonlyArray<Entry>,
|
||||
@@ -998,6 +998,35 @@ export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The default review queue: work that is green and approved, then green work still waiting on a
|
||||
* verdict, then everything else still open. Drafts stay in that third tier because their author
|
||||
* has not made them mergeable yet. Finished work follows open work when all states are visible. A
|
||||
* known conflict is never ready, whatever its checks, review or state say, so it stays at the
|
||||
* bottom. Smaller measured changes come first within a tier; recency only breaks a remaining tie.
|
||||
*/
|
||||
export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEntry>(
|
||||
entries: ReadonlyArray<Entry>,
|
||||
hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
|
||||
): ReadonlyArray<Entry> {
|
||||
const tier = (entry: Entry) => {
|
||||
if (entry.mergeability === "conflicting") return 4;
|
||||
if (entry.state !== "open") return 3;
|
||||
if (entry.isDraft) return 2;
|
||||
if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 0;
|
||||
if (entry.checksState === "passing") return 1;
|
||||
return 2;
|
||||
};
|
||||
return entries.toSorted((left, right) => {
|
||||
const byTier = tier(left) - tier(right);
|
||||
if (byTier !== 0) return byTier;
|
||||
const byMeasurement = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
|
||||
if (byMeasurement !== 0) return byMeasurement;
|
||||
const bySize = left.additions + left.deletions - (right.additions + right.deletions);
|
||||
return bySize !== 0 ? bySize : right.updatedAt.localeCompare(left.updatedAt);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A row with the line counts that arrived after it did. Only where the host left them out — a
|
||||
* listing that carried them is not second-guessed — and only where they have arrived, since a row
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
PullRequestInvolvement,
|
||||
PullRequestListFilters,
|
||||
PullRequestListState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export const PullRequestListSort = Schema.Literals([
|
||||
"ready",
|
||||
"updated",
|
||||
"newest",
|
||||
"oldest",
|
||||
"largest",
|
||||
"smallest",
|
||||
]);
|
||||
export type PullRequestListSort = typeof PullRequestListSort.Type;
|
||||
|
||||
export interface PullRequestListPreferences {
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly state: PullRequestListState;
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly projectId?: ProjectId;
|
||||
readonly host?: string;
|
||||
readonly q?: string;
|
||||
readonly draft?: "only" | "hide";
|
||||
readonly review?: NonNullable<PullRequestListFilters["review"]>;
|
||||
readonly checks?: NonNullable<PullRequestListFilters["checks"]>;
|
||||
readonly author?: string;
|
||||
readonly labels?: ReadonlyArray<string>;
|
||||
readonly sort?: PullRequestListSort;
|
||||
}
|
||||
|
||||
export type PullRequestListPreferencePatch = {
|
||||
[Key in keyof PullRequestListPreferences]?: PullRequestListPreferences[Key] | undefined;
|
||||
};
|
||||
|
||||
export const DEFAULT_PULL_REQUEST_LIST_PREFERENCES = {
|
||||
involvement: "all",
|
||||
state: "open",
|
||||
} as const satisfies PullRequestListPreferences;
|
||||
|
||||
const BoundedPreference = Schema.String.check(Schema.isMaxLength(200));
|
||||
const PullRequestListPreferencesSchema = Schema.Struct({
|
||||
involvement: PullRequestInvolvement,
|
||||
state: PullRequestListState,
|
||||
environmentId: Schema.optional(EnvironmentId),
|
||||
projectId: Schema.optional(ProjectId),
|
||||
host: Schema.optional(BoundedPreference),
|
||||
q: Schema.optional(BoundedPreference),
|
||||
draft: PullRequestListFilters.fields.draft,
|
||||
review: PullRequestListFilters.fields.review,
|
||||
checks: PullRequestListFilters.fields.checks,
|
||||
author: Schema.optional(BoundedPreference),
|
||||
labels: Schema.optional(Schema.Array(BoundedPreference).check(Schema.isMaxLength(10))),
|
||||
sort: Schema.optional(PullRequestListSort),
|
||||
});
|
||||
|
||||
const decodePullRequestListPreferences = Schema.decodeUnknownOption(
|
||||
PullRequestListPreferencesSchema,
|
||||
);
|
||||
const PULL_REQUEST_LIST_PREFERENCES_STORAGE_KEY = "t3.pullRequests.preferences";
|
||||
type PreferenceStorage = Pick<Storage, "getItem" | "setItem">;
|
||||
|
||||
function resolvePreferenceStorage(
|
||||
storage: PreferenceStorage | undefined,
|
||||
): PreferenceStorage | undefined {
|
||||
return storage ?? (typeof window === "undefined" ? undefined : window.localStorage);
|
||||
}
|
||||
|
||||
/** Only list controls are remembered. The selected row remains a URL and right-panel concern. */
|
||||
export function pullRequestListPreferences(
|
||||
search: PullRequestListPreferences | Schema.Schema.Type<typeof PullRequestListPreferencesSchema>,
|
||||
): PullRequestListPreferences {
|
||||
return {
|
||||
involvement: search.involvement,
|
||||
state: search.state,
|
||||
...(search.environmentId ? { environmentId: search.environmentId } : {}),
|
||||
...(search.projectId ? { projectId: search.projectId } : {}),
|
||||
...(search.host ? { host: search.host } : {}),
|
||||
...(search.q ? { q: search.q } : {}),
|
||||
...(search.draft ? { draft: search.draft } : {}),
|
||||
...(search.review ? { review: search.review } : {}),
|
||||
...(search.checks ? { checks: search.checks } : {}),
|
||||
...(search.author ? { author: search.author } : {}),
|
||||
...(search.labels && search.labels.length > 0 ? { labels: search.labels } : {}),
|
||||
...(search.sort && search.sort !== "ready" ? { sort: search.sort } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function readPullRequestListPreferences(
|
||||
storage?: PreferenceStorage,
|
||||
): PullRequestListPreferences {
|
||||
try {
|
||||
const raw = resolvePreferenceStorage(storage)?.getItem(
|
||||
PULL_REQUEST_LIST_PREFERENCES_STORAGE_KEY,
|
||||
);
|
||||
if (!raw) return DEFAULT_PULL_REQUEST_LIST_PREFERENCES;
|
||||
const decoded = decodePullRequestListPreferences(JSON.parse(raw));
|
||||
return decoded._tag === "Some"
|
||||
? pullRequestListPreferences(decoded.value)
|
||||
: DEFAULT_PULL_REQUEST_LIST_PREFERENCES;
|
||||
} catch {
|
||||
return DEFAULT_PULL_REQUEST_LIST_PREFERENCES;
|
||||
}
|
||||
}
|
||||
|
||||
export function writePullRequestListPreferences(
|
||||
preferences: PullRequestListPreferences,
|
||||
storage?: PreferenceStorage,
|
||||
): void {
|
||||
try {
|
||||
resolvePreferenceStorage(storage)?.setItem(
|
||||
PULL_REQUEST_LIST_PREFERENCES_STORAGE_KEY,
|
||||
JSON.stringify(preferences),
|
||||
);
|
||||
} catch {
|
||||
// Storage can be full or denied; the URL remains the source of truth for this visit.
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,11 @@ export function PullRequestStateGlyph({
|
||||
|
||||
const CHECK_STATUS_PRESENTATION = {
|
||||
pending: { label: "Running", Icon: LoaderIcon, toneClassName: "animate-spin text-amber-500" },
|
||||
"action-required": {
|
||||
label: "Awaiting action",
|
||||
Icon: CircleDotIcon,
|
||||
toneClassName: "text-amber-600 dark:text-amber-400/90",
|
||||
},
|
||||
success: {
|
||||
label: "Passed",
|
||||
Icon: CircleCheckIcon,
|
||||
@@ -134,8 +139,20 @@ const CHECK_STATUS_PRESENTATION = {
|
||||
{ label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
|
||||
>;
|
||||
|
||||
export function pullRequestCheckStatusLabel(status: PullRequestCheckStatus): string {
|
||||
return CHECK_STATUS_PRESENTATION[status].label;
|
||||
function isWorkflowApprovalCheck(check: Pick<PullRequestCheck, "status" | "url">): boolean {
|
||||
return (
|
||||
check.status === "action-required" &&
|
||||
check.url !== null &&
|
||||
/\/actions\/runs\/\d+(?:\/|$)/u.test(check.url)
|
||||
);
|
||||
}
|
||||
|
||||
export function pullRequestCheckStatusLabel(
|
||||
check: Pick<PullRequestCheck, "status" | "url">,
|
||||
): string {
|
||||
return isWorkflowApprovalCheck(check)
|
||||
? "Awaiting approval"
|
||||
: CHECK_STATUS_PRESENTATION[check.status].label;
|
||||
}
|
||||
|
||||
export function PullRequestCheckStatusIcon({ status }: { status: PullRequestCheckStatus }) {
|
||||
@@ -187,10 +204,10 @@ export function pullRequestChecksState(
|
||||
checks: ReadonlyArray<PullRequestCheck>,
|
||||
): PullRequestChecksState | null {
|
||||
if (checks.length === 0) return null;
|
||||
const statuses = checks.map((check) => check.status);
|
||||
if (statuses.includes("failure") || statuses.includes("cancelled")) return "failing";
|
||||
if (statuses.includes("pending")) return "pending";
|
||||
return statuses.includes("success") ? "passing" : null;
|
||||
const statuses = new Set(checks.map((check) => check.status));
|
||||
if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
|
||||
if (statuses.has("pending") || statuses.has("action-required")) return "pending";
|
||||
return statuses.has("success") ? "passing" : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -435,12 +452,24 @@ export function PullRequestMetaLine({
|
||||
|
||||
export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
|
||||
if (checks.length === 0) return "No checks reported";
|
||||
const actionRequired = checks.filter((check) => check.status === "action-required");
|
||||
const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
|
||||
const otherActionRequired = actionRequired.length - workflowApprovalRequired;
|
||||
const failed = checks.filter(
|
||||
(check) => check.status === "failure" || check.status === "cancelled",
|
||||
).length;
|
||||
const pending = checks.filter((check) => check.status === "pending").length;
|
||||
const passed = checks.filter((check) => check.status === "success").length;
|
||||
if (failed > 0) return `${failed} of ${checks.length} failing`;
|
||||
if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
|
||||
return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
|
||||
}
|
||||
if (workflowApprovalRequired > 0) {
|
||||
return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
|
||||
}
|
||||
if (otherActionRequired > 0) {
|
||||
return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
|
||||
}
|
||||
if (pending > 0) return `${pending} of ${checks.length} running`;
|
||||
return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
useSidebar,
|
||||
} from "../ui/sidebar";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { readPullRequestListPreferences } from "../pullRequest/pullRequestListPreferences";
|
||||
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
|
||||
import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill";
|
||||
|
||||
@@ -157,7 +158,10 @@ export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() {
|
||||
}, [isMobile, setOpenMobile]);
|
||||
const handlePullRequestsClick = useCallback(() => {
|
||||
closeMobileSidebar();
|
||||
void navigate({ to: "/pull-requests", search: { involvement: "all", state: "open" } });
|
||||
void navigate({
|
||||
to: "/pull-requests",
|
||||
search: readPullRequestListPreferences(),
|
||||
});
|
||||
}, [closeMobileSidebar, navigate]);
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
closeMobileSidebar();
|
||||
|
||||
@@ -15,6 +15,8 @@ const badgeVariants = cva(
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
control:
|
||||
"h-7 min-w-7 rounded-[var(--control-radius)] px-[calc(--spacing(2)-1px)] text-sm sm:h-6 sm:min-w-6 sm:text-xs",
|
||||
default:
|
||||
"h-5.5 min-w-5.5 px-[calc(--spacing(1)-1px)] text-sm sm:h-4.5 sm:min-w-4.5 sm:text-xs",
|
||||
lg: "h-6.5 min-w-6.5 px-[calc(--spacing(1.5)-1px)] text-base sm:h-5.5 sm:min-w-5.5 sm:text-sm",
|
||||
|
||||
@@ -53,6 +53,8 @@ const buttonVariants = cva(
|
||||
"[--control-icon-color:var(--contrast-muted-foreground)] border-input bg-popover not-dark:bg-clip-padding text-foreground shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:not-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:bg-accent/50 dark:[:hover,[data-pressed]]:bg-input/64",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [:active,[data-pressed]]:bg-secondary/80 [:hover,[data-pressed]]:bg-secondary/90",
|
||||
"warning-outline":
|
||||
"border-warning/32 bg-warning-surface text-warning-foreground shadow-xs/5 [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:border-warning/40 [:hover,[data-pressed]]:bg-warning/16 dark:[:hover,[data-pressed]]:bg-warning/24",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
GitPullRequestClosedIcon,
|
||||
GitPullRequestIcon,
|
||||
LayersIcon,
|
||||
ListChecksIcon,
|
||||
PenLineIcon,
|
||||
LoaderIcon,
|
||||
Maximize2Icon,
|
||||
@@ -57,6 +58,7 @@ import {
|
||||
pullRequestEntryKey,
|
||||
pullRequestEntryViewer,
|
||||
rankPullRequestMatches,
|
||||
rankPullRequestsByMergeReadiness,
|
||||
pullRequestEnvironmentSetKey,
|
||||
readPullRequestListSnapshot,
|
||||
resolveProjectScope,
|
||||
@@ -76,6 +78,13 @@ import {
|
||||
type PullRequestStatsScope,
|
||||
type PullRequestPartitionsSnapshot,
|
||||
} from "../components/pullRequest/pullRequestList.logic";
|
||||
import {
|
||||
pullRequestListPreferences,
|
||||
type PullRequestListPreferencePatch,
|
||||
type PullRequestListPreferences,
|
||||
type PullRequestListSort,
|
||||
writePullRequestListPreferences,
|
||||
} from "../components/pullRequest/pullRequestListPreferences";
|
||||
import { assignProjectsToEnvironments } from "../components/pullRequest/pullRequestProjectAssignment.logic";
|
||||
import { PullRequestDetailPanel } from "../components/pullRequest/PullRequestDetailPanel";
|
||||
import {
|
||||
@@ -129,9 +138,7 @@ import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
|
||||
|
||||
export interface PullRequestsSearch {
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly state: PullRequestListState;
|
||||
export interface PullRequestsSearch extends PullRequestListPreferences {
|
||||
/**
|
||||
* Narrows the list to one server. Absent means every connected one, which is the default the
|
||||
* page has now — so a link written before servers could be chosen still opens the whole list.
|
||||
@@ -153,21 +160,8 @@ export interface PullRequestsSearch {
|
||||
* link without it still opens, resolved by project id alone where that is unambiguous.
|
||||
*/
|
||||
readonly selectedEnvironmentId?: EnvironmentId;
|
||||
readonly q?: string;
|
||||
/**
|
||||
* The narrowings beyond state and involvement, each absent when that group is unfiltered. Flat
|
||||
* in the URL because a link is read and edited by hand; folded into one record for the listing.
|
||||
*/
|
||||
readonly draft?: "only" | "hide";
|
||||
readonly review?: NonNullable<PullRequestListFilters["review"]>;
|
||||
readonly checks?: NonNullable<PullRequestListFilters["checks"]>;
|
||||
readonly author?: string;
|
||||
readonly labels?: ReadonlyArray<string>;
|
||||
readonly sort?: PullRequestListSort;
|
||||
}
|
||||
|
||||
type PullRequestListSort = "updated" | "newest" | "oldest" | "largest" | "smallest";
|
||||
|
||||
// The state filters wear the same glyphs the rows do, so the two read as one vocabulary.
|
||||
const INVOLVEMENT_TABS = [
|
||||
{ value: "all", label: "All", Icon: LayersIcon },
|
||||
@@ -183,6 +177,7 @@ const STATE_TABS = [
|
||||
] as const satisfies ReadonlyArray<PullRequestFilterOption<PullRequestListState>>;
|
||||
|
||||
const SORT_OPTIONS = [
|
||||
{ value: "ready", label: "Merge readiness", Icon: ListChecksIcon },
|
||||
{ value: "updated", label: "Recently updated", Icon: ClockIcon },
|
||||
{ value: "newest", label: "Newest shown", Icon: CalendarArrowDownIcon },
|
||||
{ value: "oldest", label: "Oldest shown", Icon: CalendarArrowUpIcon },
|
||||
@@ -287,9 +282,9 @@ export const Route = createFileRoute("/_chat/pull-requests")({
|
||||
|
||||
function PullRequestsRouteView() {
|
||||
const search = Route.useSearch();
|
||||
const sort = search.sort ?? "updated";
|
||||
const sort = search.sort ?? "ready";
|
||||
const statsPolicy: PullRequestStatsPolicy =
|
||||
sort === "largest" || sort === "smallest" ? "eager" : "visible";
|
||||
sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";
|
||||
const navigate = useNavigate({ from: Route.fullPath });
|
||||
const { environments } = useEnvironments();
|
||||
// Every connected environment that has said it can list pull requests. Sorted, so the query
|
||||
@@ -487,7 +482,7 @@ function PullRequestsRouteView() {
|
||||
return {
|
||||
involvement: next.involvement ?? previous.involvement,
|
||||
state: next.state ?? previous.state,
|
||||
...(next.sort && next.sort !== "updated" ? { sort: next.sort } : {}),
|
||||
...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
|
||||
...(next.repository ? { repository: next.repository } : {}),
|
||||
...(next.number ? { number: next.number } : {}),
|
||||
...(next.projectId ? { projectId: next.projectId } : {}),
|
||||
@@ -510,22 +505,25 @@ function PullRequestsRouteView() {
|
||||
[navigate],
|
||||
);
|
||||
|
||||
// Changing what the list contains must not leave a selection from the previous view open.
|
||||
// The project filter is untouched: it is the user's scope, not part of the selection.
|
||||
const clearedSelection = {
|
||||
repository: undefined,
|
||||
number: undefined,
|
||||
selectedProjectId: undefined,
|
||||
selectedEnvironmentId: undefined,
|
||||
};
|
||||
const updateListScope = (patch: {
|
||||
[Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
|
||||
}) => {
|
||||
if (rightPanelRef !== null) {
|
||||
// Hide the old selection while retaining peer PR tabs for parallel reviews.
|
||||
useRightPanelStore.getState().close(rightPanelRef);
|
||||
}
|
||||
updateSearch({ ...patch, ...clearedSelection });
|
||||
// List controls change the rows behind the detail, not the independent selected surface. The
|
||||
// reader can keep working in that panel while narrowing, sorting, or switching projects.
|
||||
const updateListScope = (patch: PullRequestListPreferencePatch) => {
|
||||
const currentPreferences = pullRequestListPreferences({
|
||||
...search,
|
||||
...patch,
|
||||
involvement: patch.involvement ?? search.involvement,
|
||||
state: patch.state ?? search.state,
|
||||
});
|
||||
// Opening a selected-only link does not save its default all/open list. Once a list control
|
||||
// changes, the entire visible scope is intentional and becomes the next sidebar destination.
|
||||
writePullRequestListPreferences(currentPreferences);
|
||||
updateSearch(patch);
|
||||
};
|
||||
|
||||
// Searching asks the hosts, which takes a round trip, so the text is held for a moment before
|
||||
@@ -1420,7 +1418,24 @@ function PullRequestsRouteView() {
|
||||
...group,
|
||||
entries: group.entries.map((entry) => withDiffStat(entry, statsByRow)),
|
||||
}));
|
||||
if (sort === "updated") return enriched;
|
||||
if (sort === "ready" && typedParsed.text.length === 0) {
|
||||
return [
|
||||
{
|
||||
key: "others" as const,
|
||||
label: "",
|
||||
entries: rankPullRequestsByMergeReadiness(
|
||||
enriched.flatMap((group) => group.entries),
|
||||
(entry) =>
|
||||
entry.additions + entry.deletions > 0 ||
|
||||
statsByRow.has(pullRequestDiffStatKey(entry)),
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
// Searching keeps its relevance order and priority groups unless the reader explicitly asks
|
||||
// for another sort. The readiness queue is the default browse order, not a way to bury a
|
||||
// closer text match.
|
||||
if (sort === "ready" || sort === "updated") return enriched;
|
||||
const entries = enriched.flatMap((group) => group.entries);
|
||||
const hasSize = (entry: (typeof entries)[number]) =>
|
||||
entry.additions + entry.deletions > 0 || statsByRow.has(pullRequestDiffStatKey(entry));
|
||||
@@ -1448,7 +1463,7 @@ function PullRequestsRouteView() {
|
||||
}),
|
||||
},
|
||||
];
|
||||
}, [groups, sort, statsByRow]);
|
||||
}, [groups, sort, statsByRow, typedParsed.text]);
|
||||
|
||||
const linkedSelection = useMemo(
|
||||
() =>
|
||||
@@ -1567,7 +1582,7 @@ function PullRequestsRouteView() {
|
||||
<PullRequestSearchInput
|
||||
value={search.q ?? ""}
|
||||
busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
|
||||
onChange={(query) => updateSearch({ q: query || undefined })}
|
||||
onChange={(query) => updateListScope({ q: query || undefined })}
|
||||
/>
|
||||
);
|
||||
const panelToggleControls = (
|
||||
@@ -1635,7 +1650,7 @@ function PullRequestsRouteView() {
|
||||
searching={typedQuery.length > 0 && (!querySettled || showingCarried)}
|
||||
canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)}
|
||||
loadingMore={loadingMore}
|
||||
onClearQuery={() => updateSearch({ q: undefined })}
|
||||
onClearQuery={() => updateListScope({ q: undefined })}
|
||||
onLoadMore={loadMore}
|
||||
/>
|
||||
) : (
|
||||
@@ -1739,7 +1754,7 @@ function PullRequestsRouteView() {
|
||||
outlined
|
||||
value={sort}
|
||||
options={SORT_OPTIONS}
|
||||
onChange={(next) => updateSearch({ sort: next })}
|
||||
onChange={(next) => updateListScope({ sort: next })}
|
||||
/>
|
||||
);
|
||||
const filtersMenu = (
|
||||
|
||||
@@ -41,9 +41,19 @@ T3 Code works with the platforms your team already uses:
|
||||
|
||||
- See if your current branch already has an open PR/MR
|
||||
- Open several reviews from the **Pull requests** page as tabs in the right panel
|
||||
- By default, see passing and approved reviews first, passing reviews awaiting approval next, and
|
||||
conflicting reviews last. Smaller changes come first within each readiness group, and finished
|
||||
reviews follow open work when all states are visible.
|
||||
- Filter the list by author or labels, rank authors by merges in the loaded results, see label and
|
||||
change-size context on each row, and sort the results currently shown by update time, creation
|
||||
time, or change size
|
||||
change-size context on each row, and sort the results currently shown by readiness, update time,
|
||||
creation time, or change size. Your filters, search, scope, and sort are restored when you return.
|
||||
- Merge now, or on GitHub, GitLab, and Azure DevOps, leave an auto-merge instruction with a chosen
|
||||
strategy while checks are outstanding; see the completed state in the same control after the
|
||||
pull request merges
|
||||
- On GitHub, approve fork workflows that are waiting to run and open a revert pull request for a
|
||||
merged change
|
||||
- Timeline line counts stay hidden on merge commits, where GitHub's totals include upstream changes
|
||||
brought in from the base branch
|
||||
- While working in a thread, open linked reviews in the same compact right-panel tabs without
|
||||
leaving the conversation
|
||||
- Enable **Settings → General → Proactive panels** to open a newly linked review automatically and
|
||||
@@ -56,6 +66,8 @@ T3 Code works with the platforms your team already uses:
|
||||
|
||||
**Fix what you wrote, in place**
|
||||
|
||||
- Comment while closing an open pull request or reopening a closed one when the host offers that
|
||||
action
|
||||
- Rewrite a pull request's title and description from the review itself, in Markdown, with a
|
||||
preview before you save
|
||||
- Rewrite your own comments the same way, wherever they are shown
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
const decodeListResult = Schema.decodeUnknownSync(PullRequestListResult);
|
||||
const decodeListInput = Schema.decodeUnknownSync(PullRequestListInput);
|
||||
const decodeReviewerRequest = Schema.decodeUnknownSync(PullRequestReviewerRequestInput);
|
||||
const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);
|
||||
|
||||
const LIST_RESULT: PullRequestListResult = {
|
||||
viewers: { "github.com": "bilal", "gitlab.com": "bilal.hassan" },
|
||||
@@ -158,7 +159,6 @@ describe("PullRequestReviewerRequestInput", () => {
|
||||
});
|
||||
|
||||
describe("updating a branch that has fallen behind its base", () => {
|
||||
const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);
|
||||
const ref = { projectId: "project-1", repository: "acme/web", number: 7 };
|
||||
|
||||
it("carries the way the branch should be brought up to date", () => {
|
||||
@@ -182,7 +182,6 @@ describe("updating a branch that has fallen behind its base", () => {
|
||||
});
|
||||
|
||||
describe("leaving a merge for the host to make once it is ready", () => {
|
||||
const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);
|
||||
const ref = { projectId: "project-1", repository: "acme/web", number: 7 };
|
||||
|
||||
it("carries the strategy the deferred merge should use, as merging now does", () => {
|
||||
@@ -196,6 +195,33 @@ describe("leaving a merge for the host to make once it is ready", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("reverting a merged pull request", () => {
|
||||
it("carries the revert action without merge options", () => {
|
||||
const action = decodeAction({
|
||||
projectId: "project-1",
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
action: "revert",
|
||||
});
|
||||
|
||||
expect(action.action).toBe("revert");
|
||||
expect(action.mergeMethod).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("approving fork workflows", () => {
|
||||
it("carries workflow approval as its own action", () => {
|
||||
const action = decodeAction({
|
||||
projectId: "project-1",
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
action: "approve-workflows",
|
||||
});
|
||||
|
||||
expect(action.action).toBe("approve-workflows");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PullRequestCapabilities", () => {
|
||||
const decodeCapabilities = Schema.decodeUnknownSync(PullRequestCapabilities);
|
||||
const base = {
|
||||
|
||||
@@ -93,6 +93,10 @@ export const PullRequestAction = Schema.Literals([
|
||||
"enable-auto-merge",
|
||||
/** Take the standing instruction back, which leaves the change request where it was. */
|
||||
"disable-auto-merge",
|
||||
/** Open a new change request that reverses a merged one. */
|
||||
"revert",
|
||||
/** Allow Actions workflows from a fork pull request to begin running. */
|
||||
"approve-workflows",
|
||||
]);
|
||||
export type PullRequestAction = typeof PullRequestAction.Type;
|
||||
|
||||
@@ -131,6 +135,7 @@ export type PullRequestLabel = typeof PullRequestLabel.Type;
|
||||
|
||||
export const PullRequestCheckStatus = Schema.Literals([
|
||||
"pending",
|
||||
"action-required",
|
||||
"success",
|
||||
"failure",
|
||||
"skipped",
|
||||
@@ -709,6 +714,10 @@ export const PullRequestDetail = Schema.Struct({
|
||||
* arm something that is already armed, and a second arming is a write nobody asked for.
|
||||
*/
|
||||
autoMergeEnabled: Schema.optional(Schema.Boolean),
|
||||
/** The strategy the host will use for an armed auto-merge, where it reports one. */
|
||||
autoMergeMethod: Schema.optional(PullRequestMergeMethod),
|
||||
/** GitHub Actions runs on this head commit that are waiting for a maintainer's approval. */
|
||||
workflowApprovalsRequired: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
export type PullRequestDetail = typeof PullRequestDetail.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user