10 Commits
6 changed files with 870 additions and 747 deletions
+46
View File
@@ -0,0 +1,46 @@
# AGENTS.md
## Build & Run
- **Compile**: `npm run compile` (or `tsc -p ./`)
- **Watch**: `npm run watch`
- **Package**: `npm run build` → produces `.vsix` in project root
- **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
## Architecture
| File | Role |
|---|---|
| `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 Behaviors
- **Activation**: `onCommand` only — not on startup
- **Diff logic**: Prefers staged changes. Falls back to unstaged **only if** `aiCommitExt.includeUnstaged` is `true` (default `false`).
- **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.
- **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"`.
- **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)
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ai-commit-ext", "name": "ai-commit-ext",
"version": "0.0.1", "version": "1.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ai-commit-ext", "name": "ai-commit-ext",
"version": "0.0.1", "version": "1.0.0",
"devDependencies": { "devDependencies": {
"@types/node": "^25.5.2", "@types/node": "^25.5.2",
"@types/vscode": "^1.110.0", "@types/vscode": "^1.110.0",
+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.0.0", "version": "1.2.3",
"publisher": "local", "publisher": "local",
"engines": { "engines": {
"vscode": "^1.110.0" "vscode": "^1.110.0"
+19 -5
View File
@@ -41,7 +41,11 @@ async function handleGenerateCommitMessage(): Promise<void> {
const showNotification = config.get<boolean>("showNotification", true); const showNotification = config.get<boolean>("showNotification", true);
try { try {
const opencodeAvailable = await isOpenCodeAvailable(); const [opencodeAvailable, gitExtension] = await Promise.all([
isOpenCodeAvailable(),
vscode.extensions.getExtension<GitExtension>("vscode.git"),
]);
if (!opencodeAvailable) { if (!opencodeAvailable) {
if (showNotification) { if (showNotification) {
vscode.window.showErrorMessage( vscode.window.showErrorMessage(
@@ -51,8 +55,6 @@ async function handleGenerateCommitMessage(): Promise<void> {
return; return;
} }
const gitExtension =
vscode.extensions.getExtension<GitExtension>("vscode.git");
if (!gitExtension) { if (!gitExtension) {
if (showNotification) { if (showNotification) {
vscode.window.showErrorMessage("Git extension not found"); vscode.window.showErrorMessage("Git extension not found");
@@ -86,14 +88,24 @@ async function handleGenerateCommitMessage(): Promise<void> {
return; return;
} }
const userSuggestion = await vscode.window.showInputBox({
prompt: "Suggest a commit message (optional)",
placeHolder: "e.g., added login button",
ignoreFocusOut: true,
});
if (userSuggestion === undefined) {
return;
}
const commitMessage = await vscode.window.withProgress( const commitMessage = await vscode.window.withProgress(
{ {
location: vscode.ProgressLocation.Notification, location: vscode.ProgressLocation.Notification,
cancellable: false, cancellable: false,
title: "Generating commit message...", title: userSuggestion ? "Improving commit message..." : "Generating commit message...",
}, },
async () => { async () => {
return await generateCommitMessage(); return await generateCommitMessage({ userSuggestion: userSuggestion || undefined });
}, },
); );
@@ -114,3 +126,5 @@ async function handleGenerateCommitMessage(): Promise<void> {
} }
export function deactivate(): void {} export function deactivate(): void {}
export const output = vscode.window.createOutputChannel("ai-commit-ext");
+28 -25
View File
@@ -1,4 +1,4 @@
import * as vscode from 'vscode'; import * as vscode from "vscode";
interface GitExtension { interface GitExtension {
getAPI(version: number): GitAPI; getAPI(version: number): GitAPI;
@@ -30,14 +30,14 @@ interface Change {
export interface GitChange { export interface GitChange {
path: string; path: string;
status: 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked'; status: "added" | "modified" | "deleted" | "renamed" | "untracked";
diff?: string; diff?: string;
} }
export async function getGitChanges(): Promise<GitChange[]> { export async function getGitChanges(): Promise<GitChange[]> {
const repository = await getActiveGitRepository(); const repository = await getActiveGitRepository();
if (!repository) { if (!repository) {
throw new Error('No Git repository found'); throw new Error("No Git repository found");
} }
const state = repository.state; const state = repository.state;
@@ -54,8 +54,8 @@ export async function getGitChanges(): Promise<GitChange[]> {
}); });
} }
} else if (unstagedChanges.length > 0) { } else if (unstagedChanges.length > 0) {
const config = vscode.workspace.getConfiguration('aiCommitExt'); const config = vscode.workspace.getConfiguration("aiCommitExt");
const includeUnstaged = config.get<boolean>('includeUnstaged', false); const includeUnstaged = config.get<boolean>("includeUnstaged", false);
if (includeUnstaged) { if (includeUnstaged) {
for (const change of unstagedChanges) { for (const change of unstagedChanges) {
@@ -73,58 +73,61 @@ export async function getGitChanges(): Promise<GitChange[]> {
export async function getGitDiff(): Promise<string> { export async function getGitDiff(): Promise<string> {
const repository = await getActiveGitRepository(); const repository = await getActiveGitRepository();
if (!repository) { if (!repository) {
throw new Error('No Git repository found'); throw new Error("No Git repository found");
} }
const state = repository.state; const state = repository.state;
let diffOutput = ''; let diffOutput = "";
const stagedChanges = state.indexChanges || []; const stagedChanges = state.indexChanges || [];
const unstagedChanges = state.workingTreeChanges || []; const unstagedChanges = state.workingTreeChanges || [];
const config = vscode.workspace.getConfiguration('aiCommitExt'); const config = vscode.workspace.getConfiguration("aiCommitExt");
const includeUnstaged = config.get<boolean>('includeUnstaged', false); const includeUnstaged = config.get<boolean>("includeUnstaged", false);
if (stagedChanges.length > 0) { if (stagedChanges.length > 0) {
for (const change of stagedChanges) { for (const change of stagedChanges) {
const fileName = change.uri.fsPath.split('/').pop() || ''; const fileName = change.uri.fsPath.split("/").pop() || "";
diffOutput += `## ${fileName} (staged)\n`; diffOutput += `## ${fileName} (staged)\n`;
try { try {
const diff = await repository.diffIndexWithHEAD(change.uri.fsPath); const diff = await repository.diffIndexWithHEAD(
change.uri.fsPath,
);
if (diff) { if (diff) {
diffOutput += diff + '\n'; diffOutput += diff + "\n";
} }
} catch { } catch {
diffOutput += '(Unable to get diff)\n'; diffOutput += "(Unable to get diff)\n";
} }
} }
} else if (unstagedChanges.length > 0 && includeUnstaged) { } else if (unstagedChanges.length > 0 && includeUnstaged) {
for (const change of unstagedChanges) { for (const change of unstagedChanges) {
const fileName = change.uri.fsPath.split('/').pop() || ''; const fileName = change.uri.fsPath.split("/").pop() || "";
diffOutput += `## ${fileName} (unstaged)\n`; diffOutput += `## ${fileName} (unstaged)\n`;
try { try {
const diff = await repository.diffWithHEAD(change.uri.fsPath); const diff = await repository.diffWithHEAD(change.uri.fsPath);
if (diff) { if (diff) {
diffOutput += diff + '\n'; diffOutput += diff + "\n";
} }
} catch { } catch {
diffOutput += '(Unable to get diff)\n'; diffOutput += "(Unable to get diff)\n";
} }
} }
} }
if (!diffOutput) { if (!diffOutput) {
throw new Error('No changes to commit'); throw new Error("No changes to commit");
} }
return diffOutput; return diffOutput;
} }
async function getActiveGitRepository(): Promise<Repository | null> { async function getActiveGitRepository(): Promise<Repository | null> {
const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git'); const gitExtension =
vscode.extensions.getExtension<GitExtension>("vscode.git");
if (!gitExtension) { if (!gitExtension) {
throw new Error('Git extension not found'); throw new Error("Git extension not found");
} }
const api = gitExtension.exports.getAPI(1); const api = gitExtension.exports.getAPI(1);
@@ -134,7 +137,7 @@ async function getActiveGitRepository(): Promise<Repository | null> {
return api.repositories[0]; return api.repositories[0];
} }
function getChangeStatus(status: number): GitChange['status'] { function getChangeStatus(status: number): GitChange["status"] {
const Status = { const Status = {
INDEX_MODIFIED: 0, INDEX_MODIFIED: 0,
INDEX_ADDED: 1, INDEX_ADDED: 1,
@@ -146,16 +149,16 @@ function getChangeStatus(status: number): GitChange['status'] {
}; };
if (status === Status.INDEX_ADDED || status === Status.UNTRACKED) { if (status === Status.INDEX_ADDED || status === Status.UNTRACKED) {
return 'added'; return "added";
} }
if (status === Status.INDEX_DELETED || status === Status.DELETED) { if (status === Status.INDEX_DELETED || status === Status.DELETED) {
return 'deleted'; return "deleted";
} }
if (status === Status.INDEX_RENAMED) { if (status === Status.INDEX_RENAMED) {
return 'renamed'; return "renamed";
} }
return 'modified'; return "modified";
} }
export async function getRepositoryRoot(): Promise<string | null> { export async function getRepositoryRoot(): Promise<string | null> {
@@ -163,7 +166,7 @@ export async function getRepositoryRoot(): Promise<string | null> {
if (!repository) { if (!repository) {
return null; return null;
} }
if (typeof repository.root === 'string') { if (typeof repository.root === "string") {
return repository.root; return repository.root;
} }
return repository.rootUri.fsPath; return repository.rootUri.fsPath;
+99 -39
View File
@@ -1,11 +1,15 @@
import { exec, spawn, ExecException } from "child_process"; import { exec, spawn, ExecException } from "child_process";
import * as vscode from "vscode"; import * as vscode from "vscode";
import { getGitDiff, getRepositoryRoot } from "./gitService"; import { getGitDiff, getRepositoryRoot } from "./gitService";
import { output } from "./extension";
export interface GenerateOptions { export interface GenerateOptions {
model?: string; model?: string;
userSuggestion?: string;
} }
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).
Format: <type>(<scope>): <description> Format: <type>(<scope>): <description>
@@ -15,47 +19,100 @@ 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> {
return new Promise((resolve) => { try {
exec("which opencode", (error: ExecException | null) => { await getOpenCodePath();
resolve(!error); return true;
}); } catch {
return false;
}
}
async function getOpenCodePath(): Promise<string> {
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( getGitDiff(),
"OpenCode is not installed. Please install it from https://opencode.ai", getRepositoryRoot(),
); ]);
}
const diff = await getGitDiff();
const repoRoot = await getRepositoryRoot();
const config = vscode.workspace.getConfiguration("aiCommitExt"); const config = vscode.workspace.getConfiguration("aiCommitExt");
const model = options.model || config.get<string>("model", ""); const model = options.model || config.get<string>("model", "");
const prompt = `${DEFAULT_PROMPT} let prompt: string;
if (options.userSuggestion) {
prompt = `The user suggested: "${options.userSuggestion}"
Improve this commit message to be concise and follow Conventional Commit format.
Format: <type>(<scope>): <description>
Max 72 characters for the subject line.
Types: feat, fix, refactor, docs, style, test, chore, perf, ci, build, revert
Here are the git changes:
${diff}
Only output the improved commit message, nothing else.`;
} else {
prompt = `${DEFAULT_PROMPT}
Here are the git changes: Here are the git changes:
${diff} ${diff}
Generate a concise Conventional Commit message for these changes:`; Generate a concise Conventional Commit message for these changes:`;
}
output.appendLine(`[${Date.now()}]\r\n${prompt}`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const args: string[] = ["run", "--format", "default"]; const args: string[] = [
"run",
"--format",
"default",
"--variant",
"minimal",
];
if (model) { if (model) {
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: {
...process.env,
OPENCODE_SERVER_PASSWORD: undefined,
OPENCODE_SERVER_USERNAME: undefined,
OPENCODE_CLIENT: undefined,
OPENCODE_HOST: undefined,
OPENCODE_PORT: undefined,
OPENCODE_SKIP_START: undefined,
OPENCODE_BINARY: undefined,
},
}); });
let stdout = ""; let stdout = "";
@@ -69,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();
}); });
@@ -82,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);
}); });
@@ -98,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;
} }