Compare commits
9 Commits
v0.1.0
..
e1354e8651
| Author | SHA1 | Date | |
|---|---|---|---|
| e1354e8651 | |||
| 7e662b25cc | |||
| 5bb2dc8e8a | |||
| 1dbfac7985 | |||
| c8626ff69a | |||
| 7e9cab5805 | |||
| 9885096229 | |||
| 1ea180387c | |||
| 6ff541284e |
@@ -0,0 +1,25 @@
|
|||||||
|
name: Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
bun-build:
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: bun test
|
||||||
|
|
||||||
|
- name: Build binary
|
||||||
|
run: bun run build
|
||||||
@@ -2,14 +2,14 @@
|
|||||||
|
|
||||||
# gai
|
# gai
|
||||||
|
|
||||||
**AI-powered git commit message generator**
|
**AI-powered Git commit and pull request helper**
|
||||||
|
|
||||||
[](https://github.com/mplan/git-ai)
|
[](https://git.catpl.top/Mplan/gai/releases)
|
||||||
[](./LICENSE)
|
[](./LICENSE)
|
||||||
[](https://bun.sh)
|
[](https://bun.sh)
|
||||||
[](https://www.typescriptlang.org/)
|
[](https://www.typescriptlang.org/)
|
||||||
|
|
||||||
Generate **Conventional Commits** messages using AI — based on your project context, code diff, and commit history.
|
Generate **Conventional Commits** messages and pull request descriptions using AI, based on your project context, code diff, branch changes, and commit history.
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -18,13 +18,14 @@ Generate **Conventional Commits** messages using AI — based on your project co
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Interactive menu** — `gai` opens a menu, select actions with ↑/↓ + space/enter
|
- **Interactive menu** — `gai` opens a menu, select actions with ↑/↓ + space/enter
|
||||||
- **3-layer context** — project overview, staged diff, and recent commit history
|
- **Context-aware commits** — reads project overview, staged diff, and recent commit history
|
||||||
- **Conventional Commits** — `feat(scope): description` format by default
|
- **Conventional Commits** — `feat(scope): description` format by default
|
||||||
- **Interactive file selection** — ↑/↓ to navigate, space to select, top-level "Select all"
|
- **Interactive file selection** — ↑/↓ to navigate, space to select, top-level "Select all"
|
||||||
- **Inline editing** — edit AI-generated messages right in the terminal with cursor movement
|
- **Inline editing** — edit AI-generated messages right in the terminal with cursor movement
|
||||||
- **OpenAI-compatible API** — works with DeepSeek, OpenAI, Ollama, and more
|
- **AI-generated PRs** — create GitHub, Gitea, or GitLab pull requests with generated title and body
|
||||||
|
- **OpenAI-compatible API** — works with DeepSeek, OpenAI, Ollama, OpenRouter, and more
|
||||||
- **Review before commit** — confirm, edit, or abort the generated message
|
- **Review before commit** — confirm, edit, or abort the generated message
|
||||||
- **Zero dependencies** — built entirely on Bun native APIs
|
- **Bun-native runtime** — built on Bun APIs with no runtime npm dependencies
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@@ -40,6 +41,9 @@ gai
|
|||||||
|
|
||||||
# Or directly generate a commit message
|
# Or directly generate a commit message
|
||||||
gai commit
|
gai commit
|
||||||
|
|
||||||
|
# Or create an AI-generated pull request
|
||||||
|
gai pr
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
@@ -49,6 +53,8 @@ gai Open interactive menu
|
|||||||
gai commit Generate commit message (interactive file selection)
|
gai commit Generate commit message (interactive file selection)
|
||||||
gai commit --auto Auto-stage all changed files
|
gai commit --auto Auto-stage all changed files
|
||||||
gai commit -d Generate message without committing
|
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 config Configure API settings
|
||||||
gai --help Show help
|
gai --help Show help
|
||||||
gai --version Show version
|
gai --version Show version
|
||||||
@@ -60,10 +66,12 @@ gai --version Show version
|
|||||||
$ gai
|
$ gai
|
||||||
|
|
||||||
gai
|
gai
|
||||||
|
Choose a workflow
|
||||||
|
↑/↓ navigate · enter/space select · ctrl+c cancel
|
||||||
|
|
||||||
↑/↓ navigate, space/enter select
|
❯ ● commit Generate AI commit message
|
||||||
|
○ pr Create a PR with AI-generated title
|
||||||
❯ ◉ commit Generate AI commit message
|
○ config Configure API settings
|
||||||
```
|
```
|
||||||
|
|
||||||
### Commit Flow
|
### Commit Flow
|
||||||
@@ -74,14 +82,13 @@ $ gai commit
|
|||||||
Staged files (will be included):
|
Staged files (will be included):
|
||||||
✓ src/git.ts (modified)
|
✓ src/git.ts (modified)
|
||||||
|
|
||||||
Unstaged files:
|
|
||||||
1. src/ai.ts (modified)
|
|
||||||
2. src/newfile.ts (new)
|
|
||||||
|
|
||||||
Select files to stage:
|
Select files to stage:
|
||||||
❯ ◉ Select all
|
2 unstaged files available
|
||||||
○ src/ai.ts (modified)
|
↑/↓ navigate · space toggle · enter confirm · ←/backspace back · ctrl+c cancel
|
||||||
◉ src/newfile.ts (new)
|
|
||||||
|
❯ □ Select all
|
||||||
|
□ src/ai.ts modified
|
||||||
|
■ src/newfile.ts new
|
||||||
|
|
||||||
Generating commit message...
|
Generating commit message...
|
||||||
|
|
||||||
@@ -95,6 +102,22 @@ $ gai commit
|
|||||||
1 file changed, 45 insertions(+), 12 deletions(-)
|
1 file changed, 45 insertions(+), 12 deletions(-)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Pull Request Flow
|
||||||
|
|
||||||
|
`gai pr` detects the remote platform from `origin`:
|
||||||
|
|
||||||
|
- GitHub remotes use the `gh` CLI
|
||||||
|
- Gitea remotes use the `tea` CLI
|
||||||
|
- GitLab remotes use the `glab` CLI
|
||||||
|
- Unknown remotes prompt you to choose a platform
|
||||||
|
|
||||||
|
The command compares your current branch against the default branch, pushes the branch if needed, generates a PR title/body from the branch commits and diff, then asks for confirmation before creating the PR.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gai pr
|
||||||
|
gai pr --draft
|
||||||
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
### Via `gai config` (interactive)
|
### Via `gai config` (interactive)
|
||||||
@@ -109,7 +132,7 @@ gai config
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GAI_API_KEY` | — | **Required.** Your API key |
|
| `GAI_API_KEY` | — | **Required.** Your API key |
|
||||||
| `GAI_API_BASE` | `https://api.deepseek.com/v1` | API base URL |
|
| `GAI_API_BASE` | `https://api.deepseek.com/v1` | API base URL |
|
||||||
| `GAI_MODEL` | `deepseek-chat` | Model name |
|
| `GAI_MODEL` | `deepseek-v4-flash` | Model name |
|
||||||
| `GAI_MAX_TOKENS` | `500` | Max response tokens |
|
| `GAI_MAX_TOKENS` | `500` | Max response tokens |
|
||||||
| `GAI_TEMPERATURE` | `0.7` | Sampling temperature |
|
| `GAI_TEMPERATURE` | `0.7` | Sampling temperature |
|
||||||
|
|
||||||
@@ -120,7 +143,7 @@ Bun auto-loads `.env` — no dotenv needed:
|
|||||||
```bash
|
```bash
|
||||||
GAI_API_KEY=sk-your-key
|
GAI_API_KEY=sk-your-key
|
||||||
GAI_API_BASE=https://api.deepseek.com/v1
|
GAI_API_BASE=https://api.deepseek.com/v1
|
||||||
GAI_MODEL=deepseek-chat
|
GAI_MODEL=deepseek-v4-flash
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using other providers
|
### Using other providers
|
||||||
@@ -169,14 +192,16 @@ GAI_MODEL=anthropic/claude-sonnet-4
|
|||||||
│ └─ Directory structure │
|
│ └─ Directory structure │
|
||||||
│ │
|
│ │
|
||||||
│ 2. Collect code changes │
|
│ 2. Collect code changes │
|
||||||
│ └─ git diff --staged │
|
│ ├─ git diff --staged for commits │
|
||||||
|
│ └─ branch diff for pull requests │
|
||||||
│ │
|
│ │
|
||||||
│ 3. Collect commit history │
|
│ 3. Collect commit history │
|
||||||
│ └─ git log --oneline -10 │
|
│ ├─ git log --oneline -10 for commits │
|
||||||
|
│ └─ branch commits for pull requests │
|
||||||
│ │
|
│ │
|
||||||
│ 4. Build prompt → Call AI API │
|
│ 4. Build prompt → Call AI API │
|
||||||
│ │
|
│ │
|
||||||
│ 5. Review → Confirm → Commit │
|
│ 5. Review → Confirm → Commit or Create PR │
|
||||||
└─────────────────────────────────────────────┘
|
└─────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -13,12 +13,28 @@ import {
|
|||||||
commit,
|
commit,
|
||||||
} from "./src/git";
|
} from "./src/git";
|
||||||
import { selectFiles } from "./src/selector";
|
import { selectFiles } from "./src/selector";
|
||||||
|
import { BACK, selectOne } from "./src/menu";
|
||||||
|
import type { PromptBack } from "./src/menu";
|
||||||
import { collectProjectContext } from "./src/context";
|
import { collectProjectContext } from "./src/context";
|
||||||
import { buildPrompt, SYSTEM_PROMPT } from "./src/prompt";
|
import { buildPrompt, SYSTEM_PROMPT } from "./src/prompt";
|
||||||
import { generateCommitMessage } from "./src/ai";
|
import { generateCommitMessage } from "./src/ai";
|
||||||
import { copyToClipboard } from "./src/clipboard";
|
import { copyToClipboard } from "./src/clipboard";
|
||||||
import { BOLD, GREEN, YELLOW, CYAN, RED, DIM, RESET } from "./src/terminal";
|
import { BOLD, GREEN, YELLOW, CYAN, RED, DIM, RESET } from "./src/terminal";
|
||||||
import type { Config } from "./src/types";
|
import type { Config } from "./src/types";
|
||||||
|
import {
|
||||||
|
getDefaultBranch,
|
||||||
|
getBranchName,
|
||||||
|
getBranchPushStatus,
|
||||||
|
pushCurrentBranch,
|
||||||
|
getBranchCommits,
|
||||||
|
getBranchDiff,
|
||||||
|
detectPlatform,
|
||||||
|
getRemoteHostname,
|
||||||
|
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);
|
const args = process.argv.slice(2);
|
||||||
|
|
||||||
@@ -31,6 +47,8 @@ ${BOLD}Usage:${RESET}
|
|||||||
gai commit Generate commit message for staged/changed files
|
gai commit Generate commit message for staged/changed files
|
||||||
gai commit --auto Auto-stage all changed files
|
gai commit --auto Auto-stage all changed files
|
||||||
gai commit -d Generate message without committing
|
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 config Configure API settings
|
||||||
gai --help Show this help message
|
gai --help Show this help message
|
||||||
gai --version Show version
|
gai --version Show version
|
||||||
@@ -270,133 +288,71 @@ function printCommitResult(
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MenuAction {
|
interface MenuAction {
|
||||||
key: string;
|
key: "commit" | "pr" | "config";
|
||||||
label: string;
|
label: string;
|
||||||
description: string;
|
description: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MENU_ACTIONS: MenuAction[] = [
|
const MENU_ACTIONS: MenuAction[] = [
|
||||||
{ key: "commit", label: "commit", description: "Generate AI commit message" },
|
{ 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" },
|
{ key: "config", label: "config", description: "Configure API settings" },
|
||||||
];
|
];
|
||||||
|
|
||||||
async function showMenu(): Promise<void> {
|
async function showMenu(): Promise<void> {
|
||||||
const actions = MENU_ACTIONS;
|
|
||||||
let cursor = 0;
|
|
||||||
|
|
||||||
const headerLines = 4;
|
|
||||||
|
|
||||||
process.stdout.write(`\n ${BOLD}gai${RESET}\n`);
|
|
||||||
process.stdout.write(` ${DIM}↑/↓ navigate, space/enter select${RESET}\n\n`);
|
|
||||||
|
|
||||||
const totalLines = headerLines + actions.length;
|
|
||||||
|
|
||||||
function render() {
|
|
||||||
for (let i = 0; i < actions.length; i++) {
|
|
||||||
process.stdout.write("\x1b[2K\r");
|
|
||||||
const a = actions[i]!;
|
|
||||||
const pointer = i === cursor ? `${CYAN}❯${RESET} ` : " ";
|
|
||||||
const dot = i === cursor ? `${GREEN}◉${RESET}` : `${DIM}○${RESET}`;
|
|
||||||
const name = i === cursor ? `${BOLD}${a.label}${RESET}` : a.label;
|
|
||||||
const desc = i === cursor ? a.description : `${DIM}${a.description}${RESET}`;
|
|
||||||
process.stdout.write(`${pointer} ${dot} ${name}${" ".repeat(Math.max(1, 14 - a.label.length))}${desc}\n`);
|
|
||||||
}
|
|
||||||
process.stdout.write(`\x1b[${actions.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) {
|
if (!process.stdin.isTTY) {
|
||||||
console.error(` ${RED}Error: Interactive menu requires a TTY.${RESET}`);
|
console.error(` ${RED}Error: Interactive menu requires a TTY.${RESET}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const savedRaw = process.stdin.isRaw;
|
while (true) {
|
||||||
process.stdin.setRawMode(true);
|
const selected = await selectOne({
|
||||||
process.stdin.resume();
|
title: "gai",
|
||||||
process.stdout.write("\x1b[?25l");
|
subtitle: "Choose a workflow",
|
||||||
|
allowBack: false,
|
||||||
render();
|
items: MENU_ACTIONS.map((action) => ({
|
||||||
|
label: action.label,
|
||||||
return new Promise((resolve) => {
|
value: action.key,
|
||||||
let escapeBuf = "";
|
description: action.description,
|
||||||
|
})),
|
||||||
function handleSeq(seq: string) {
|
|
||||||
if (seq === "\x1b[A" || seq === "\x1bOA") {
|
|
||||||
if (cursor > 0) {
|
|
||||||
cursor--;
|
|
||||||
render();
|
|
||||||
}
|
|
||||||
} else if (seq === "\x1b[B" || seq === "\x1bOB") {
|
|
||||||
if (cursor < actions.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();
|
|
||||||
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 = actions[cursor]!;
|
|
||||||
process.stdin.setRawMode(savedRaw === true);
|
|
||||||
process.stdin.pause();
|
|
||||||
process.stdin.removeAllListeners("data");
|
|
||||||
|
|
||||||
clearMenu();
|
|
||||||
process.stdout.write("\x1b[?25h");
|
|
||||||
|
|
||||||
if (selected.key === "commit") {
|
|
||||||
handleCommit(false, false).then(resolve);
|
|
||||||
} else if (selected.key === "config") {
|
|
||||||
handleConfig().then(resolve);
|
|
||||||
} else {
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (selected === null || selected === BACK) return;
|
||||||
|
|
||||||
|
const result =
|
||||||
|
selected === "commit"
|
||||||
|
? await handleCommit(false, false)
|
||||||
|
: selected === "pr"
|
||||||
|
? await handlePR(false)
|
||||||
|
: await handleConfig().then(() => "done" as const);
|
||||||
|
|
||||||
|
if (result !== "back") return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectPlatform(
|
||||||
|
hostname: string,
|
||||||
|
): Promise<Platform | null | PromptBack> {
|
||||||
|
if (!process.stdin.isTTY) {
|
||||||
|
console.error(` ${RED}Error: Platform selection requires a TTY.${RESET}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectOne({
|
||||||
|
title: "Select remote platform",
|
||||||
|
subtitle: `Remote ${hostname} could not be auto-detected`,
|
||||||
|
items: [
|
||||||
|
{ label: "GitHub", value: "github" as Platform, description: "Use gh CLI" },
|
||||||
|
{ label: "Gitea", value: "gitea" as Platform, description: "Use tea CLI" },
|
||||||
|
{ label: "GitLab", value: "gitlab" as Platform, description: "Use glab CLI" },
|
||||||
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
async function handleCommit(
|
||||||
|
autoMode: boolean,
|
||||||
|
dryRun: boolean,
|
||||||
|
): Promise<"done" | "back"> {
|
||||||
const config = await loadConfig();
|
const config = await loadConfig();
|
||||||
|
|
||||||
if (!config.apiKey) {
|
if (!config.apiKey) {
|
||||||
@@ -416,7 +372,7 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
|||||||
|
|
||||||
if (stagedFiles.length === 0 && unstagedFiles.length === 0) {
|
if (stagedFiles.length === 0 && unstagedFiles.length === 0) {
|
||||||
console.log(" Nothing to commit.");
|
console.log(" Nothing to commit.");
|
||||||
return;
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (unstagedFiles.length > 0) {
|
if (unstagedFiles.length > 0) {
|
||||||
@@ -427,6 +383,7 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
|||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
const selected = await selectFiles(stagedFiles, unstagedFiles);
|
const selected = await selectFiles(stagedFiles, unstagedFiles);
|
||||||
|
if (selected === BACK) return "back";
|
||||||
if (selected.length > 0) {
|
if (selected.length > 0) {
|
||||||
await stageFiles(selected);
|
await stageFiles(selected);
|
||||||
console.log(
|
console.log(
|
||||||
@@ -439,7 +396,7 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
|||||||
const diff = await getStagedDiff();
|
const diff = await getStagedDiff();
|
||||||
if (!diff) {
|
if (!diff) {
|
||||||
console.log(" No staged changes to commit.");
|
console.log(" No staged changes to commit.");
|
||||||
return;
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_DIFF_SIZE = 15000;
|
const MAX_DIFF_SIZE = 15000;
|
||||||
@@ -477,7 +434,7 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
|||||||
console.log(` ${GREEN}${message}${RESET}`);
|
console.log(` ${GREEN}${message}${RESET}`);
|
||||||
await copyToClipboard(message);
|
await copyToClipboard(message);
|
||||||
console.log(`\n ${DIM}(dry-run, message copied to clipboard)${RESET}`);
|
console.log(`\n ${DIM}(dry-run, message copied to clipboard)${RESET}`);
|
||||||
return;
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
const action = await confirmCommit(message);
|
const action = await confirmCommit(message);
|
||||||
@@ -515,6 +472,174 @@ async function handleCommit(autoMode: boolean, dryRun: boolean): Promise<void> {
|
|||||||
: ` Aborted. Message: ${message}`,
|
: ` Aborted. Message: ${message}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handlePR(draft: boolean): Promise<"done" | "back"> {
|
||||||
|
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 === BACK) return "back";
|
||||||
|
if (!chosen) {
|
||||||
|
console.log(" Aborted.");
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
platform = chosen;
|
||||||
|
}
|
||||||
|
|
||||||
|
const platformLabel =
|
||||||
|
platform === "github" ? "GitHub" : platform === "gitlab" ? "GitLab" : "Gitea";
|
||||||
|
console.log(` Using: ${CYAN}${platformLabel}${RESET}`);
|
||||||
|
|
||||||
|
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 pushStatus = await getBranchPushStatus();
|
||||||
|
if (!pushStatus.pushed) {
|
||||||
|
const target = pushStatus.upstream ?? `origin/${branchName}`;
|
||||||
|
const answer = await ask(
|
||||||
|
` Branch is not pushed to ${CYAN}${target}${RESET}. Push now? [${GREEN}Y${RESET}/n] `,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (answer.toLowerCase() === "n") {
|
||||||
|
console.log(" Aborted.");
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(` Pushing ${CYAN}${branchName}${RESET}...`);
|
||||||
|
try {
|
||||||
|
await pushCurrentBranch(branchName, pushStatus.upstream);
|
||||||
|
console.log(` ${GREEN}Pushed ${branchName}.${RESET}`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(
|
||||||
|
` ${RED}Push failed: ${err instanceof Error ? err.message : err}${RESET}`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 "done";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lower === "e") {
|
||||||
|
const newTitle = await ask(" Title: ");
|
||||||
|
const newBody = await ask(" Body (optional): ");
|
||||||
|
if (!newTitle.trim()) {
|
||||||
|
console.log(" Aborted.");
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
@@ -547,6 +672,12 @@ async function main() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (subcommand === "pr") {
|
||||||
|
const draft = args.includes("--draft");
|
||||||
|
await handlePR(draft);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!subcommand) {
|
if (!subcommand) {
|
||||||
await showMenu();
|
await showMenu();
|
||||||
return;
|
return;
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "gai",
|
"name": "gai",
|
||||||
"version": "0.1.0",
|
"version": "0.1.2",
|
||||||
"description": "AI-powered git commit message generator",
|
"description": "AI-powered git commit message generator",
|
||||||
"module": "index.ts",
|
"module": "index.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -39,11 +39,10 @@ async function sleep(ms: number) {
|
|||||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateCommitMessage(
|
export async function callAI(
|
||||||
config: Config,
|
config: Config,
|
||||||
systemPrompt: string,
|
systemPrompt: string,
|
||||||
userPrompt: string,
|
userPrompt: string,
|
||||||
retries = MAX_RETRIES,
|
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const url = `${config.apiBase.replace(/\/$/, "")}/chat/completions`;
|
const url = `${config.apiBase.replace(/\/$/, "")}/chat/completions`;
|
||||||
|
|
||||||
@@ -52,7 +51,7 @@ export async function generateCommitMessage(
|
|||||||
{ role: "user", content: userPrompt },
|
{ role: "user", content: userPrompt },
|
||||||
];
|
];
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -70,7 +69,7 @@ export async function generateCommitMessage(
|
|||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
if (response.status === 429 && attempt < retries) {
|
if (response.status === 429 && attempt < MAX_RETRIES) {
|
||||||
await sleep(RETRY_DELAY * attempt);
|
await sleep(RETRY_DELAY * attempt);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -89,7 +88,7 @@ export async function generateCommitMessage(
|
|||||||
const finishReason = data.choices?.[0]?.finish_reason;
|
const finishReason = data.choices?.[0]?.finish_reason;
|
||||||
|
|
||||||
if (raw && raw.trim()) {
|
if (raw && raw.trim()) {
|
||||||
return cleanMessage(raw);
|
return raw;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (finishReason === "length") {
|
if (finishReason === "length") {
|
||||||
@@ -102,22 +101,53 @@ export async function generateCommitMessage(
|
|||||||
throw new Error("Response blocked by content filter.");
|
throw new Error("Response blocked by content filter.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (attempt < retries) {
|
if (attempt < MAX_RETRIES) {
|
||||||
await sleep(RETRY_DELAY * attempt);
|
await sleep(RETRY_DELAY * attempt);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Empty response from AI after ${retries} attempts. finish_reason: ${finishReason ?? "unknown"}`,
|
`Empty response from AI after ${MAX_RETRIES} attempts. finish_reason: ${finishReason ?? "unknown"}`,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (attempt >= retries) throw err;
|
if (attempt >= MAX_RETRIES) throw err;
|
||||||
if (err instanceof Error && err.message.startsWith("API error")) throw err;
|
if (err instanceof Error && err.message.startsWith("API error")) throw err;
|
||||||
if (err instanceof Error && err.message.includes("max_tokens")) throw err;
|
if (err instanceof Error && err.message.includes("max_tokens")) throw err;
|
||||||
if (err instanceof Error && err.message.includes("content filter")) throw err;
|
if (err instanceof Error && err.message.includes("content filter"))
|
||||||
|
throw err;
|
||||||
await sleep(RETRY_DELAY * attempt);
|
await sleep(RETRY_DELAY * attempt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error("Failed to generate commit message");
|
throw new Error("Failed to generate response");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateCommitMessage(
|
||||||
|
config: Config,
|
||||||
|
systemPrompt: string,
|
||||||
|
userPrompt: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const raw = await callAI(config, systemPrompt, userPrompt);
|
||||||
|
return cleanMessage(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generatePRMessage(
|
||||||
|
config: Config,
|
||||||
|
systemPrompt: string,
|
||||||
|
userPrompt: string,
|
||||||
|
): Promise<{ title: string; body: string }> {
|
||||||
|
const raw = await callAI(config, systemPrompt, userPrompt);
|
||||||
|
const cleaned = cleanMessage(raw);
|
||||||
|
|
||||||
|
const lines = cleaned.split("\n");
|
||||||
|
const title = lines[0]?.trim() || "Update";
|
||||||
|
let bodyStart = 1;
|
||||||
|
|
||||||
|
while (bodyStart < lines.length && lines[bodyStart]?.trim() === "") {
|
||||||
|
bodyStart++;
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = lines.slice(bodyStart).join("\n").trim();
|
||||||
|
|
||||||
|
return { title, body };
|
||||||
}
|
}
|
||||||
|
|||||||
+328
@@ -0,0 +1,328 @@
|
|||||||
|
import { BOLD, GREEN, CYAN, DIM, RESET } from "./terminal";
|
||||||
|
|
||||||
|
const UP = "\x1b[A";
|
||||||
|
const DOWN = "\x1b[B";
|
||||||
|
const LEFT = "\x1b[D";
|
||||||
|
const ALT_UP = "\x1bOA";
|
||||||
|
const ALT_DOWN = "\x1bOB";
|
||||||
|
const ALT_LEFT = "\x1bOD";
|
||||||
|
const SPACE = " ";
|
||||||
|
const ENTER = "\r";
|
||||||
|
const CTRL_C = "\x03";
|
||||||
|
const BACKSPACE = "\x7f";
|
||||||
|
|
||||||
|
export const BACK = Symbol("prompt-back");
|
||||||
|
export type PromptBack = typeof BACK;
|
||||||
|
|
||||||
|
export interface Choice<T> {
|
||||||
|
label: string;
|
||||||
|
value: T;
|
||||||
|
description?: string;
|
||||||
|
selected?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BasePromptOptions {
|
||||||
|
title: string;
|
||||||
|
subtitle?: string;
|
||||||
|
cancelMessage?: string;
|
||||||
|
allowBack?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SinglePromptOptions<T> extends BasePromptOptions {
|
||||||
|
items: Choice<T>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MultiPromptOptions<T> extends BasePromptOptions {
|
||||||
|
items: Choice<T>[];
|
||||||
|
selectAllLabel?: string;
|
||||||
|
doneLabel?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideCursor() {
|
||||||
|
process.stdout.write("\x1b[?25l");
|
||||||
|
}
|
||||||
|
|
||||||
|
function showCursor() {
|
||||||
|
process.stdout.write("\x1b[?25h");
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveUp(lines: number) {
|
||||||
|
if (lines > 0) process.stdout.write(`\x1b[${lines}A`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearLine() {
|
||||||
|
process.stdout.write("\r\x1b[2K");
|
||||||
|
}
|
||||||
|
|
||||||
|
function visibleLength(value: string) {
|
||||||
|
return value.replace(/\x1b\[[0-9;]*m/g, "").length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function padLabel(label: string, width: number) {
|
||||||
|
return label + " ".repeat(Math.max(1, width - visibleLength(label)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function controls(mode: "single" | "multi", showBackHint = true) {
|
||||||
|
if (mode === "single") {
|
||||||
|
const backHint = showBackHint ? " · ←/backspace back" : "";
|
||||||
|
return `${DIM}↑/↓ navigate · enter/space select${backHint} · ctrl+c cancel${RESET}`;
|
||||||
|
}
|
||||||
|
const backHint = showBackHint ? " · ←/backspace back" : "";
|
||||||
|
return `${DIM}↑/↓ navigate · space toggle · enter confirm${backHint} · ctrl+c cancel${RESET}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPrompt(lines: string[], previousLines: number) {
|
||||||
|
if (previousLines > 0) {
|
||||||
|
for (let i = 0; i < previousLines; i++) {
|
||||||
|
clearLine();
|
||||||
|
process.stdout.write("\n");
|
||||||
|
}
|
||||||
|
moveUp(previousLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
process.stdout.write(`${line}\n`);
|
||||||
|
}
|
||||||
|
moveUp(lines.length);
|
||||||
|
return lines.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearPrompt(lines: number) {
|
||||||
|
for (let i = 0; i < lines; i++) {
|
||||||
|
clearLine();
|
||||||
|
process.stdout.write("\n");
|
||||||
|
}
|
||||||
|
moveUp(lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeKey(key: string, escapeBuf: string) {
|
||||||
|
if (key === UP || key === ALT_UP) return { action: "up", escapeBuf: "" };
|
||||||
|
if (key === DOWN || key === ALT_DOWN) return { action: "down", escapeBuf: "" };
|
||||||
|
if (key === LEFT || key === ALT_LEFT || key === BACKSPACE) {
|
||||||
|
return { action: "back", escapeBuf: "" };
|
||||||
|
}
|
||||||
|
if (key === SPACE) return { action: "space", escapeBuf: "" };
|
||||||
|
if (key === ENTER) return { action: "enter", escapeBuf: "" };
|
||||||
|
if (key === CTRL_C) return { action: "cancel", escapeBuf: "" };
|
||||||
|
|
||||||
|
if (key === "\x1b" || key.startsWith("\x1b[")) {
|
||||||
|
return { action: null, escapeBuf: key };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (escapeBuf) {
|
||||||
|
const next = escapeBuf + key;
|
||||||
|
if (next === UP || next === ALT_UP) return { action: "up", escapeBuf: "" };
|
||||||
|
if (next === DOWN || next === ALT_DOWN) return { action: "down", escapeBuf: "" };
|
||||||
|
if (next === LEFT || next === ALT_LEFT) {
|
||||||
|
return { action: "back", escapeBuf: "" };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
action: null,
|
||||||
|
escapeBuf: /^[A-Za-z~]$/.test(key) || next.length > 8 ? "" : next,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { action: null, escapeBuf: "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createLines<T>(
|
||||||
|
options: BasePromptOptions & { items: Choice<T>[] },
|
||||||
|
mode: "single" | "multi",
|
||||||
|
cursor: number,
|
||||||
|
) {
|
||||||
|
const labelWidth = Math.max(
|
||||||
|
...options.items.map((item) => visibleLength(item.label)),
|
||||||
|
0,
|
||||||
|
) + 2;
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
"",
|
||||||
|
` ${BOLD}${options.title}${RESET}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (options.subtitle) lines.push(` ${DIM}${options.subtitle}${RESET}`);
|
||||||
|
lines.push(` ${controls(mode, options.allowBack !== false)}`, "");
|
||||||
|
|
||||||
|
for (let i = 0; i < options.items.length; i++) {
|
||||||
|
const item = options.items[i]!;
|
||||||
|
const active = i === cursor;
|
||||||
|
const pointer = active ? `${CYAN}❯${RESET}` : " ";
|
||||||
|
const marker = mode === "single"
|
||||||
|
? active ? `${GREEN}●${RESET}` : `${DIM}○${RESET}`
|
||||||
|
: item.selected ? `${GREEN}◼${RESET}` : `${DIM}□${RESET}`;
|
||||||
|
const label = active ? `${BOLD}${item.label}${RESET}` : item.label;
|
||||||
|
const description = item.description
|
||||||
|
? active ? item.description : `${DIM}${item.description}${RESET}`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
` ${pointer} ${marker} ${padLabel(label, labelWidth)}${description}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureTTY(title: string) {
|
||||||
|
if (process.stdin.isTTY !== true) {
|
||||||
|
throw new Error(`${title} requires a TTY.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function selectOne<T>(
|
||||||
|
options: SinglePromptOptions<T>,
|
||||||
|
): Promise<T | null | PromptBack> {
|
||||||
|
ensureTTY(options.title);
|
||||||
|
|
||||||
|
let cursor = 0;
|
||||||
|
let renderedLines = 0;
|
||||||
|
let escapeBuf = "";
|
||||||
|
const wasRaw = process.stdin.isRaw;
|
||||||
|
|
||||||
|
if (wasRaw !== true) process.stdin.setRawMode(true);
|
||||||
|
process.stdin.resume();
|
||||||
|
hideCursor();
|
||||||
|
|
||||||
|
const render = () => {
|
||||||
|
renderedLines = renderPrompt(
|
||||||
|
createLines(options, "single", cursor),
|
||||||
|
renderedLines,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
render();
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const finish = (value: T | null | PromptBack) => {
|
||||||
|
process.stdin.setRawMode(wasRaw === true);
|
||||||
|
process.stdin.pause();
|
||||||
|
process.stdin.removeListener("data", onData);
|
||||||
|
clearPrompt(renderedLines);
|
||||||
|
showCursor();
|
||||||
|
if (value === null && options.cancelMessage) {
|
||||||
|
process.stdout.write(` ${options.cancelMessage}\n`);
|
||||||
|
}
|
||||||
|
resolve(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onData = (data: Buffer) => {
|
||||||
|
const result = normalizeKey(data.toString(), escapeBuf);
|
||||||
|
escapeBuf = result.escapeBuf;
|
||||||
|
|
||||||
|
if (result.action === "cancel") return finish(null);
|
||||||
|
if (result.action === "back" && options.allowBack !== false) {
|
||||||
|
return finish(BACK);
|
||||||
|
}
|
||||||
|
if (result.action === "up" && cursor > 0) {
|
||||||
|
cursor--;
|
||||||
|
render();
|
||||||
|
} else if (result.action === "down" && cursor < options.items.length - 1) {
|
||||||
|
cursor++;
|
||||||
|
render();
|
||||||
|
} else if (result.action === "space" || result.action === "enter") {
|
||||||
|
finish(options.items[cursor]!.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
process.stdin.on("data", onData);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function selectMany<T>(
|
||||||
|
options: MultiPromptOptions<T>,
|
||||||
|
): Promise<T[] | null | PromptBack> {
|
||||||
|
ensureTTY(options.title);
|
||||||
|
|
||||||
|
const items: Choice<T | null>[] = options.selectAllLabel
|
||||||
|
? [
|
||||||
|
{ label: options.selectAllLabel, value: null, selected: false },
|
||||||
|
...options.items.map((item) => ({ ...item })),
|
||||||
|
]
|
||||||
|
: options.items.map((item) => ({ ...item }));
|
||||||
|
|
||||||
|
let cursor = 0;
|
||||||
|
let renderedLines = 0;
|
||||||
|
let escapeBuf = "";
|
||||||
|
const wasRaw = process.stdin.isRaw;
|
||||||
|
|
||||||
|
if (wasRaw !== true) process.stdin.setRawMode(true);
|
||||||
|
process.stdin.resume();
|
||||||
|
hideCursor();
|
||||||
|
|
||||||
|
const syncSelectAll = () => {
|
||||||
|
if (!options.selectAllLabel) return;
|
||||||
|
items[0]!.selected = items.slice(1).every((item) => item.selected);
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggle = (index: number) => {
|
||||||
|
const item = items[index]!;
|
||||||
|
item.selected = !item.selected;
|
||||||
|
|
||||||
|
if (options.selectAllLabel && index === 0) {
|
||||||
|
for (let i = 1; i < items.length; i++) {
|
||||||
|
items[i]!.selected = item.selected;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
syncSelectAll();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const render = () => {
|
||||||
|
renderedLines = renderPrompt(
|
||||||
|
createLines(
|
||||||
|
{
|
||||||
|
title: options.title,
|
||||||
|
subtitle: options.subtitle,
|
||||||
|
items,
|
||||||
|
},
|
||||||
|
"multi",
|
||||||
|
cursor,
|
||||||
|
),
|
||||||
|
renderedLines,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
render();
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const finish = (value: T[] | null | PromptBack) => {
|
||||||
|
process.stdin.setRawMode(wasRaw === true);
|
||||||
|
process.stdin.pause();
|
||||||
|
process.stdin.removeListener("data", onData);
|
||||||
|
clearPrompt(renderedLines);
|
||||||
|
showCursor();
|
||||||
|
if (value === null && options.cancelMessage) {
|
||||||
|
process.stdout.write(` ${options.cancelMessage}\n`);
|
||||||
|
}
|
||||||
|
resolve(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onData = (data: Buffer) => {
|
||||||
|
const result = normalizeKey(data.toString(), escapeBuf);
|
||||||
|
escapeBuf = result.escapeBuf;
|
||||||
|
|
||||||
|
if (result.action === "cancel") return finish(null);
|
||||||
|
if (result.action === "back" && options.allowBack !== false) {
|
||||||
|
return finish(BACK);
|
||||||
|
}
|
||||||
|
if (result.action === "up" && cursor > 0) {
|
||||||
|
cursor--;
|
||||||
|
render();
|
||||||
|
} else if (result.action === "down" && cursor < items.length - 1) {
|
||||||
|
cursor++;
|
||||||
|
render();
|
||||||
|
} else if (result.action === "space") {
|
||||||
|
toggle(cursor);
|
||||||
|
render();
|
||||||
|
} else if (result.action === "enter") {
|
||||||
|
finish(
|
||||||
|
items
|
||||||
|
.filter((item) => item.selected && item.value !== null)
|
||||||
|
.map((item) => item.value as T),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
process.stdin.on("data", onData);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
export type Platform = "github" | "gitea" | "gitlab";
|
||||||
|
|
||||||
|
export async function getDefaultBranch(): Promise<string> {
|
||||||
|
try {
|
||||||
|
const result =
|
||||||
|
await Bun.$`git symbolic-ref refs/remotes/origin/HEAD`.quiet().text();
|
||||||
|
return result.trim().replace("refs/remotes/origin/", "");
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
const branches = await Bun.$`git branch -r`.quiet().text();
|
||||||
|
for (const line of branches.split("\n")) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (trimmed === "origin/main" || trimmed === "origin/master") {
|
||||||
|
return trimmed.replace("origin/", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
return "main";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBranchName(): Promise<string> {
|
||||||
|
const result =
|
||||||
|
await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet().text();
|
||||||
|
return result.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBranchPushStatus(): Promise<{
|
||||||
|
pushed: boolean;
|
||||||
|
upstream: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const upstream = (await Bun.$`git rev-parse --abbrev-ref --symbolic-full-name @{u}`.quiet().text()).trim();
|
||||||
|
const localHead = (await Bun.$`git rev-parse HEAD`.quiet().text()).trim();
|
||||||
|
const remoteHead = (await Bun.$`git rev-parse @{u}`.quiet().text()).trim();
|
||||||
|
return { pushed: localHead === remoteHead, upstream };
|
||||||
|
} catch {
|
||||||
|
return { pushed: false, upstream: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pushCurrentBranch(branch: string, upstream: string | null): Promise<void> {
|
||||||
|
const args = upstream
|
||||||
|
? ["push"]
|
||||||
|
: ["push", "-u", "origin", branch];
|
||||||
|
|
||||||
|
const proc = Bun.spawn(["git", ...args], {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
});
|
||||||
|
const exitCode = await proc.exited;
|
||||||
|
const stdout = await new Response(proc.stdout).text();
|
||||||
|
const stderr = await new Response(proc.stderr).text();
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
throw new Error(stderr.trim() || stdout.trim() || `git push failed (exit code ${exitCode})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBranchCommits(base: string): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const result =
|
||||||
|
await Bun.$`git log --oneline origin/${base}..HEAD`.quiet().text();
|
||||||
|
return result.trim().split("\n").filter(Boolean);
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
const result =
|
||||||
|
await Bun.$`git log --oneline ${base}..HEAD`.quiet().text();
|
||||||
|
return result.trim().split("\n").filter(Boolean);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBranchDiff(base: string): Promise<string> {
|
||||||
|
try {
|
||||||
|
const result =
|
||||||
|
await Bun.$`git diff ${base}...HEAD`.quiet().text();
|
||||||
|
return result.trim();
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRemoteHostname(url: string): string | null {
|
||||||
|
const hostname = url
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/^(https?:\/\/|ssh:\/\/|git:\/\/)/, "")
|
||||||
|
.replace(/^[^@]+@/, "")
|
||||||
|
.split(/[:/]/)[0];
|
||||||
|
return hostname || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectPlatformFromHostname(hostname: string | null): Platform | null {
|
||||||
|
if (!hostname) return null;
|
||||||
|
|
||||||
|
if (hostname === "github.com") return "github";
|
||||||
|
if (hostname === "gitlab.com" || hostname.includes("gitlab")) {
|
||||||
|
return "gitlab";
|
||||||
|
}
|
||||||
|
if (hostname.includes("gitea")) return "gitea";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function detectPlatform(): Promise<Platform | null> {
|
||||||
|
try {
|
||||||
|
const url = await Bun.$`git remote get-url origin`.quiet().text();
|
||||||
|
const hostname = parseRemoteHostname(url);
|
||||||
|
|
||||||
|
return detectPlatformFromHostname(hostname);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRemoteHostname(): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const url = await Bun.$`git remote get-url origin`.quiet().text();
|
||||||
|
return parseRemoteHostname(url);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPR(
|
||||||
|
platform: Platform,
|
||||||
|
title: string,
|
||||||
|
body: string,
|
||||||
|
base: string,
|
||||||
|
draft: boolean,
|
||||||
|
): Promise<string> {
|
||||||
|
if (platform === "github") {
|
||||||
|
const args = [
|
||||||
|
"pr",
|
||||||
|
"create",
|
||||||
|
"--title",
|
||||||
|
title,
|
||||||
|
"--body",
|
||||||
|
body,
|
||||||
|
"--base",
|
||||||
|
base,
|
||||||
|
];
|
||||||
|
if (draft) args.push("--draft");
|
||||||
|
|
||||||
|
const proc = Bun.spawn(["gh", ...args], {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
});
|
||||||
|
const exitCode = await proc.exited;
|
||||||
|
const stdout = await new Response(proc.stdout).text();
|
||||||
|
const stderr = await new Response(proc.stderr).text();
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
stderr.trim() || `gh pr create failed (exit code ${exitCode})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = stdout.match(/(https?:\/\/[^\s]+)/);
|
||||||
|
return match?.[1] ?? stdout.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === "gitlab") {
|
||||||
|
const args = [
|
||||||
|
"mr",
|
||||||
|
"create",
|
||||||
|
"--title",
|
||||||
|
title,
|
||||||
|
"--description",
|
||||||
|
body,
|
||||||
|
"--target-branch",
|
||||||
|
base,
|
||||||
|
];
|
||||||
|
if (draft) args.push("--draft");
|
||||||
|
|
||||||
|
const proc = Bun.spawn(["glab", ...args], {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
});
|
||||||
|
const exitCode = await proc.exited;
|
||||||
|
const stdout = await new Response(proc.stdout).text();
|
||||||
|
const stderr = await new Response(proc.stderr).text();
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
stderr.trim() || `glab mr create failed (exit code ${exitCode})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = stdout.match(/(https?:\/\/[^\s]+)/);
|
||||||
|
return match?.[1] ?? stdout.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const args = [
|
||||||
|
"pulls",
|
||||||
|
"create",
|
||||||
|
"--title",
|
||||||
|
title,
|
||||||
|
"--description",
|
||||||
|
body,
|
||||||
|
"--base",
|
||||||
|
base,
|
||||||
|
];
|
||||||
|
|
||||||
|
const proc = Bun.spawn(["tea", ...args], {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
});
|
||||||
|
const exitCode = await proc.exited;
|
||||||
|
const stdout = await new Response(proc.stdout).text();
|
||||||
|
const stderr = await new Response(proc.stderr).text();
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
stderr.trim() || `tea pulls create failed (exit code ${exitCode})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = stdout.match(/(https?:\/\/[^\s]+)/);
|
||||||
|
return match?.[1] ?? stdout.trim();
|
||||||
|
}
|
||||||
+63
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { ProjectContext } from "./types";
|
import type { PRContext, ProjectContext } from "./types";
|
||||||
|
|
||||||
export const SYSTEM_PROMPT = `You are an expert at writing concise, meaningful git commit messages following the Conventional Commits specification.
|
export const SYSTEM_PROMPT = `You are an expert at writing concise, meaningful git commit messages following the Conventional Commits specification.
|
||||||
|
|
||||||
@@ -54,3 +54,65 @@ export function buildPrompt(context: ProjectContext): string {
|
|||||||
|
|
||||||
return parts.join("\n");
|
return parts.join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const PR_SYSTEM_PROMPT = `You are an expert at writing clear, concise pull request titles and descriptions.
|
||||||
|
|
||||||
|
Format:
|
||||||
|
<pr title>
|
||||||
|
<blank line>
|
||||||
|
<pr body>
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
1. Title must be under 72 characters, in imperative mood
|
||||||
|
2. Follow the Conventional Commits style for the title (e.g., "feat(api): add user authentication")
|
||||||
|
3. Body should be 2-3 sentences in plain text explaining WHAT was changed and WHY
|
||||||
|
4. Be specific — avoid vague messages
|
||||||
|
5. Match the language and style of recent commits if provided
|
||||||
|
6. If the branch name hints at the type (e.g., "feat/..." or "fix/..."), reflect that in the title
|
||||||
|
7. Output ONLY the PR text — no markdown, no code blocks, no prefixes`;
|
||||||
|
|
||||||
|
export function buildPRPrompt(context: PRContext): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
|
||||||
|
if (
|
||||||
|
context.packageDescription ||
|
||||||
|
context.readme ||
|
||||||
|
context.structure
|
||||||
|
) {
|
||||||
|
parts.push("## Project Context");
|
||||||
|
if (context.packageDescription) {
|
||||||
|
parts.push(`Description: ${context.packageDescription}`);
|
||||||
|
}
|
||||||
|
if (context.structure) {
|
||||||
|
parts.push(`Structure: ${context.structure}`);
|
||||||
|
}
|
||||||
|
if (context.readme) {
|
||||||
|
parts.push(`README:\n${context.readme}`);
|
||||||
|
}
|
||||||
|
parts.push("");
|
||||||
|
}
|
||||||
|
|
||||||
|
parts.push("## Branch Info");
|
||||||
|
parts.push(`Branch: ${context.branchName}`);
|
||||||
|
parts.push(`Target base: ${context.baseBranch}`);
|
||||||
|
parts.push("");
|
||||||
|
|
||||||
|
if (context.branchCommits.length > 0) {
|
||||||
|
parts.push("## Commits on This Branch");
|
||||||
|
for (const c of context.branchCommits) {
|
||||||
|
parts.push(c);
|
||||||
|
}
|
||||||
|
parts.push("");
|
||||||
|
}
|
||||||
|
|
||||||
|
parts.push("## Changes (diff from base)");
|
||||||
|
parts.push("```diff");
|
||||||
|
parts.push(context.diff);
|
||||||
|
parts.push("```");
|
||||||
|
parts.push("");
|
||||||
|
parts.push(
|
||||||
|
"Generate a pull request title and brief body for the above changes.",
|
||||||
|
);
|
||||||
|
|
||||||
|
return parts.join("\n");
|
||||||
|
}
|
||||||
|
|||||||
+19
-144
@@ -1,42 +1,12 @@
|
|||||||
import type { FileEntry } from "./types";
|
import type { FileEntry } from "./types";
|
||||||
import { BOLD, GREEN, YELLOW, CYAN, DIM, RESET } from "./terminal";
|
import { BOLD, GREEN, YELLOW, RESET } from "./terminal";
|
||||||
|
import { BACK, selectMany } from "./menu";
|
||||||
const UP = "\x1b[A";
|
import type { PromptBack } from "./menu";
|
||||||
const DOWN = "\x1b[B";
|
|
||||||
const SPACE = " ";
|
|
||||||
const ENTER = "\r";
|
|
||||||
const CTRL_C = "\x03";
|
|
||||||
|
|
||||||
function hideCursor() {
|
|
||||||
process.stdout.write("\x1b[?25l");
|
|
||||||
}
|
|
||||||
|
|
||||||
function showCursor() {
|
|
||||||
process.stdout.write("\x1b[?25h");
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveUp(n: number) {
|
|
||||||
process.stdout.write(`\x1b[${n}A`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveDown(n: number) {
|
|
||||||
process.stdout.write(`\x1b[${n}B`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearLine() {
|
|
||||||
process.stdout.write("\x1b[2K\r");
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SelectItem {
|
|
||||||
label: string;
|
|
||||||
path: string;
|
|
||||||
selected: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function selectFiles(
|
export async function selectFiles(
|
||||||
stagedFiles: FileEntry[],
|
stagedFiles: FileEntry[],
|
||||||
unstagedFiles: FileEntry[],
|
unstagedFiles: FileEntry[],
|
||||||
): Promise<string[]> {
|
): Promise<string[] | PromptBack> {
|
||||||
if (unstagedFiles.length === 0) return [];
|
if (unstagedFiles.length === 0) return [];
|
||||||
|
|
||||||
if (stagedFiles.length > 0) {
|
if (stagedFiles.length > 0) {
|
||||||
@@ -46,111 +16,22 @@ export async function selectFiles(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const items: SelectItem[] = [
|
if (process.stdin.isTTY !== true) return [];
|
||||||
{ label: "Select all", path: "__all__", selected: false },
|
|
||||||
...unstagedFiles.map((f) => ({
|
const selected = await selectMany({
|
||||||
label: `${f.path} (${f.label})`,
|
title: "Select files to stage",
|
||||||
path: f.path,
|
subtitle: `${unstagedFiles.length} unstaged file${unstagedFiles.length > 1 ? "s" : ""} available`,
|
||||||
selected: false,
|
selectAllLabel: "Select all",
|
||||||
|
cancelMessage: "Aborted.",
|
||||||
|
items: unstagedFiles.map((f) => ({
|
||||||
|
label: f.path,
|
||||||
|
value: f.path,
|
||||||
|
description: f.label,
|
||||||
})),
|
})),
|
||||||
];
|
});
|
||||||
|
|
||||||
let cursor = 0;
|
if (selected === null) process.exit(1);
|
||||||
|
if (selected === BACK) return BACK;
|
||||||
process.stdout.write(`\n ${BOLD}Select files to stage:${RESET}\n`);
|
|
||||||
process.stdout.write(` ${DIM}↑/↓ navigate, space select, enter confirm${RESET}\n\n`);
|
|
||||||
|
|
||||||
const itemStartRow = 4 + (stagedFiles.length > 0 ? stagedFiles.length + 2 : 0);
|
|
||||||
|
|
||||||
function render() {
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
|
||||||
process.stdout.write("\x1b[2K\r");
|
|
||||||
const item = items[i]!;
|
|
||||||
const isAll = i === 0;
|
|
||||||
const cursor_ = i === cursor ? `${CYAN}❯${RESET} ` : " ";
|
|
||||||
const checkbox = item.selected ? `${GREEN}◉${RESET}` : `${DIM}○${RESET}`;
|
|
||||||
|
|
||||||
if (isAll) {
|
|
||||||
process.stdout.write(`${cursor_} ${checkbox} ${BOLD}${item.label}${RESET}\n`);
|
|
||||||
} else {
|
|
||||||
process.stdout.write(`${cursor_} ${checkbox} ${item.path.includes("(") ? item.label : `${item.label}`}\n`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
moveUp(items.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleItem(index: number) {
|
|
||||||
const item = items[index]!;
|
|
||||||
item.selected = !item.selected;
|
|
||||||
|
|
||||||
if (index === 0) {
|
|
||||||
for (let i = 1; i < items.length; i++) {
|
|
||||||
items[i]!.selected = item.selected;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const allSelected = items.slice(1).every((it) => it.selected);
|
|
||||||
items[0]!.selected = allSelected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
if (process.stdin.isTTY !== true) {
|
|
||||||
resolve([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const wasRaw = process.stdin.isRaw;
|
|
||||||
if (wasRaw !== true) {
|
|
||||||
process.stdin.setRawMode(true);
|
|
||||||
}
|
|
||||||
process.stdin.resume();
|
|
||||||
hideCursor();
|
|
||||||
|
|
||||||
render();
|
|
||||||
|
|
||||||
const onData = (data: Buffer) => {
|
|
||||||
const key = data.toString();
|
|
||||||
|
|
||||||
if (key === CTRL_C) {
|
|
||||||
process.stdin.setRawMode(wasRaw === true);
|
|
||||||
process.stdin.pause();
|
|
||||||
process.stdin.removeListener("data", onData);
|
|
||||||
showCursor();
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
|
||||||
process.stdout.write("\x1b[2K\n");
|
|
||||||
}
|
|
||||||
moveUp(items.length);
|
|
||||||
process.stdout.write(`\n Aborted.\n`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === UP) {
|
|
||||||
if (cursor > 0) {
|
|
||||||
cursor--;
|
|
||||||
render();
|
|
||||||
}
|
|
||||||
} else if (key === DOWN) {
|
|
||||||
if (cursor < items.length - 1) {
|
|
||||||
cursor++;
|
|
||||||
render();
|
|
||||||
}
|
|
||||||
} else if (key === SPACE) {
|
|
||||||
toggleItem(cursor);
|
|
||||||
render();
|
|
||||||
} else if (key === ENTER) {
|
|
||||||
process.stdin.setRawMode(wasRaw === true);
|
|
||||||
process.stdin.pause();
|
|
||||||
process.stdin.removeListener("data", onData);
|
|
||||||
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
|
||||||
process.stdout.write("\x1b[2K\n");
|
|
||||||
}
|
|
||||||
moveUp(items.length);
|
|
||||||
|
|
||||||
const selected = items
|
|
||||||
.slice(1)
|
|
||||||
.filter((it) => it.selected)
|
|
||||||
.map((it) => it.path);
|
|
||||||
|
|
||||||
if (selected.length > 0) {
|
if (selected.length > 0) {
|
||||||
process.stdout.write(
|
process.stdout.write(
|
||||||
@@ -158,11 +39,5 @@ export async function selectFiles(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
showCursor();
|
return selected;
|
||||||
resolve(selected);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
process.stdin.on("data", onData);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,3 +19,13 @@ export interface ProjectContext {
|
|||||||
recentCommits: string[];
|
recentCommits: string[];
|
||||||
diff: string;
|
diff: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PRContext {
|
||||||
|
readme: string | null;
|
||||||
|
packageDescription: string | null;
|
||||||
|
structure: string | null;
|
||||||
|
branchName: string;
|
||||||
|
baseBranch: string;
|
||||||
|
branchCommits: string[];
|
||||||
|
diff: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { test, expect, describe } from "bun:test";
|
||||||
|
import { detectPlatformFromHostname } from "../src/pr";
|
||||||
|
|
||||||
|
describe("pr platform detection", () => {
|
||||||
|
test("detects supported hosted platforms", () => {
|
||||||
|
expect(detectPlatformFromHostname("github.com")).toBe("github");
|
||||||
|
expect(detectPlatformFromHostname("gitlab.com")).toBe("gitlab");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("detects self-hosted platform hostnames", () => {
|
||||||
|
expect(detectPlatformFromHostname("gitlab.example.com")).toBe("gitlab");
|
||||||
|
expect(detectPlatformFromHostname("gitea.example.com")).toBe("gitea");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns null for unknown hostnames", () => {
|
||||||
|
expect(detectPlatformFromHostname("git.example.com")).toBeNull();
|
||||||
|
expect(detectPlatformFromHostname(null)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user