feat(cli): add gai pr subcommand for AI-powered pull request creation

This commit is contained in:
2026-06-11 00:24:51 +08:00
parent 76a5bac11a
commit d9b037c1fc
5 changed files with 457 additions and 11 deletions
+170
View File
@@ -19,6 +19,18 @@ import { generateCommitMessage } from "./src/ai";
import { copyToClipboard } from "./src/clipboard";
import { BOLD, GREEN, YELLOW, CYAN, RED, DIM, RESET } from "./src/terminal";
import type { Config } from "./src/types";
import {
getDefaultBranch,
getBranchName,
getBranchCommits,
getBranchDiff,
detectPlatform,
checkCLI,
checkAuth,
createPR,
} from "./src/pr";
import { PR_SYSTEM_PROMPT, buildPRPrompt } from "./src/prompt";
import { generatePRMessage } from "./src/ai";
const args = process.argv.slice(2);
@@ -31,6 +43,8 @@ ${BOLD}Usage:${RESET}
gai commit Generate commit message for staged/changed files
gai commit --auto Auto-stage all changed files
gai commit -d Generate message without committing
gai pr Create a PR with AI-generated title and body
gai pr --draft Create a draft PR
gai config Configure API settings
gai --help Show this help message
gai --version Show version
@@ -277,6 +291,7 @@ interface MenuAction {
const MENU_ACTIONS: MenuAction[] = [
{ key: "commit", label: "commit", description: "Generate AI commit message" },
{ key: "pr", label: "pr", description: "Create a PR with AI-generated title" },
{ key: "config", label: "config", description: "Configure API settings" },
];
@@ -385,6 +400,8 @@ async function showMenu(): Promise<void> {
if (selected.key === "commit") {
handleCommit(false, false).then(resolve);
} else if (selected.key === "pr") {
handlePR(false).then(resolve);
} else if (selected.key === "config") {
handleConfig().then(resolve);
} else {
@@ -517,6 +534,153 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
}
}
async function handlePR(draft: boolean): Promise<void> {
const config = await loadConfig();
if (!config.apiKey) {
console.error(
` ${RED}Error: API key not set. Run ${BOLD}gai config${RESET}${RED} to configure.${RESET}`,
);
process.exit(1);
}
if (!(await isGitRepo())) {
console.error(` ${RED}Error: Not a git repository.${RESET}`);
process.exit(1);
}
const platform = await detectPlatform();
if (!platform) {
console.error(
` ${RED}Error: Could not detect GitHub or Gitea from origin remote URL.${RESET}`,
);
process.exit(1);
}
const platformLabel = platform === "github" ? "GitHub" : "Gitea";
console.log(` Remote platform: ${CYAN}${platformLabel}${RESET}`);
const cliError = checkCLI(platform);
if (cliError) {
console.error(` ${RED}Error: ${cliError}${RESET}`);
process.exit(1);
}
const authError = await checkAuth(platform);
if (authError) {
console.error(` ${RED}Error: ${authError}${RESET}`);
process.exit(1);
}
const baseBranch = await getDefaultBranch();
const branchName = await getBranchName();
if (branchName === baseBranch) {
console.error(
` ${RED}Error: You are on the default branch (${baseBranch}). Switch to a feature branch first.${RESET}`,
);
process.exit(1);
}
console.log(
` Branch: ${CYAN}${branchName}${RESET} → base: ${CYAN}${baseBranch}${RESET}`,
);
const commits = await getBranchCommits(baseBranch);
if (commits.length === 0) {
console.error(
` ${RED}Error: No commits on ${branchName} compared to ${baseBranch}. Commit something first.${RESET}`,
);
process.exit(1);
}
console.log(
` ${commits.length} commit${commits.length > 1 ? "s" : ""} on this branch`,
);
const diff = await getBranchDiff(baseBranch);
if (!diff) {
console.error(` ${RED}Error: No diff from base branch.${RESET}`);
process.exit(1);
}
const MAX_DIFF_SIZE = 15000;
const truncatedDiff =
diff.length > MAX_DIFF_SIZE
? diff.substring(0, MAX_DIFF_SIZE) + "\n... (truncated)"
: diff;
const repoRoot = await getRepoRoot();
const projectCtx = await collectProjectContext(repoRoot);
const userPrompt = buildPRPrompt({
readme: projectCtx.readme,
packageDescription: projectCtx.packageDescription,
structure: projectCtx.structure,
branchName,
baseBranch,
branchCommits: commits,
diff: truncatedDiff,
});
console.log("\n Generating PR title...");
let title: string;
let body: string;
try {
const result = await generatePRMessage(config, PR_SYSTEM_PROMPT, userPrompt);
title = result.title;
body = result.body;
} catch (err) {
console.error(
` ${RED}AI request failed: ${err instanceof Error ? err.message : err}${RESET}`,
);
process.exit(1);
}
console.log(`\n ${BOLD}Generated PR:${RESET}`);
console.log(` Title: ${GREEN}${title}${RESET}`);
if (body) {
console.log(
` Body: ${DIM}${body.replace(/\n/g, "\n ")}${RESET}`,
);
}
console.log("");
const answer = await ask(` Create this PR? [${GREEN}Y${RESET}/n/e] `);
const lower = answer.toLowerCase();
if (lower === "n") {
console.log(" Aborted.");
return;
}
if (lower === "e") {
const newTitle = await ask(" Title: ");
const newBody = await ask(" Body (optional): ");
if (!newTitle.trim()) {
console.log(" Aborted.");
return;
}
title = newTitle;
body = newBody;
}
console.log(`\n Creating PR...`);
try {
const url = await createPR(platform, title, body, baseBranch, draft);
console.log(` ${GREEN}${BOLD}✔ PR created!${RESET}`);
console.log(` ${CYAN}${url}${RESET}`);
} catch (err) {
console.error(
` ${RED}PR creation failed: ${err instanceof Error ? err.message : err}${RESET}`,
);
process.exit(1);
}
}
async function main() {
if (args.includes("--help") || args.includes("-h")) {
showHelp();
@@ -547,6 +711,12 @@ async function main() {
return;
}
if (subcommand === "pr") {
const draft = args.includes("--draft");
await handlePR(draft);
return;
}
if (!subcommand) {
await showMenu();
return;