Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88bc27be40 | ||
|
|
019dfa96a0 | ||
|
|
645421e59c | ||
|
|
d51ae3a574 | ||
|
|
0c2c35ad72 |
@@ -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)
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ai-commit-ext",
|
"name": "ai-commit-ext",
|
||||||
"version": "1.0.0",
|
"version": "1.3.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ai-commit-ext",
|
"name": "ai-commit-ext",
|
||||||
"version": "1.0.0",
|
"version": "1.3.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
@@ -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.1",
|
"version": "1.4.0",
|
||||||
"publisher": "local",
|
"publisher": "local",
|
||||||
"engines": {
|
"engines": {
|
||||||
"vscode": "^1.110.0"
|
"vscode": "^1.110.0"
|
||||||
|
|||||||
+83
-47
@@ -1,50 +1,32 @@
|
|||||||
import * as vscode from "vscode";
|
import * as vscode from "vscode";
|
||||||
import { generateCommitMessage, isOpenCodeAvailable } from "./opencodeService";
|
import { generateCommitMessage, isOpenCodeAvailable } from "./opencodeService";
|
||||||
|
import {
|
||||||
interface GitExtension {
|
Repository,
|
||||||
getAPI(version: number): GitAPI;
|
getAllRepositories,
|
||||||
}
|
getRepositoryLabel,
|
||||||
|
getRepositoryRoot,
|
||||||
interface GitAPI {
|
} from "./gitService";
|
||||||
repositories: Repository[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Repository {
|
|
||||||
root: string;
|
|
||||||
rootUri: vscode.Uri;
|
|
||||||
state: RepositoryState;
|
|
||||||
inputBox: { value: string };
|
|
||||||
diffIndexWithHEAD(path?: string): Promise<string>;
|
|
||||||
diffWithHEAD(path?: string): Promise<string>;
|
|
||||||
status(): Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RepositoryState {
|
|
||||||
indexChanges: any[];
|
|
||||||
workingTreeChanges: any[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function activate(
|
export async function activate(
|
||||||
context: vscode.ExtensionContext,
|
context: vscode.ExtensionContext,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const commandHandler = vscode.commands.registerCommand(
|
const commandHandler = vscode.commands.registerCommand(
|
||||||
"aiCommitExt.generate",
|
"aiCommitExt.generate",
|
||||||
async () => {
|
async (sc?: vscode.SourceControl) => {
|
||||||
await handleGenerateCommitMessage();
|
await handleGenerateCommitMessage(sc);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
context.subscriptions.push(commandHandler);
|
context.subscriptions.push(commandHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleGenerateCommitMessage(): Promise<void> {
|
async function handleGenerateCommitMessage(
|
||||||
|
sc?: vscode.SourceControl,
|
||||||
|
): Promise<void> {
|
||||||
const config = vscode.workspace.getConfiguration("aiCommitExt");
|
const config = vscode.workspace.getConfiguration("aiCommitExt");
|
||||||
const showNotification = config.get<boolean>("showNotification", true);
|
const showNotification = config.get<boolean>("showNotification", true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [opencodeAvailable, gitExtension] = await Promise.all([
|
const opencodeAvailable = await isOpenCodeAvailable();
|
||||||
isOpenCodeAvailable(),
|
|
||||||
vscode.extensions.getExtension<GitExtension>("vscode.git"),
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (!opencodeAvailable) {
|
if (!opencodeAvailable) {
|
||||||
if (showNotification) {
|
if (showNotification) {
|
||||||
@@ -55,25 +37,15 @@ async function handleGenerateCommitMessage(): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!gitExtension) {
|
const repository = await resolveRepository(sc);
|
||||||
if (showNotification) {
|
|
||||||
vscode.window.showErrorMessage("Git extension not found");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const gitApi = gitExtension.exports.getAPI(1);
|
if (!repository) {
|
||||||
const repositories = gitApi.repositories;
|
|
||||||
|
|
||||||
if (repositories.length === 0) {
|
|
||||||
if (showNotification) {
|
if (showNotification) {
|
||||||
vscode.window.showErrorMessage("No Git repository found");
|
vscode.window.showErrorMessage("No Git repository found");
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const repository = repositories[0];
|
|
||||||
|
|
||||||
await repository.status();
|
await repository.status();
|
||||||
|
|
||||||
const state = repository.state;
|
const state = repository.state;
|
||||||
@@ -98,21 +70,31 @@ async function handleGenerateCommitMessage(): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const repoLabel = getRepositoryLabel(repository);
|
||||||
|
|
||||||
const commitMessage = await vscode.window.withProgress(
|
const commitMessage = await vscode.window.withProgress(
|
||||||
{
|
{
|
||||||
location: vscode.ProgressLocation.Notification,
|
location: vscode.ProgressLocation.Notification,
|
||||||
cancellable: false,
|
cancellable: true,
|
||||||
title: userSuggestion ? "Improving commit message..." : "Generating commit message...",
|
title: userSuggestion
|
||||||
|
? `Improving commit message (${repoLabel})...`
|
||||||
|
: `Generating commit message (${repoLabel})...`,
|
||||||
},
|
},
|
||||||
async () => {
|
async (_progress, token) => {
|
||||||
return await generateCommitMessage({ userSuggestion: userSuggestion || undefined });
|
return await generateCommitMessage({
|
||||||
|
repository,
|
||||||
|
userSuggestion: userSuggestion || undefined,
|
||||||
|
cancellationToken: token,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
repository.inputBox.value = commitMessage;
|
repository.inputBox.value = commitMessage;
|
||||||
|
|
||||||
if (showNotification) {
|
if (showNotification) {
|
||||||
vscode.window.showInformationMessage("Commit message generated");
|
vscode.window.showInformationMessage(
|
||||||
|
`Commit message generated for ${repoLabel}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message =
|
const message =
|
||||||
@@ -125,6 +107,60 @@ async function handleGenerateCommitMessage(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resolveRepository(
|
||||||
|
sc?: vscode.SourceControl,
|
||||||
|
): Promise<Repository | undefined> {
|
||||||
|
const repositories = getAllRepositories();
|
||||||
|
|
||||||
|
if (repositories.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sc) {
|
||||||
|
output.appendLine(`[resolveRepository] sc provided, sc.rootUri=${sc.rootUri?.fsPath}`);
|
||||||
|
for (const r of repositories) {
|
||||||
|
const rRoot = getRepositoryRoot(r);
|
||||||
|
const match = r.inputBox === sc.inputBox;
|
||||||
|
output.appendLine(`[resolveRepository] repo root=${rRoot}, inputBox match=${match}, sc.inputBox===r.inputBox=${sc.inputBox === r.inputBox}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const byInputBox = repositories.find((r) => r.inputBox === sc.inputBox);
|
||||||
|
if (byInputBox) {
|
||||||
|
output.appendLine(`[resolveRepository] matched by inputBox`);
|
||||||
|
return byInputBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sc.rootUri) {
|
||||||
|
const byRootUri = repositories.find((r) => {
|
||||||
|
const rRoot = getRepositoryRoot(r);
|
||||||
|
return rRoot === sc.rootUri!.fsPath;
|
||||||
|
});
|
||||||
|
if (byRootUri) {
|
||||||
|
output.appendLine(`[resolveRepository] matched by rootUri`);
|
||||||
|
return byRootUri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output.appendLine(`[resolveRepository] no match found for sc`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (repositories.length === 1) {
|
||||||
|
return repositories[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = repositories.map((repo) => ({
|
||||||
|
label: getRepositoryLabel(repo),
|
||||||
|
description: getRepositoryRoot(repo),
|
||||||
|
repository: repo,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const selected = await vscode.window.showQuickPick(items, {
|
||||||
|
placeHolder: "Select a repository to generate a commit message for",
|
||||||
|
});
|
||||||
|
|
||||||
|
return selected?.repository;
|
||||||
|
}
|
||||||
|
|
||||||
export function deactivate(): void {}
|
export function deactivate(): void {}
|
||||||
|
|
||||||
export const output = vscode.window.createOutputChannel("ai-commit-ext");
|
export const output = vscode.window.createOutputChannel("ai-commit-ext");
|
||||||
|
|||||||
+44
-32
@@ -1,24 +1,24 @@
|
|||||||
import * as vscode from "vscode";
|
import * as vscode from "vscode";
|
||||||
|
|
||||||
interface GitExtension {
|
export interface GitExtension {
|
||||||
getAPI(version: number): GitAPI;
|
getAPI(version: number): GitAPI;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GitAPI {
|
export interface GitAPI {
|
||||||
repositories: Repository[];
|
repositories: Repository[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Repository {
|
export interface Repository {
|
||||||
root: string;
|
root: string;
|
||||||
rootUri: vscode.Uri;
|
rootUri: vscode.Uri;
|
||||||
state: RepositoryState;
|
state: RepositoryState;
|
||||||
inputBox: { value: string };
|
inputBox: { value: string };
|
||||||
diffWithHEAD(path?: string): Promise<string>;
|
|
||||||
diffIndexWithHEAD(path?: string): Promise<string>;
|
diffIndexWithHEAD(path?: string): Promise<string>;
|
||||||
|
diffWithHEAD(path?: string): Promise<string>;
|
||||||
status(): Promise<void>;
|
status(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RepositoryState {
|
export interface RepositoryState {
|
||||||
indexChanges: Change[];
|
indexChanges: Change[];
|
||||||
workingTreeChanges: Change[];
|
workingTreeChanges: Change[];
|
||||||
}
|
}
|
||||||
@@ -34,12 +34,9 @@ export interface GitChange {
|
|||||||
diff?: string;
|
diff?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getGitChanges(): Promise<GitChange[]> {
|
export async function getGitChanges(
|
||||||
const repository = await getActiveGitRepository();
|
repository: Repository,
|
||||||
if (!repository) {
|
): Promise<GitChange[]> {
|
||||||
throw new Error("No Git repository found");
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = repository.state;
|
const state = repository.state;
|
||||||
const changes: GitChange[] = [];
|
const changes: GitChange[] = [];
|
||||||
|
|
||||||
@@ -70,12 +67,9 @@ export async function getGitChanges(): Promise<GitChange[]> {
|
|||||||
return changes;
|
return changes;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getGitDiff(): Promise<string> {
|
export async function getGitDiff(
|
||||||
const repository = await getActiveGitRepository();
|
repository: Repository,
|
||||||
if (!repository) {
|
): Promise<string> {
|
||||||
throw new Error("No Git repository found");
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = repository.state;
|
const state = repository.state;
|
||||||
let diffOutput = "";
|
let diffOutput = "";
|
||||||
|
|
||||||
@@ -123,7 +117,20 @@ export async function getGitDiff(): Promise<string> {
|
|||||||
return diffOutput;
|
return diffOutput;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getActiveGitRepository(): Promise<Repository | null> {
|
export function getRepositoryRoot(repository: Repository): string {
|
||||||
|
if (typeof repository.root === "string") {
|
||||||
|
return repository.root;
|
||||||
|
}
|
||||||
|
return repository.rootUri.fsPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRepositoryLabel(repository: Repository): string {
|
||||||
|
const root = getRepositoryRoot(repository);
|
||||||
|
const folderName = root.split("/").pop() || root;
|
||||||
|
return folderName;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllRepositories(): Repository[] {
|
||||||
const gitExtension =
|
const gitExtension =
|
||||||
vscode.extensions.getExtension<GitExtension>("vscode.git");
|
vscode.extensions.getExtension<GitExtension>("vscode.git");
|
||||||
if (!gitExtension) {
|
if (!gitExtension) {
|
||||||
@@ -131,10 +138,26 @@ async function getActiveGitRepository(): Promise<Repository | null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const api = gitExtension.exports.getAPI(1);
|
const api = gitExtension.exports.getAPI(1);
|
||||||
if (api.repositories.length === 0) {
|
return api.repositories;
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
return api.repositories[0];
|
|
||||||
|
export function findRepositoryForFile(
|
||||||
|
repositories: Repository[],
|
||||||
|
filePath: string,
|
||||||
|
): Repository | undefined {
|
||||||
|
const normalizedPath = filePath.toLowerCase();
|
||||||
|
let bestMatch: Repository | undefined;
|
||||||
|
let bestLength = 0;
|
||||||
|
|
||||||
|
for (const repo of repositories) {
|
||||||
|
const root = getRepositoryRoot(repo).toLowerCase();
|
||||||
|
if (normalizedPath.startsWith(root) && root.length > bestLength) {
|
||||||
|
bestMatch = repo;
|
||||||
|
bestLength = root.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bestMatch;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getChangeStatus(status: number): GitChange["status"] {
|
function getChangeStatus(status: number): GitChange["status"] {
|
||||||
@@ -160,14 +183,3 @@ function getChangeStatus(status: number): GitChange["status"] {
|
|||||||
|
|
||||||
return "modified";
|
return "modified";
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getRepositoryRoot(): Promise<string | null> {
|
|
||||||
const repository = await getActiveGitRepository();
|
|
||||||
if (!repository) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (typeof repository.root === "string") {
|
|
||||||
return repository.root;
|
|
||||||
}
|
|
||||||
return repository.rootUri.fsPath;
|
|
||||||
}
|
|
||||||
|
|||||||
+90
-54
@@ -1,14 +1,16 @@
|
|||||||
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, Repository } from "./gitService";
|
||||||
import { output } from "./extension";
|
import { output } from "./extension";
|
||||||
|
|
||||||
export interface GenerateOptions {
|
export interface GenerateOptions {
|
||||||
|
repository: Repository;
|
||||||
model?: string;
|
model?: string;
|
||||||
userSuggestion?: string;
|
userSuggestion?: string;
|
||||||
|
cancellationToken?: vscode.CancellationToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
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,32 +21,48 @@ 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 { repository } = options;
|
||||||
if (!opencodeAvailable) {
|
|
||||||
throw new Error(
|
|
||||||
"OpenCode is not installed. Please install it from https://opencode.ai",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [diff, repoRoot] = await Promise.all([
|
const [opencodePath, diff] = await Promise.all([
|
||||||
getGitDiff(),
|
getOpenCodePath(),
|
||||||
getRepositoryRoot(),
|
getGitDiff(repository),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const repoRoot = getRepositoryRoot(repository);
|
||||||
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", "");
|
||||||
|
|
||||||
@@ -70,17 +88,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/gpt-5-nano",
|
|
||||||
"--variant",
|
"--variant",
|
||||||
"minimal",
|
"minimal",
|
||||||
];
|
];
|
||||||
@@ -89,10 +103,10 @@ 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,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
OPENCODE_SERVER_PASSWORD: undefined,
|
OPENCODE_SERVER_PASSWORD: undefined,
|
||||||
@@ -105,6 +119,21 @@ Generate a concise Conventional Commit message for these changes:`;
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let settled = false;
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
proc.kill();
|
||||||
|
reject(new Error("OpenCode timed out"));
|
||||||
|
}, 120000);
|
||||||
|
|
||||||
|
const cancelDisposable = options.cancellationToken?.onCancellationRequested(() => {
|
||||||
|
if (!settled) {
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
proc.kill();
|
||||||
|
reject(new Error("Cancelled"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let stdout = "";
|
let stdout = "";
|
||||||
let stderr = "";
|
let stderr = "";
|
||||||
|
|
||||||
@@ -116,12 +145,18 @@ 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();
|
||||||
});
|
});
|
||||||
|
|
||||||
proc.on("close", (code: number | null) => {
|
proc.on("close", (code: number | null) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cancelDisposable?.dispose();
|
||||||
|
|
||||||
if (code !== 0) {
|
if (code !== 0) {
|
||||||
reject(
|
reject(
|
||||||
new Error(`OpenCode exited with code ${code}: ${stderr}`),
|
new Error(`OpenCode exited with code ${code}: ${stderr}`),
|
||||||
@@ -129,47 +164,48 @@ 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);
|
||||||
});
|
});
|
||||||
|
|
||||||
proc.on("error", (err: Error) => {
|
proc.on("error", (err: Error) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cancelDisposable?.dispose();
|
||||||
reject(new Error(`Failed to run opencode: ${err.message}`));
|
reject(new Error(`Failed to run opencode: ${err.message}`));
|
||||||
});
|
});
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
proc.kill();
|
|
||||||
reject(new Error("OpenCode timed out"));
|
|
||||||
}, 120000);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user