feat: add REST PR edit CLI
This commit is contained in:
+97
-40
@@ -778,6 +778,10 @@ function readDisclosureOptions(options: GitHubOptions, shorthand: GitHubShorthan
|
||||
};
|
||||
}
|
||||
|
||||
function isGitHubCommandResult(value: GitHubResolvedNumberReference | GitHubCommandResult): value is GitHubCommandResult {
|
||||
return typeof (value as { ok?: unknown }).ok === "boolean";
|
||||
}
|
||||
|
||||
function unknownGhOptionDetails(args: string[], option: string): Record<string, unknown> {
|
||||
const [top, sub, third] = args;
|
||||
const details: Record<string, unknown> = {
|
||||
@@ -804,11 +808,18 @@ function readBodyFile(path: string | undefined, command: string): string {
|
||||
return readFileSync(path, "utf8");
|
||||
}
|
||||
|
||||
function readMarkdownBody(options: GitHubOptions, command: string): { body: string; bodySource: Record<string, unknown> } {
|
||||
function readMarkdownBodyFileOrStdin(path: string): { body: string; bodySource: Record<string, unknown> } {
|
||||
if (path === "-") {
|
||||
return { body: readFileSync(0, "utf8"), bodySource: { kind: "stdin", path: "-" } };
|
||||
}
|
||||
if (!existsSync(path)) throw new Error(`body file not found: ${path}`);
|
||||
return { body: readFileSync(path, "utf8"), bodySource: { kind: "body-file", path } };
|
||||
}
|
||||
|
||||
function readOptionalMarkdownBody(options: GitHubOptions, command: string): { body: string; bodySource: Record<string, unknown> } | null {
|
||||
if (options.bodyFile !== undefined && options.body !== undefined) throw new Error(`${command} accepts only one body source: --body-file or --body`);
|
||||
if (options.bodyFile !== undefined) {
|
||||
const body = readBodyFile(options.bodyFile, command);
|
||||
return { body, bodySource: { kind: "body-file", path: options.bodyFile } };
|
||||
return readMarkdownBodyFileOrStdin(options.bodyFile);
|
||||
}
|
||||
if (options.body !== undefined) {
|
||||
return {
|
||||
@@ -819,6 +830,12 @@ function readMarkdownBody(options: GitHubOptions, command: string): { body: stri
|
||||
},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readMarkdownBody(options: GitHubOptions, command: string): { body: string; bodySource: Record<string, unknown> } {
|
||||
const body = readOptionalMarkdownBody(options, command);
|
||||
if (body !== null) return body;
|
||||
throw new Error(`${command} requires --body-file <file> or --body <text>`);
|
||||
}
|
||||
|
||||
@@ -3632,6 +3649,10 @@ function compareSummary(compare: GitHubCompare): Record<string, unknown> {
|
||||
};
|
||||
}
|
||||
|
||||
function prUrl(repo: string, number: number): string {
|
||||
return `https://github.com/${repo}/pull/${number}`;
|
||||
}
|
||||
|
||||
function encodePathPart(value: string): string {
|
||||
return encodeURIComponent(value);
|
||||
}
|
||||
@@ -3729,6 +3750,17 @@ function bodyUpdatePlan(command: string, repo: string, number: number, mode: Bod
|
||||
};
|
||||
}
|
||||
|
||||
function prEditBodyPlan(mode: BodyUpdateMode, input: { body: string; bodySource: Record<string, unknown> } | null, finalBody: string | undefined, existingBody: string | null): Record<string, unknown> | null {
|
||||
if (input === null || finalBody === undefined) return null;
|
||||
return {
|
||||
mode,
|
||||
bodySource: input.bodySource,
|
||||
input: bodySafetySignals(input.body),
|
||||
existingBody: existingBody === null ? { fetched: false } : { fetched: true, bodyChars: existingBody.length, bodySha: bodySha(existingBody) },
|
||||
finalBody: bodySafetySignals(finalBody),
|
||||
};
|
||||
}
|
||||
|
||||
async function prCreate(repo: string, token: string, options: GitHubOptions): Promise<GitHubCommandResult> {
|
||||
if (options.title === undefined) return validationError("pr create", repo, "pr create requires --title <title>");
|
||||
if (options.base === undefined) return validationError("pr create", repo, "pr create requires --base <branch>");
|
||||
@@ -3854,53 +3886,75 @@ async function prComment(repo: string, token: string, issueNumber: number, optio
|
||||
};
|
||||
}
|
||||
|
||||
async function prUpdate(repo: string, token: string, number: number, options: GitHubOptions): Promise<GitHubCommandResult> {
|
||||
let bodySource: { body: string; bodySource: Record<string, unknown> };
|
||||
async function prUpdate(repo: string, token: string, number: number, options: GitHubOptions, commandName = "pr update"): Promise<GitHubCommandResult> {
|
||||
let bodySource: { body: string; bodySource: Record<string, unknown> } | null;
|
||||
try {
|
||||
bodySource = readMarkdownBody(options, "pr update");
|
||||
bodySource = readOptionalMarkdownBody(options, commandName);
|
||||
} catch (error) {
|
||||
return validationError("pr update", repo, error instanceof Error ? error.message : String(error), { number });
|
||||
return validationError(commandName, repo, error instanceof Error ? error.message : String(error), { number });
|
||||
}
|
||||
if (bodySource === null && options.title === undefined) {
|
||||
return validationError(commandName, repo, `${commandName} requires --title <title>, --body-file <file|->, or --body <text>`, { number });
|
||||
}
|
||||
if (options.mode === "append" && bodySource === null) {
|
||||
return validationError(commandName, repo, `${commandName} --mode append requires a body source`, { number });
|
||||
}
|
||||
const { owner, name } = repoParts(repo);
|
||||
let oldPr: GitHubPullRequest | null = null;
|
||||
if (token.length > 0 && (options.mode === "append" || !options.dryRun)) {
|
||||
if (token.length > 0 && options.mode === "append") {
|
||||
const pr = await githubRequest<GitHubPullRequest>(token, "GET", `/repos/${owner}/${name}/pulls/${number}`);
|
||||
if (isGitHubError(pr)) return commandError("pr update", repo, pr, { number, phase: "read-before-update" });
|
||||
if (isGitHubError(pr)) return commandError(commandName, repo, pr, { number, phase: "read-before-update" });
|
||||
oldPr = pr;
|
||||
}
|
||||
const finalBody = options.mode === "append" ? `${oldPr?.body ?? ""}${bodySource.body}` : bodySource.body;
|
||||
const planned = bodyUpdatePlan("pr update", repo, number, options.mode, bodySource.body, bodySource.bodySource, oldPr?.body ?? null);
|
||||
const finalBody = bodySource === null ? undefined : (options.mode === "append" ? `${oldPr?.body ?? ""}${bodySource.body}` : bodySource.body);
|
||||
const changedFields = [
|
||||
...(options.title === undefined ? [] : ["title"]),
|
||||
...(bodySource === null ? [] : ["body"]),
|
||||
];
|
||||
const bodyPlan = prEditBodyPlan(options.mode, bodySource, finalBody, oldPr?.body ?? null);
|
||||
const request = {
|
||||
method: "PATCH",
|
||||
path: `/repos/{owner}/{repo}/pulls/${number}`,
|
||||
changedFields,
|
||||
body: {
|
||||
...(options.title === undefined ? {} : { title: "provided" }),
|
||||
...(finalBody === undefined ? {} : { bodyChars: finalBody.length, bodySha: bodySha(finalBody) }),
|
||||
},
|
||||
};
|
||||
if (options.dryRun) {
|
||||
return {
|
||||
ok: true,
|
||||
command: "pr update",
|
||||
command: commandName,
|
||||
repo,
|
||||
dryRun: true,
|
||||
planned: true,
|
||||
number,
|
||||
title: options.title ?? null,
|
||||
...planned,
|
||||
request: {
|
||||
method: "PATCH",
|
||||
path: `/repos/{owner}/{repo}/pulls/${number}`,
|
||||
body: { title: options.title ?? null, bodyChars: finalBody.length },
|
||||
},
|
||||
url: prUrl(repo, number),
|
||||
changedFields,
|
||||
...(bodyPlan === null ? {} : { body: bodyPlan }),
|
||||
request,
|
||||
graphQl: false,
|
||||
projectsClassic: false,
|
||||
};
|
||||
}
|
||||
const payload: Record<string, unknown> = { body: finalBody };
|
||||
const payload: Record<string, unknown> = {};
|
||||
if (finalBody !== undefined) payload.body = finalBody;
|
||||
if (options.title !== undefined) payload.title = options.title;
|
||||
const pr = await githubRequest<GitHubPullRequest>(token, "PATCH", `/repos/${owner}/${name}/pulls/${number}`, payload);
|
||||
if (isGitHubError(pr)) return commandError("pr update", repo, pr, { number, planned });
|
||||
if (isGitHubError(pr)) return commandError(commandName, repo, pr, { number, planned: { changedFields, body: bodyPlan, request } });
|
||||
return {
|
||||
ok: true,
|
||||
command: "pr update",
|
||||
command: commandName,
|
||||
repo,
|
||||
number,
|
||||
mode: options.mode,
|
||||
pullRequest: prSummary(pr),
|
||||
update: planned,
|
||||
request: { method: "PATCH", path: `/repos/${owner}/${name}/pulls/${number}`, title: options.title ?? null, bodyChars: finalBody.length },
|
||||
pr: pr.number ?? number,
|
||||
number: pr.number ?? number,
|
||||
changedFields,
|
||||
url: pr.html_url ?? prUrl(repo, number),
|
||||
...(bodyPlan === null ? {} : { body: bodyPlan }),
|
||||
request: { ...request, path: `/repos/${owner}/${name}/pulls/${number}` },
|
||||
rest: true,
|
||||
graphQl: false,
|
||||
projectsClassic: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4838,7 +4892,8 @@ export function ghHelp(): unknown {
|
||||
"bun scripts/cli.ts gh pr read <number|owner/repo#number> [--repo owner/name] [--json body,title,state,head,base,draft,headRefName,baseRefName,mergeable,mergeStateStatus,statusCheckRollup] [--raw|--full]",
|
||||
"bun scripts/cli.ts gh pr view <number|owner/repo#number> [--repo owner/name] [--raw|--full] [compatibility alias for pr read]",
|
||||
"bun scripts/cli.ts gh pr create --title <title> --body-file <file>|--body <text> --base <branch> --head <branch> [--repo owner/name] [--draft] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr update <number> --mode replace|append --body-file <file>|--body <text> [--title title] [--repo owner/name] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr edit <number> [--title title] [--body-file <file>|--body-file -|--body <text>] [--repo owner/name] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr update <number> --mode replace|append [--body-file <file>|--body-file -|--body <text>] [--title title] [--repo owner/name] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr comment create <number> --body-file <file>|--body <text> [--repo owner/name] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr comment delete <commentId> [--repo owner/name] [--dry-run]",
|
||||
"bun scripts/cli.ts gh pr close|reopen <number> [--repo owner/name] [--dry-run]",
|
||||
@@ -4860,7 +4915,7 @@ export function ghHelp(): unknown {
|
||||
"issue update dry-run reports old/new body length slots, body SHA, required heading checks, literal \\n detection, and shell-pollution signals. Non-dry-run can use --expect-updated-at or --expect-body-sha for stale-cache protection.",
|
||||
"Issue body stdin is intentionally unsupported in this CLI; write generated Markdown to a file and pass --body-file.",
|
||||
"When staging a body file from a shell, use a quoted heredoc such as cat <<'EOF' > /tmp/body.md so backticks and backslashes are not expanded before --body-file reads the file.",
|
||||
"For JSON request bodies in other CLI namespaces, prefer --body-file or --body-stdin over long inline shell arguments; GitHub Markdown writes intentionally use --body-file only.",
|
||||
"For JSON request bodies in other CLI namespaces, prefer --body-file or --body-stdin over long inline shell arguments. GitHub issue Markdown writes intentionally use --body-file only; PR edit/update also accepts --body-file - for stdin when a runner already has reviewed Markdown on stdin.",
|
||||
"issue scan-escape classifies literal \\n findings as suspected-pollution, explanatory-mention, or risk, and emits cleanupSuggestions with body/comment ids plus diff-like previews. cleanup-plan is an alias that remains dry-run/read-only.",
|
||||
"issue board-audit is read-only and defaults to repo pikasTech/unidesk plus board issue #20. It reads only the board issue body, returns body size/SHA and parsed Markdown board sections, and no longer validates GitHub open/closed issue coverage against OPEN/CLOSED tables. The legacy coverage fields remain present as empty arrays/zero counts for compatibility.",
|
||||
"issue board-row list/get reuse the board-audit table parser and are read-only. board-row update changes one table cell by issue number, returns old/new row, body SHA, body guard and request plan, and defaults to dry-run unless --expect-updated-at or --expect-body-sha is supplied for the guarded PATCH. Field aliases map status and validation to the 验收状态 column, tasks to 相关 Code Queue 任务, and focus to 当前关注点.",
|
||||
@@ -4870,6 +4925,7 @@ export function ghHelp(): unknown {
|
||||
"Commander brief ClaudeQQ defaults to private target 645275593 through backend-core /api/microservices/claudeqq/proxy; UNIDESK_COMMANDER_BRIEF_CLAUDEQQ_* env vars can override target, base URL, timeout, and enabled state.",
|
||||
"comment delete is supported because GitHub supports deleting issue comments; issue/pr hard delete is unsupported and close is the lifecycle alternative.",
|
||||
"PR read is the canonical read path; view remains a compatibility alias. PR read/view accept owner/repo#number shorthand and derive --repo unless an explicit conflicting --repo is supplied, which fails structurally with suggested commands. PR read/view supports closeout fields headRefName, baseRefName, mergeable, mergeStateStatus, and statusCheckRollup; mergeability and status rollup are fetched through GitHub GraphQL only when requested or when --raw/--full requests full disclosure.",
|
||||
"PR edit/update PATCHes /repos/{owner}/{repo}/pulls/{number} through REST only, never GitHub Projects Classic GraphQL/projectCards, and returns low-noise JSON with repo, PR number, changedFields, url, and body size/SHA metadata instead of echoing the full body.",
|
||||
"PR create/update/comment are safe-write operations with dry-run planning; merge is intentionally unsupported in this phase.",
|
||||
],
|
||||
};
|
||||
@@ -4915,9 +4971,9 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult
|
||||
],
|
||||
});
|
||||
}
|
||||
if (optionWasProvided(args, "--mode") && !((top === "issue" && (sub === "update" || sub === "edit")) || (top === "pr" && sub === "update"))) {
|
||||
if (optionWasProvided(args, "--mode") && !((top === "issue" && (sub === "update" || sub === "edit")) || (top === "pr" && (sub === "update" || sub === "edit")))) {
|
||||
const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh";
|
||||
return validationError(command, options.repo, "--mode is only supported by gh issue update/edit and gh pr update");
|
||||
return validationError(command, options.repo, "--mode is only supported by gh issue update/edit and gh pr update/edit");
|
||||
}
|
||||
if ((options.allowShortBody || options.expectUpdatedAt !== undefined || options.expectBodySha !== undefined || optionWasProvided(args, "--body-profile")) && !(top === "issue" && (sub === "edit" || sub === "update" || sub === "board-row" && ["update", "add", "move", "delete", "upsert"].includes(third ?? "")))) {
|
||||
const command = [top, sub].filter((value): value is string => value !== undefined).join(" ") || "gh";
|
||||
@@ -5032,7 +5088,7 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult
|
||||
}
|
||||
if (sub === "read" || sub === "view") {
|
||||
const resolved = resolveReadViewNumberReference("issue", sub, third, options, args);
|
||||
if ("ok" in resolved && resolved.ok === false) return resolved;
|
||||
if (isGitHubCommandResult(resolved)) return resolved;
|
||||
const { token, probe } = resolveToken(true);
|
||||
const missing = authRequired(resolved.repo, `issue ${sub}`, probe);
|
||||
if (missing !== null || token === null) return missing ?? authRequired(resolved.repo, `issue ${sub}`, { present: false, source: null, ghFallbackAttempted: true });
|
||||
@@ -5093,14 +5149,15 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult
|
||||
if (typeof number !== "number") return number;
|
||||
return prComment(options.repo, token, number, options);
|
||||
}
|
||||
if (sub === "update") {
|
||||
const number = parseNumberForCommand(options.repo, third, "pr update");
|
||||
if (sub === "update" || sub === "edit") {
|
||||
const commandName = `pr ${sub}`;
|
||||
const number = parseNumberForCommand(options.repo, third, commandName);
|
||||
if (typeof number !== "number") return number;
|
||||
if (options.dryRun && options.mode === "replace") return prUpdate(options.repo, "", number, options);
|
||||
if (options.dryRun && options.mode === "replace") return prUpdate(options.repo, "", number, options, commandName);
|
||||
const { token, probe } = resolveToken(true);
|
||||
const missing = authRequired(options.repo, "pr update", probe);
|
||||
if (missing !== null || token === null) return missing ?? authRequired(options.repo, "pr update", { present: false, source: null, ghFallbackAttempted: true });
|
||||
return prUpdate(options.repo, token, number, options);
|
||||
const missing = authRequired(options.repo, commandName, probe);
|
||||
if (missing !== null || token === null) return missing ?? authRequired(options.repo, commandName, { present: false, source: null, ghFallbackAttempted: true });
|
||||
return prUpdate(options.repo, token, number, options, commandName);
|
||||
}
|
||||
if (sub === "close" || sub === "reopen") {
|
||||
const number = parseNumberForCommand(options.repo, third, `pr ${sub}`);
|
||||
@@ -5115,11 +5172,11 @@ export async function runGhCommand(args: string[]): Promise<GitHubCommandResult
|
||||
return unsupportedCommand("pr merge", options.repo, "PR merge is intentionally unsupported in this phase; use create/comment/read only.");
|
||||
}
|
||||
if (sub !== "list" && !isPrReadCommand(sub)) {
|
||||
return unsupportedCommand(`pr ${sub ?? ""}`.trim(), options.repo, "PR supported commands are list, read/view, create, update, close, reopen, comment create/delete, and unsupported merge/delete.");
|
||||
return unsupportedCommand(`pr ${sub ?? ""}`.trim(), options.repo, "PR supported commands are list, read/view, create, update/edit, close, reopen, comment create/delete, and unsupported merge/delete.");
|
||||
}
|
||||
if (sub === "read" || sub === "view") {
|
||||
const resolved = resolveReadViewNumberReference("pr", sub, third, options, args);
|
||||
if ("ok" in resolved && resolved.ok === false) return resolved;
|
||||
if (isGitHubCommandResult(resolved)) return resolved;
|
||||
const { token, probe } = resolveToken(true);
|
||||
const missing = authRequired(resolved.repo, `pr ${sub}`, probe);
|
||||
if (missing !== null || token === null) return missing ?? authRequired(resolved.repo, `pr ${sub}`, { present: false, source: null, ghFallbackAttempted: true });
|
||||
|
||||
Reference in New Issue
Block a user