feat: add pr edit, close, and reopen (task 0011)
All checks were successful
CI / test (pull_request) Successful in 38s
CI / test (push) Successful in 39s

Add the PR-side state mutations mirroring the issue-side slice:

- `pr edit` applies title/body/base/milestone and the recomputed assignee
  list in one PATCH, with additive label endpoints and (per the ADR 0007
  amendment) the dedicated requested-reviewers POST/DELETE endpoints for
  `--add-reviewer`/`--remove-reviewer`.
- `pr close --comment` posts the comment after the PATCH and surfaces a
  comment-post failure; an already-closed or merged PR is an `already: true`
  no-op reporting the actual state.
- `pr reopen` is an `already: true` no-op when already open.

Extract the fetch-then-patch assignee merge into a shared `src/assignees.ts`
(`mergeAssignees` + `assigneeLogins`), now used by both `issue edit` and
`pr edit`.
This commit was merged in pull request #11.
This commit is contained in:
2026-07-13 19:55:00 -04:00
parent 6c15e6082f
commit 965ece306f
7 changed files with 808 additions and 29 deletions

View File

@@ -14,9 +14,54 @@ Success outputs follow the action-block pattern: `edited:`/`closed:`/`reopened:`
## Acceptance criteria
- [ ] `pr edit` applies title, body, milestone, and base changes and outputs `edited: { number, status: "ok" }`
- [ ] Label and assignee mutations follow the same rules as `issue edit` (additive endpoints, fetch-then-patch, unapplied-label silent success)
- [ ] `--add-reviewer`/`--remove-reviewer` call the requested-reviewers endpoints with `{ reviewers: [login] }`
- [ ] `pr close --comment` posts the comment after the PATCH and surfaces a comment failure; closing an already-closed-or-merged PR returns the entity block with `already: true`
- [ ] `pr reopen` on an open PR returns the entity block with `already: true`; otherwise outputs `reopened: { number, status: "ok" }`
- [ ] Fixture-server tests cover reviewer add/remove, the merged-PR close no-op, and the reopen paths
- [x] `pr edit` applies title, body, milestone, and base changes and outputs `edited: { number, status: "ok" }`
- [x] Label and assignee mutations follow the same rules as `issue edit` (additive endpoints, fetch-then-patch, unapplied-label silent success)
- [x] `--add-reviewer`/`--remove-reviewer` call the requested-reviewers endpoints with `{ reviewers: [login] }`
- [x] `pr close --comment` posts the comment after the PATCH and surfaces a comment failure; closing an already-closed-or-merged PR returns the entity block with `already: true`
- [x] `pr reopen` on an open PR returns the entity block with `already: true`; otherwise outputs `reopened: { number, status: "ok" }`
- [x] Fixture-server tests cover reviewer add/remove, the merged-PR close no-op, and the reopen paths
## Implementation Notes
No criteria were dropped or altered; all six are satisfied.
Decisions made mid-implementation:
- The close no-op reports the actual state: `merged` for a merged PR (whose raw
`state` Gitea reports as `closed`), otherwise the raw state — computed by a
small `pullState` helper. `pull.state === "closed"` catches both the closed and
merged cases for the short-circuit, matching the spec's "already closed or
merged".
- `pr reopen` short-circuits only on `state === "open"`, per the spec. A merged
PR (state `closed`) therefore falls through to the PATCH and Gitea rejects it as
a `VALIDATION_ERROR` — the spec asks for no merged-guard on reopen, mirroring the
issue side.
- Reviewer mutations are one POST for all `--add-reviewer` and one DELETE for all
`--remove-reviewer`, each carrying the whole list — the requested-reviewers
endpoints take arrays (ADR 0007 amendment). They are not fetch-then-patch and
are not idempotency-checked; a redundant add/remove surfaces whatever Gitea
answers.
- `--add-label`/`--remove-label`/`--add-assignee`/`--remove-assignee`/`--add-reviewer`/`--remove-reviewer`
are repeatable, matching `issue edit`.
- Name resolution (milestone, remove-label ids) runs before any mutation so a typo
is reported before a change lands. Title/body/base/milestone and the recomputed
assignee list travel in a single PATCH; labels and reviewers use their dedicated
endpoints afterward.
- Added a `VALIDATION_ERROR` when `pr edit` is invoked with no changes, matching
`issue edit`.
- Review finding (Duplicated Code): extracted the fetch-then-patch merge into a
shared `src/assignees.ts` — a pure `mergeAssignees` plus an `assigneeLogins`
reader — now used by both `issue edit` and `pr edit`, replacing the inline copy
that previously lived in `issue.ts`.
Follow-ups worth flagging (unaddressed review findings, both judgement calls):
- The close/reopen state-machine (read state → no-op short-circuit → PATCH `{state}`
→ render) is still duplicated between `issue.ts` and `pr.ts`. A shared helper was
left unextracted because the two sides diverge in their no-op shape, help
suggestions, and the PR-only merged handling, which would make the abstraction
leaky.
- The no-op output shape differs between the issue side (`message: "Already
closed"`) and the PR side (`already: true` + `state`). This is spec-driven — the
spec fixes `already: true` for PRs — but the CLI's no-op output is not uniform
across the two entities.

44
src/assignees.ts Normal file
View File

@@ -0,0 +1,44 @@
/** The subset of a Gitea `User` this module reads: just the login, if present. */
interface AssigneeLike {
login?: string;
}
/**
* The logins of an entity's current assignees, dropping any without one. The
* shared read side of fetch-then-patch: `issue edit` and `pr edit` both take the
* `assignees` off a freshly fetched entity and feed the result to
* {@link mergeAssignees}.
*/
export function assigneeLogins(assignees: AssigneeLike[] | undefined): string[] {
return (assignees ?? []).flatMap((assignee) => (assignee.login ? [assignee.login] : []));
}
/**
* The full assignee login list to PATCH under fetch-then-patch semantics
* (ADR 0007): the entity's current assignees with the requested additions
* appended and removals dropped. Matching is case-insensitive and the result is
* de-duplicated, order-preserving, so a login already assigned never lands in the
* list twice. Shared by `issue edit` and `pr edit`, whose PATCH bodies both
* replace the whole assignee list rather than adding or removing individual
* entries.
*/
export function mergeAssignees(current: string[], add: string[], remove: string[]): string[] {
const removeSet = new Set(remove.map((login) => login.toLowerCase()));
const seen = new Set<string>();
const result: string[] = [];
const push = (login: string): void => {
const key = login.toLowerCase();
if (removeSet.has(key) || seen.has(key)) {
return;
}
seen.add(key);
result.push(login);
};
for (const login of current) {
push(login);
}
for (const login of add) {
push(login);
}
return result;
}

View File

@@ -1,4 +1,5 @@
import type { Comment, CreateIssueOption, EditIssueOption, Issue, IssueMeta } from "gitea-js";
import { assigneeLogins, mergeAssignees } from "../assignees.js";
import { BODY_TRUNCATE_LIMIT, truncateBody } from "../body.js";
import { requireBodySource, resolveBodySource } from "../body-source.js";
import { createClient, type GiteaClient } from "../client.js";
@@ -702,9 +703,9 @@ async function issueComment(deps: CliDeps, args: string[]): Promise<string> {
/**
* The assignee list to PATCH: the issue's current assignees with the requested
* additions appended and removals dropped (fetch-then-patch, ADR 0007). Matching
* is case-insensitive and the result is de-duplicated, order-preserving, so a
* login that is already assigned never lands in the list twice.
* additions applied and removals dropped (fetch-then-patch, ADR 0007). The
* current logins are read off a fresh GET, then merged by the shared
* {@link mergeAssignees}.
*/
async function resolveAssignees(
api: GiteaClient,
@@ -714,26 +715,7 @@ async function resolveAssignees(
remove: string[],
): Promise<string[]> {
const issue = await getIssue(api, context, number);
const removeSet = new Set(remove.map((login) => login.toLowerCase()));
const seen = new Set<string>();
const result: string[] = [];
const push = (login: string): void => {
const key = login.toLowerCase();
if (removeSet.has(key) || seen.has(key)) {
return;
}
seen.add(key);
result.push(login);
};
for (const assignee of issue.assignees ?? []) {
if (assignee.login) {
push(assignee.login);
}
}
for (const login of add) {
push(login);
}
return result;
return mergeAssignees(assigneeLogins(issue.assignees), add, remove);
}
async function issueEdit(deps: CliDeps, args: string[]): Promise<string> {

View File

@@ -1,11 +1,14 @@
import type {
Comment,
CreatePullRequestOption,
EditPullRequestOption,
PullRequest,
PullReview,
PullReviewComment,
PullReviewRequestOptions,
Repository,
} from "gitea-js";
import { assigneeLogins, mergeAssignees } from "../assignees.js";
import { BODY_TRUNCATE_LIMIT, COMMENT_TRUNCATE_LIMIT, truncateBody } from "../body.js";
import { requireBodySource, resolveBodySource } from "../body-source.js";
import { createClient, type GiteaClient } from "../client.js";
@@ -47,11 +50,64 @@ commands:
view Show a single pull request's details
checks Show a pull request's CI check results
create Create a pull request
edit Edit a pull request's title, body, labels, assignees, reviewers, milestone, or base
close Close a pull request
reopen Reopen a closed pull request
comment Post a comment on a pull request
Run \`gitea-axi pr <command> --help\` for the flags of a command.
`;
export const PR_EDIT_HELP = `usage: gitea-axi pr edit <number> [flags]
Edit a pull request in the current repository. At least one change is required.
flags:
--title <text> New title
--body <text> New body
--body-file <path> Read the new body from a file (mutually exclusive with --body)
--base <branch> Change the base branch to merge into
--add-label <name> Add a label by name (repeatable)
--remove-label <name> Remove a label by name (repeatable, case-insensitive)
--add-assignee <login> Add an assignee (repeatable)
--remove-assignee <login> Remove an assignee (repeatable)
--add-reviewer <login> Request a review from a user (repeatable)
--remove-reviewer <login> Cancel a requested review (repeatable)
--milestone <name> Assign a milestone by name (case-insensitive)
--help Show this help
global flags:
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
--login <name> Select a tea login profile by name
`;
export const PR_CLOSE_HELP = `usage: gitea-axi pr close <number> [flags]
Close a pull request in the current repository. Closing an already-closed or
merged pull request is a no-op.
flags:
--comment <text> Post a comment when closing
--help Show this help
global flags:
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
--login <name> Select a tea login profile by name
`;
export const PR_REOPEN_HELP = `usage: gitea-axi pr reopen <number>
Reopen a closed pull request in the current repository. Reopening an
already-open pull request is a no-op.
flags:
--help Show this help
global flags:
-R, --repo <OWNER/NAME> Override the repository detected from the git origin remote
--login <name> Select a tea login profile by name
`;
export const PR_VIEW_HELP = `usage: gitea-axi pr view <number> [flags]
Show a single pull request, including its CI checks and review summary.
@@ -905,6 +961,258 @@ async function prComment(deps: CliDeps, args: string[]): Promise<string> {
});
}
/**
* The assignee list to PATCH: the pull request's current assignees with the
* requested additions applied and removals dropped (fetch-then-patch, ADR 0007).
* The current logins are read off a fresh GET, then merged by the shared
* {@link mergeAssignees}.
*/
async function resolvePullAssignees(
api: GiteaClient,
context: RepoContext,
number: number,
add: string[],
remove: string[],
): Promise<string[]> {
const pull = await getPull(api, context, number);
return mergeAssignees(assigneeLogins(pull.assignees), add, remove);
}
/**
* The state to report for a pull request in the close no-op: `merged` marks a
* merged pull request (whose `state` Gitea reports as `closed`), otherwise the
* raw state stands.
*/
function pullState(pull: PullRequest): string {
return pull.merged ? "merged" : (pull.state ?? "closed");
}
async function prEdit(deps: CliDeps, args: string[]): Promise<string> {
if (args.includes("--help")) {
return PR_EDIT_HELP;
}
const { flags, lists, positionals } = parseFlags(
args,
{
"--title": { takesValue: true },
"--body": { takesValue: true },
"--body-file": { takesValue: true },
"--base": { takesValue: true },
"--add-label": { takesValue: true, repeatable: true },
"--remove-label": { takesValue: true, repeatable: true },
"--add-assignee": { takesValue: true, repeatable: true },
"--remove-assignee": { takesValue: true, repeatable: true },
"--add-reviewer": { takesValue: true, repeatable: true },
"--remove-reviewer": { takesValue: true, repeatable: true },
"--milestone": { takesValue: true },
},
"pr edit",
);
const number = parsePositionalNumber(positionals, "pr edit", "pull request");
const title = flagValue(flags, "--title");
const body = resolveBodySource(deps, flags, "pr edit");
const base = flagValue(flags, "--base");
const milestoneName = flagValue(flags, "--milestone");
const addLabels = lists["--add-label"] ?? [];
const removeLabels = lists["--remove-label"] ?? [];
const addAssignees = lists["--add-assignee"] ?? [];
const removeAssignees = lists["--remove-assignee"] ?? [];
const addReviewers = lists["--add-reviewer"] ?? [];
const removeReviewers = lists["--remove-reviewer"] ?? [];
const changesAssignees = addAssignees.length > 0 || removeAssignees.length > 0;
const nothingToDo =
title === undefined &&
body === undefined &&
base === undefined &&
milestoneName === undefined &&
addLabels.length === 0 &&
removeLabels.length === 0 &&
!changesAssignees &&
addReviewers.length === 0 &&
removeReviewers.length === 0;
if (nothingToDo) {
throw axiError("pr edit requires at least one change", "VALIDATION_ERROR", [
"Run `gitea-axi pr edit --help` to see the fields you can change",
]);
}
const context = await resolveRepoContext(deps);
const api = createClient(context);
// Name resolution runs before any mutation: whether a milestone or label name
// is real does not depend on the pull request's state, so a typo is reported
// before a single change lands, never leaving the pull request half-edited.
const milestoneId =
milestoneName !== undefined ? await resolveMilestoneId(api, context, milestoneName) : undefined;
const removeLabelIds = await resolveLabelIds(api, context, removeLabels);
// Title, body, base, milestone, and the recomputed assignee list travel in one
// PATCH — the reviewers are the exception, having no field on this body.
const payload: EditPullRequestOption = {};
if (title !== undefined) {
payload.title = title;
}
if (body !== undefined) {
payload.body = body;
}
if (base !== undefined) {
payload.base = base;
}
if (milestoneId !== undefined) {
payload.milestone = milestoneId;
}
if (changesAssignees) {
payload.assignees = await resolvePullAssignees(
api,
context,
number,
addAssignees,
removeAssignees,
);
}
if (Object.keys(payload).length > 0) {
try {
await api.repos.repoEditPullRequest(context.owner, context.name, number, payload);
} catch (error) {
throw classifyHttpError(error);
}
}
// Label mutations use Gitea's dedicated endpoints (idempotent). `--add-label`
// passes names straight through — Gitea accepts them there, no lookup needed —
// while `--remove-label` resolved to ids above (mirrors `issue edit`).
if (addLabels.length > 0) {
try {
await api.repos.issueAddLabel(context.owner, context.name, number, { labels: addLabels });
} catch (error) {
throw classifyHttpError(error);
}
}
for (const id of removeLabelIds) {
try {
await api.repos.issueRemoveLabel(context.owner, context.name, number, id);
} catch (error) {
// The label exists in the repo but is not applied to this pull request:
// Gitea answers 404, and the caller's intent (label absent) already holds,
// so it is silent success rather than an error.
if (httpStatus(error) === 404) {
continue;
}
throw classifyHttpError(error);
}
}
// Reviewer mutations go through Gitea's dedicated requested-reviewers endpoints
// — `EditPullRequestOption` has no reviewers field, so fetch-then-patch is
// structurally impossible here (ADR 0007 amendment). Each direction is one call
// carrying the whole list.
if (addReviewers.length > 0) {
const options: PullReviewRequestOptions = { reviewers: addReviewers };
try {
await api.repos.repoCreatePullReviewRequests(context.owner, context.name, number, options);
} catch (error) {
throw classifyHttpError(error);
}
}
if (removeReviewers.length > 0) {
const options: PullReviewRequestOptions = { reviewers: removeReviewers };
try {
await api.repos.repoDeletePullReviewRequests(context.owner, context.name, number, options);
} catch (error) {
throw classifyHttpError(error);
}
}
// The mutation ran, so the block is named for the action, not the entity.
return renderDetail({
noun: "edited",
item: { number, status: "ok" },
help: [suggestCommand(context, `pr view ${number}`, "to see the pull request in full")],
});
}
async function prClose(deps: CliDeps, args: string[]): Promise<string> {
if (args.includes("--help")) {
return PR_CLOSE_HELP;
}
const { flags, positionals } = parseFlags(args, { "--comment": { takesValue: true } }, "pr close");
const number = parsePositionalNumber(positionals, "pr close", "pull request");
const comment = flagValue(flags, "--comment");
const context = await resolveRepoContext(deps);
const api = createClient(context);
// Read the current state first: an already-closed or merged pull request
// short-circuits to the idempotent no-op below rather than issuing a redundant
// PATCH. A merged pull request has state `closed`, so this catches both.
const pull = await getPull(api, context, number);
if (pull.state === "closed") {
return renderDetail({
noun: "pull_request",
item: { number, state: pullState(pull), already: true },
help: [suggestCommand(context, `pr reopen ${number}`, "to reopen this pull request")],
});
}
try {
await api.repos.repoEditPullRequest(context.owner, context.name, number, { state: "closed" });
} catch (error) {
throw classifyHttpError(error);
}
// The comment is a second call after the close lands. A failure here is
// surfaced, never swallowed: the pull request is closed, but the caller must
// learn that the comment they asked for did not post.
if (comment !== undefined) {
try {
await api.repos.issueCreateComment(context.owner, context.name, number, { body: comment });
} catch (error) {
throw classifyHttpError(error);
}
}
return renderDetail({
noun: "closed",
item: { number, status: "ok" },
help: [suggestCommand(context, `pr reopen ${number}`, "to reopen this pull request")],
});
}
async function prReopen(deps: CliDeps, args: string[]): Promise<string> {
if (args.includes("--help")) {
return PR_REOPEN_HELP;
}
const { positionals } = parseFlags(args, {}, "pr reopen");
const number = parsePositionalNumber(positionals, "pr reopen", "pull request");
const context = await resolveRepoContext(deps);
const api = createClient(context);
// Read the current state first: an already-open pull request short-circuits to
// the idempotent no-op below rather than issuing a redundant PATCH.
const pull = await getPull(api, context, number);
if (pull.state === "open") {
return renderDetail({
noun: "pull_request",
item: { number, state: "open", already: true },
help: [suggestCommand(context, `pr close ${number}`, "to close this pull request")],
});
}
try {
await api.repos.repoEditPullRequest(context.owner, context.name, number, { state: "open" });
} catch (error) {
throw classifyHttpError(error);
}
return renderDetail({
noun: "reopened",
item: { number, status: "ok" },
help: [suggestCommand(context, `pr view ${number}`, "to see the pull request in full")],
});
}
export function prCommand(deps: CliDeps) {
return async (args: string[]): Promise<string> => {
const [subcommand, ...rest] = args;
@@ -923,6 +1231,15 @@ export function prCommand(deps: CliDeps) {
if (subcommand === "create") {
return prCreate(deps, rest);
}
if (subcommand === "edit") {
return prEdit(deps, rest);
}
if (subcommand === "close") {
return prClose(deps, rest);
}
if (subcommand === "reopen") {
return prReopen(deps, rest);
}
if (subcommand === "comment") {
return prComment(deps, rest);
}

107
test/pr-close.test.ts Normal file
View File

@@ -0,0 +1,107 @@
import { afterEach, describe, expect, it } from "vitest";
import { startFixtureServer, type FixtureServer } from "./fixture-server.js";
import { runCliTest, testModeEnv } from "./harness.js";
const REPO_PATH = "/api/v1/repos/testowner/testrepo";
const PR_PATH = `${REPO_PATH}/pulls/9`;
const COMMENTS_PATH = `${REPO_PATH}/issues/9/comments`;
let server: FixtureServer;
afterEach(async () => {
await server.close();
});
describe("pr close", () => {
it("closes an open pull request and reports the action", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "open" } },
{ method: "PATCH", path: PR_PATH, body: { number: 9, state: "closed" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "close", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("closed:");
expect(stdout).toContain("number: 9");
expect(stdout).toContain("status: ok");
const patch = server.requests.find((request) => request.method === "PATCH");
expect(patch?.body).toEqual({ state: "closed" });
});
it("posts a --comment after the close and reports success", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "open" } },
{ method: "PATCH", path: PR_PATH, body: { number: 9, state: "closed" } },
{ method: "POST", path: COMMENTS_PATH, status: 201, body: { id: 1 } },
]);
const { exitCode } = await runCliTest(["pr", "close", "9", "--comment", "Superseded."], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
const post = server.requests.find((request) => request.method === "POST");
expect(post?.body).toEqual({ body: "Superseded." });
// The close lands before the comment.
const patchIndex = server.requests.findIndex((request) => request.method === "PATCH");
const postIndex = server.requests.findIndex((request) => request.method === "POST");
expect(patchIndex).toBeLessThan(postIndex);
});
it("surfaces a comment-post failure even though the pull request was closed", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "open" } },
{ method: "PATCH", path: PR_PATH, body: { number: 9, state: "closed" } },
{ method: "POST", path: COMMENTS_PATH, status: 403, body: { message: "forbidden" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "close", "9", "--comment", "note"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(1);
expect(stdout).toContain("code: FORBIDDEN");
// The close still happened.
expect(server.requests.some((request) => request.method === "PATCH")).toBe(true);
});
it("returns early with already: true on an already-closed pull request", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "closed" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "close", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("pull_request:");
expect(stdout).toContain("state: closed");
expect(stdout).toContain("already: true");
expect(server.requests.some((request) => request.method === "PATCH")).toBe(false);
});
it("reports a merged pull request as state: merged without patching", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "closed", merged: true } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "close", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("state: merged");
expect(stdout).toContain("already: true");
expect(server.requests.some((request) => request.method === "PATCH")).toBe(false);
});
it("prints help with --help without calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["pr", "close", "--help"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("usage: gitea-axi pr close");
expect(server.requests).toHaveLength(0);
});
});

227
test/pr-edit.test.ts Normal file
View File

@@ -0,0 +1,227 @@
import { afterEach, describe, expect, it } from "vitest";
import { startFixtureServer, type FixtureServer } from "./fixture-server.js";
import { runCliTest, tempFiles, testModeEnv } from "./harness.js";
const REPO_PATH = "/api/v1/repos/testowner/testrepo";
const PR_PATH = `${REPO_PATH}/pulls/9`;
const LABELS_ENDPOINT = `${REPO_PATH}/issues/9/labels`;
const REPO_LABELS = `${REPO_PATH}/labels`;
const MILESTONES_PATH = `${REPO_PATH}/milestones`;
const REVIEWERS_PATH = `${PR_PATH}/requested_reviewers`;
let server: FixtureServer;
const files = tempFiles();
afterEach(async () => {
await server.close();
files.cleanup();
});
/** The parsed body of the single PATCH the CLI sent to the pull request. */
function patchedPull(): Record<string, unknown> {
const patch = server.requests.find(
(request) => request.method === "PATCH" && request.path === PR_PATH,
);
expect(patch, "expected a PATCH to the pull request").toBeDefined();
return patch!.body as Record<string, unknown>;
}
function pull(fields: Record<string, unknown> = {}): Record<string, unknown> {
return { number: 9, state: "open", assignees: [], ...fields };
}
describe("pr edit", () => {
it("applies title, body, base, and milestone in one PATCH and reports the action", async () => {
server = await startFixtureServer([
{
method: "GET",
path: MILESTONES_PATH,
query: { name: "v2.0" },
body: [{ id: 8, title: "v2.0" }],
},
{ method: "PATCH", path: PR_PATH, body: pull() },
]);
const { stdout, exitCode } = await runCliTest(
[
"pr",
"edit",
"9",
"--title",
"New title",
"--body",
"New body",
"--base",
"develop",
"--milestone",
"v2.0",
],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain("edited:");
expect(stdout).toContain("number: 9");
expect(stdout).toContain("status: ok");
expect(patchedPull()).toEqual({
title: "New title",
body: "New body",
base: "develop",
milestone: 8,
});
});
it("reads the new body from --body-file", async () => {
const path = files.write("body.md", "Body from a file.\n");
server = await startFixtureServer([{ method: "PATCH", path: PR_PATH, body: pull() }]);
const { exitCode } = await runCliTest(["pr", "edit", "9", "--body-file", path], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(patchedPull()).toEqual({ body: "Body from a file.\n" });
});
it("posts --add-label names directly to the additive label endpoint", async () => {
server = await startFixtureServer([{ method: "POST", path: LABELS_ENDPOINT, body: [] }]);
const { exitCode } = await runCliTest(
["pr", "edit", "9", "--add-label", "bug", "--add-label", "chore"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
const post = server.requests.find(
(request) => request.method === "POST" && request.path === LABELS_ENDPOINT,
);
expect(post?.body).toEqual({ labels: ["bug", "chore"] });
// No label lookup happens for additions — names go straight through.
expect(server.requests.some((request) => request.path === REPO_LABELS)).toBe(false);
});
it("resolves --remove-label to an id before deleting it", async () => {
server = await startFixtureServer([
{ method: "GET", path: REPO_LABELS, body: [{ id: 22, name: "Priority: High" }] },
{ method: "DELETE", path: `${LABELS_ENDPOINT}/22`, body: {} },
]);
const { exitCode } = await runCliTest(["pr", "edit", "9", "--remove-label", "priority: high"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(
server.requests.some(
(request) => request.method === "DELETE" && request.path === `${LABELS_ENDPOINT}/22`,
),
).toBe(true);
});
it("treats a 404 removing an unapplied label as silent success", async () => {
server = await startFixtureServer([
{ method: "GET", path: REPO_LABELS, body: [{ id: 22, name: "wontfix" }] },
{ method: "DELETE", path: `${LABELS_ENDPOINT}/22`, status: 404, body: { message: "not found" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "edit", "9", "--remove-label", "wontfix"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("edited:");
expect(stdout).toContain("status: ok");
});
it("adds and removes assignees via fetch-then-patch, sending the full resulting list", async () => {
server = await startFixtureServer([
{
method: "GET",
path: PR_PATH,
body: pull({ assignees: [{ login: "alice" }, { login: "bob" }] }),
},
{ method: "PATCH", path: PR_PATH, body: pull() },
]);
const { exitCode } = await runCliTest(
["pr", "edit", "9", "--add-assignee", "carol", "--remove-assignee", "alice"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(patchedPull()).toEqual({ assignees: ["bob", "carol"] });
// Exactly one PATCH carries the whole recomputed list.
expect(server.requests.filter((request) => request.method === "PATCH")).toHaveLength(1);
});
it("requests a review via the requested-reviewers POST endpoint", async () => {
server = await startFixtureServer([{ method: "POST", path: REVIEWERS_PATH, body: [] }]);
const { exitCode } = await runCliTest(["pr", "edit", "9", "--add-reviewer", "dana"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
const post = server.requests.find(
(request) => request.method === "POST" && request.path === REVIEWERS_PATH,
);
expect(post?.body).toEqual({ reviewers: ["dana"] });
// No PATCH: reviewers do not travel on the edit body.
expect(server.requests.some((request) => request.method === "PATCH")).toBe(false);
});
it("cancels a requested review via the requested-reviewers DELETE endpoint", async () => {
server = await startFixtureServer([{ method: "DELETE", path: REVIEWERS_PATH, body: {} }]);
const { exitCode } = await runCliTest(["pr", "edit", "9", "--remove-reviewer", "dana"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
const del = server.requests.find(
(request) => request.method === "DELETE" && request.path === REVIEWERS_PATH,
);
expect(del?.body).toEqual({ reviewers: ["dana"] });
});
it("adds and removes reviewers in one POST and one DELETE", async () => {
server = await startFixtureServer([
{ method: "POST", path: REVIEWERS_PATH, body: [] },
{ method: "DELETE", path: REVIEWERS_PATH, body: {} },
]);
const { exitCode } = await runCliTest(
[
"pr",
"edit",
"9",
"--add-reviewer",
"dana",
"--add-reviewer",
"erin",
"--remove-reviewer",
"frank",
],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
const post = server.requests.find((request) => request.method === "POST");
const del = server.requests.find((request) => request.method === "DELETE");
expect(post?.body).toEqual({ reviewers: ["dana", "erin"] });
expect(del?.body).toEqual({ reviewers: ["frank"] });
});
it("rejects an edit with no changes before calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["pr", "edit", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(server.requests).toHaveLength(0);
});
it("prints help with --help without calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["pr", "edit", "--help"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("usage: gitea-axi pr edit");
expect(server.requests).toHaveLength(0);
});
});

57
test/pr-reopen.test.ts Normal file
View File

@@ -0,0 +1,57 @@
import { afterEach, describe, expect, it } from "vitest";
import { startFixtureServer, type FixtureServer } from "./fixture-server.js";
import { runCliTest, testModeEnv } from "./harness.js";
const REPO_PATH = "/api/v1/repos/testowner/testrepo";
const PR_PATH = `${REPO_PATH}/pulls/9`;
let server: FixtureServer;
afterEach(async () => {
await server.close();
});
describe("pr reopen", () => {
it("reopens a closed pull request and reports the action", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "closed" } },
{ method: "PATCH", path: PR_PATH, body: { number: 9, state: "open" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "reopen", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("reopened:");
expect(stdout).toContain("number: 9");
expect(stdout).toContain("status: ok");
const patch = server.requests.find((request) => request.method === "PATCH");
expect(patch?.body).toEqual({ state: "open" });
});
it("returns early with already: true on an already-open pull request", async () => {
server = await startFixtureServer([
{ method: "GET", path: PR_PATH, body: { number: 9, state: "open" } },
]);
const { stdout, exitCode } = await runCliTest(["pr", "reopen", "9"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("pull_request:");
expect(stdout).toContain("state: open");
expect(stdout).toContain("already: true");
expect(server.requests.some((request) => request.method === "PATCH")).toBe(false);
});
it("prints help with --help without calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["pr", "reopen", "--help"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("usage: gitea-axi pr reopen");
expect(server.requests).toHaveLength(0);
});
});