1 Commits
3 changed files with 95 additions and 58 deletions
+36 -12
View File
@@ -4,19 +4,43 @@
- **Compile**: `npm run compile` (or `tsc -p ./`) - **Compile**: `npm run compile` (or `tsc -p ./`)
- **Watch**: `npm run watch` - **Watch**: `npm run watch`
- **Package extension**: `npm run build` → produces `.vsix` file - **Package**: `npm run build` → produces `.vsix` in project root
- **Test**: Press F5 to launch extension in debug mode - **Test**: `npm run test` — currently a no-op (`echo "No tests yet"`); press F5 in VS Code to debug the extension
- **Verify**: `npx tsc --noEmit` — strict mode, TS 6.0 (uses `ignoreDeprecations: "6.0"`)
- No linter or formatter is configured
## Project Structure ## Architecture
- `src/extension.ts` - Extension entry point, registers `aiCommitExt.generate` command | File | Role |
- `src/opencodeService.ts` - Spawns `opencode run` CLI, parses output for commit message |---|---|
- `src/gitService.ts` - Uses VS Code Git extension API to get diffs and repo root | `src/extension.ts` | Entrypoint; registers `aiCommitExt.generate` command; orchestrates flow |
| `src/opencodeService.ts` | Spawns `opencode run --format default --variant minimal` with the prompt on stdin; parses stdout for the commit message |
| `src/gitService.ts` | Uses VS Code's built-in Git extension API (`vscode.git`) for diffs and repo root |
## Key Details ## Key Behaviors
- Output compiled to `out/` directory - **Activation**: `onCommand` only — not on startup
- Extension activates only on command invocation (not on startup) - **Diff logic**: Prefers staged changes. Falls back to unstaged **only if** `aiCommitExt.includeUnstaged` is `true` (default `false`).
- OpenCode CLI is required on PATH; checked via `which opencode` - **Prompt**: Hardcoded in `opencodeService.ts` — enforces Conventional Commit format (`<type>(<scope>): <description>`, max 72-char subject). Types: feat, fix, refactor, docs, style, test, chore, perf, ci, build, revert.
- Generated message written to SCM input box via `repository.inputBox.value` - **Parsing**: Uses `\b(type)(\(scope\))?:\s` regex that matches anywhere in a line (not just line-start), so backtick-wrapped or prose-embedded commit messages are found. ANSI escape sequences are stripped before matching. Falls back to first content line, then `"chore: generated commit message"`.
- Timeout: 120 seconds for OpenCode response - **Stdout is logged** to the output channel ("ai-commit-ext") for debugging.
- **`--pure` flag**: Not used — opencode loads its user config (`~/.config/opencode/opencode.json`) which needs to configure the model. The extension does NOT pass a hardcoded `--model` flag; the user's config determines the model.
- **`shell: true`**: Spawn uses a shell so opencode can find `git` and other tools via the shell's PATH (VS Code's GUI-launched process has a minimal PATH).
- **Timeout**: 120 seconds for OpenCode response.
- **Model**: Default is whatever opencode's user config sets. Override via `aiCommitExt.model` setting or `GenerateOptions.model`.
- **OpenCode CLI**: Required on `$PATH`; resolved to an absolute path via `which opencode` and cached — used in `spawn()` to avoid PATH lookup mismatches between the shell and VS Code's process environment.
## Configuration (`aiCommitExt.*`)
| Setting | Default | Purpose |
|---|---|---|
| `model` | `""` | OpenCode model override |
| `includeUnstaged` | `false` | Use unstaged changes when nothing staged |
| `showNotification` | `true` | Show VS Code notifications on success/error |
## Build Artifacts & Cleanup
- Compiled output → `out/` (gitignored)
- Packaged extension → `*.vsix` (gitignored)
- `node_modules/` (gitignored)
- `npm run compile` before packaging (`vscode:prepublish` hook)
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "ai-commit-ext", "name": "ai-commit-ext",
"displayName": "AI Commit Ext", "displayName": "AI Commit Ext",
"description": "Generate commit messages using OpenCode AI", "description": "Generate commit messages using OpenCode AI",
"version": "1.2.2", "version": "1.2.3",
"publisher": "local", "publisher": "local",
"engines": { "engines": {
"vscode": "^1.110.0" "vscode": "^1.110.0"
+58 -45
View File
@@ -8,7 +8,7 @@ export interface GenerateOptions {
userSuggestion?: string; userSuggestion?: string;
} }
let opencodeAvailableCache: boolean | null = null; let opencodePathCache: string | null = null;
const DEFAULT_PROMPT = `You are a helpful assistant that generates git commit messages. const DEFAULT_PROMPT = `You are a helpful assistant that generates git commit messages.
Generate a concise Conventional Commit message (max 72 characters for the subject line). Generate a concise Conventional Commit message (max 72 characters for the subject line).
@@ -19,28 +19,42 @@ Types: feat, fix, refactor, docs, style, test, chore, perf, ci, build, revert
Only output the commit message, nothing else.`; Only output the commit message, nothing else.`;
export async function isOpenCodeAvailable(): Promise<boolean> { export async function isOpenCodeAvailable(): Promise<boolean> {
if (opencodeAvailableCache !== null) { try {
return opencodeAvailableCache; await getOpenCodePath();
return true;
} catch {
return false;
} }
return new Promise((resolve) => { }
exec("which opencode", (error: ExecException | null) => {
opencodeAvailableCache = !error; async function getOpenCodePath(): Promise<string> {
resolve(opencodeAvailableCache); if (opencodePathCache !== null) {
}); return opencodePathCache;
}
return new Promise((resolve, reject) => {
exec(
"which opencode",
(error: ExecException | null, stdout: string) => {
if (error) {
reject(
new Error(
"OpenCode not found. Please install from https://opencode.ai",
),
);
} else {
opencodePathCache = stdout.trim();
resolve(opencodePathCache);
}
},
);
}); });
} }
export async function generateCommitMessage( export async function generateCommitMessage(
options: GenerateOptions = {}, options: GenerateOptions = {},
): Promise<string> { ): Promise<string> {
const opencodeAvailable = await isOpenCodeAvailable(); const [opencodePath, diff, repoRoot] = await Promise.all([
if (!opencodeAvailable) { getOpenCodePath(),
throw new Error(
"OpenCode is not installed. Please install it from https://opencode.ai",
);
}
const [diff, repoRoot] = await Promise.all([
getGitDiff(), getGitDiff(),
getRepositoryRoot(), getRepositoryRoot(),
]); ]);
@@ -70,17 +84,13 @@ ${diff}
Generate a concise Conventional Commit message for these changes:`; Generate a concise Conventional Commit message for these changes:`;
} }
const log = `[${Date.now()}]\r\n${prompt}`; output.appendLine(`[${Date.now()}]\r\n${prompt}`);
output.appendLine(log);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const args: string[] = [ const args: string[] = [
"run", "run",
"--pure",
"--format", "--format",
"default", "default",
"-m",
"opencode/deepseek-v4-flash-free",
"--variant", "--variant",
"minimal", "minimal",
]; ];
@@ -89,9 +99,9 @@ Generate a concise Conventional Commit message for these changes:`;
args.push("--model", model); args.push("--model", model);
} }
const proc = spawn("opencode", args, { const proc = spawn(opencodePath, args, {
stdio: ["pipe", "pipe", "pipe"], stdio: ["pipe", "pipe", "pipe"],
shell: false, shell: true,
cwd: repoRoot || undefined, cwd: repoRoot || undefined,
env: { env: {
...process.env, ...process.env,
@@ -116,7 +126,8 @@ Generate a concise Conventional Commit message for these changes:`;
}); });
proc.stdin?.write(prompt + "\n", (err) => { proc.stdin?.write(prompt + "\n", (err) => {
if (err) { if (err) {
new Error(`OpenCode write error with ${err}`); reject(new Error(`OpenCode write error with ${err}`));
return;
} }
proc.stdin?.end(); proc.stdin?.end();
}); });
@@ -129,6 +140,7 @@ Generate a concise Conventional Commit message for these changes:`;
return; return;
} }
output.appendLine(stdout);
const message = parseCommitMessage(stdout); const message = parseCommitMessage(stdout);
resolve(message); resolve(message);
}); });
@@ -145,31 +157,32 @@ Generate a concise Conventional Commit message for these changes:`;
} }
function parseCommitMessage(output: string): string { function parseCommitMessage(output: string): string {
const lines = output.split("\n").filter((line) => line.trim()); const clean = output.replace(/\x1b\[[0-9;]*m/g, "");
const lines = clean.split("\n").filter((line) => line.trim());
const ccTypes = [
"feat",
"fix",
"refactor",
"docs",
"style",
"test",
"chore",
"perf",
"ci",
"build",
"revert",
];
const pat = new RegExp(`\\b(${ccTypes.join("|")})(\\([^)]*\\))?:\\s`);
for (const line of lines) { for (const line of lines) {
const trimmed = line.trim(); const trimmed = line.trim();
const m = trimmed.match(pat);
if ( if (m) {
trimmed.includes(":") && return trimmed.substring(m.index!).substring(0, 200);
(trimmed.startsWith("feat") ||
trimmed.startsWith("fix") ||
trimmed.startsWith("refactor") ||
trimmed.startsWith("docs") ||
trimmed.startsWith("style") ||
trimmed.startsWith("test") ||
trimmed.startsWith("chore") ||
trimmed.startsWith("perf") ||
trimmed.startsWith("ci") ||
trimmed.startsWith("build") ||
trimmed.startsWith("revert"))
) {
return trimmed.substring(0, 200);
} }
} }
const cleaned = return lines[0]?.substring(0, 200) || "chore: generated commit message";
output.trim().split("\n")[0]?.substring(0, 200) ||
"chore: generated commit message";
return cleaned;
} }