feat(cli): add pull request creation with AI-generated messages (#2)

Add a new `gai pr` subcommand that generates pull request titles and descriptions using AI, then creates the PR via GitHub CLI (`gh`) or Gitea CLI (`tea`). This extends the existing commit-generation system by reusing retry logic and prompt infrastructure, and introduces a `callAI` function that returns raw output (instead of pre-cleaned messages) to support structured PR responses.

Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
2026-06-11 00:39:20 +08:00
parent 76a5bac11a
commit 6ff541284e
5 changed files with 585 additions and 11 deletions
+288
View File
@@ -19,6 +19,20 @@ 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,
getRemoteHostname,
checkCLI,
checkAuth,
createPR,
} from "./src/pr";
import type { Platform } from "./src/pr";
import { PR_SYSTEM_PROMPT, buildPRPrompt } from "./src/prompt";
import { generatePRMessage } from "./src/ai";
const args = process.argv.slice(2);
@@ -31,6 +45,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 +293,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 +402,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 {
@@ -396,6 +415,119 @@ async function showMenu(): Promise<void> {
});
}
async function selectPlatform(hostname: string): Promise<Platform | null> {
const options = [
{ platform: "github" as Platform, label: "GitHub", desc: "gh CLI" },
{ platform: "gitea" as Platform, label: "Gitea", desc: "tea CLI" },
];
let cursor = 0;
const headerLines = 4;
process.stdout.write(`\n Remote: ${CYAN}${hostname}${RESET} — could not auto-detect platform.\n`);
process.stdout.write(` ${DIM}↑/↓ navigate, space/enter select${RESET}\n\n`);
const totalLines = headerLines + options.length;
function render() {
for (let i = 0; i < options.length; i++) {
process.stdout.write("\x1b[2K\r");
const opt = options[i]!;
const pointer = i === cursor ? `${CYAN}${RESET} ` : " ";
const dot = i === cursor ? `${GREEN}${RESET}` : `${DIM}${RESET}`;
const name = i === cursor ? `${BOLD}${opt.label}${RESET}` : opt.label;
const desc = i === cursor ? opt.desc : `${DIM}${opt.desc}${RESET}`;
process.stdout.write(`${pointer} ${dot} ${name}${" ".repeat(Math.max(1, 10 - opt.label.length))}${desc}\n`);
}
process.stdout.write(`\x1b[${options.length}A`);
}
function clearMenu() {
process.stdout.write(`\x1b[${headerLines}A`);
for (let i = 0; i < totalLines; i++) {
process.stdout.write("\r\x1b[2K\n");
}
process.stdout.write(`\x1b[${totalLines}A`);
}
if (!process.stdin.isTTY) {
console.error(` ${RED}Error: Platform selection requires a TTY.${RESET}`);
process.exit(1);
}
const savedRaw = process.stdin.isRaw;
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdout.write("\x1b[?25l");
render();
return new Promise((resolve) => {
let escapeBuf = "";
function handleSeq(seq: string) {
if (seq === "\x1b[A" || seq === "\x1bOA") {
if (cursor > 0) {
cursor--;
render();
}
} else if (seq === "\x1b[B" || seq === "\x1bOB") {
if (cursor < options.length - 1) {
cursor++;
render();
}
}
}
process.stdin.on("data", (data: Buffer) => {
const key = data.toString();
if (key === "\x03") {
process.stdin.setRawMode(savedRaw === true);
process.stdin.pause();
process.stdin.removeAllListeners("data");
clearMenu();
process.stdout.write("\x1b[?25h");
resolve(null);
return;
}
if (key === "\x1b" || key.startsWith("\x1b[")) {
escapeBuf = key;
if (key.length >= 3) {
handleSeq(key);
escapeBuf = "";
}
return;
}
if (escapeBuf) {
escapeBuf += key;
if (/^[A-Za-z~]$/.test(key)) {
handleSeq(escapeBuf);
escapeBuf = "";
} else if (escapeBuf.length > 8) {
escapeBuf = "";
}
return;
}
if (key === " " || key === "\r") {
const selected = options[cursor]!;
process.stdin.setRawMode(savedRaw === true);
process.stdin.pause();
process.stdin.removeAllListeners("data");
clearMenu();
process.stdout.write("\x1b[?25h");
resolve(selected.platform);
return;
}
});
});
}
async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
const config = await loadConfig();
@@ -517,6 +649,156 @@ 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);
}
let platform = await detectPlatform();
if (!platform) {
const hostname = (await getRemoteHostname()) || "unknown";
const chosen = await selectPlatform(hostname);
if (!chosen) {
console.log(" Aborted.");
process.exit(0);
}
platform = chosen;
}
const platformLabel = platform === "github" ? "GitHub" : "Gitea";
console.log(` Using: ${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 +829,12 @@ async function main() {
return;
}
if (subcommand === "pr") {
const draft = args.includes("--draft");
await handlePR(draft);
return;
}
if (!subcommand) {
await showMenu();
return;