-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
291 lines (269 loc) · 8.41 KB
/
extension.js
File metadata and controls
291 lines (269 loc) · 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const vscode = require("vscode");
const { exec } = require("node:child_process");
const { promisify } = require("node:util");
const asyncExec = promisify(exec);
/**
* System prompt used for guiding the LLM's behavior.
*
* @type {string}
*/
const SYSTEM_PROMPT =
"You are a helpful assistant that writes high-quality Git commit messages.";
/**
* Template for the user prompt. The token {{DIFF}} will be replaced with the
* unified git diff content at runtime.
*
* @type {string}
*/
const USER_PROMPT_TEMPLATE = `Given the following unified git diff, write a clear, conventional commit message.
Provide a concise title (<= 72 chars).
Include a brief body with bullet points when helpful.
Use imperative mood and explain the "why" when evident from the diff.
<START_OF_FORMAT>
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<END_OF_FORMAT>
<START_OF_DIFF>
\`\`\`diff
{{DIFF}}
\`\`\`
<END_OF_DIFF>
`;
/**
* Return VS Code Git API v1 if available.
*
* @returns {import('vscode').Extension<any>["exports"] | undefined} Git API exports or undefined.
*/
function getGitApi() {
const gitExtension = vscode.extensions.getExtension("vscode.git");
if (!gitExtension) {
return undefined;
}
const exports = gitExtension.exports;
if (!exports || typeof exports.getAPI !== "function") {
return undefined;
}
return exports.getAPI(1);
}
/**
* Execute a git diff command in the given working directory.
*
* @param {string} cwd Working directory path.
* @param {boolean} staged Whether to diff staged changes only.
*
* @returns {Promise<string>} Diff output text.
*/
async function gitDiffFallback(cwd, staged) {
const args = staged ? "diff --staged" : "diff";
const { stdout } = await asyncExec(`git ${args}`, {
cwd,
maxBuffer: 10 * 1024 * 1024,
});
return stdout;
}
/**
* Get a unified diff string from the first available repository using the Git extension API.
* Falls back to invoking the git binary if necessary.
*
* @param {any} api VS Code Git API v1.
*
* @returns {Promise<{ repo: any, diff: string }>} Repository and its diff string.
*/
async function getRepositoryDiff(api) {
if (
!api ||
!Array.isArray(api.repositories) ||
api.repositories.length === 0
) {
throw new Error("No Git repository found.");
}
const repo = api.repositories[0];
if (typeof repo.diffWithHEAD === "function") {
const diff = await repo.diffWithHEAD();
if (typeof diff === "string") {
return { repo, diff };
}
}
if (typeof repo.diffIndexWithHEAD === "function") {
const diff = await repo.diffIndexWithHEAD();
if (typeof diff === "string") {
return { repo, diff };
}
}
const cwd = repo.rootUri?.fsPath;
const diff = await gitDiffFallback(cwd || process.cwd(), true);
return { repo, diff };
}
/**
* Call an OpenAI-compatible chat completions endpoint (Ollama) to generate a commit message.
*
* @param {string} endpoint Base URL to the API, e.g. http://localhost:11434/v1.
* @param {string} model Model name.
* @param {string} diff Unified diff text.
*
* @returns {Promise<string>} Generated commit message.
*/
async function generateCommitMessageWithLLM(endpoint, model, diff) {
const trimmed =
diff.length > 60_000 ? `${diff.slice(0, 60_000)}\n [truncated]` : diff;
const system = SYSTEM_PROMPT;
const user = USER_PROMPT_TEMPLATE.replace("{{DIFF}}", trimmed);
const res = await fetch(`${endpoint}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model,
messages: [
{ role: "system", content: system },
{ role: "user", content: user },
],
stream: false,
}),
});
if (!res.ok) {
const text = await res.text().catch(() => String(res.status));
throw new Error(`LLM request failed: ${res.status} ${text}`);
}
const data = await res.json();
const hasChoices = data && typeof data === "object" && "choices" in data;
const choices = hasChoices ? /** @type {any} */ (data).choices : undefined;
const firstChoice = Array.isArray(choices) ? choices[0] : undefined;
const content =
firstChoice &&
firstChoice.message &&
typeof firstChoice.message.content === "string"
? firstChoice.message.content
: undefined;
if (!content) {
throw new Error("LLM returned no content.");
}
return stripOuterCodeFence(content.trim());
}
/**
* Strip a surrounding triple backtick code fence (optionally with language) from text.
*
* @param {string} text Raw text possibly wrapped in ``` fences.
* @returns {string} Unfenced text.
*/
function stripOuterCodeFence(text) {
let result = text.trim();
if (!result.startsWith("```") && !result.endsWith("```")) {
return result;
}
// Remove leading fence line: ``` or ```lang
if (result.startsWith("```")) {
const firstNewlineIdx = result.indexOf("\n");
if (firstNewlineIdx !== -1) {
result = result.slice(firstNewlineIdx + 1);
} else {
result = result.replace(/^```+/, "");
}
}
// Remove trailing fence: on its own line or at end
if (result.endsWith("```")) {
// If there's a trailing newline then the last three backticks should be on the final line
const lastFenceIdx = result.lastIndexOf("```");
if (lastFenceIdx !== -1) {
result = result.slice(0, lastFenceIdx);
}
}
return result.trim();
}
/**
* Generate and set the commit message for the active repository.
* Logs progress using console debug/info/error messages.
*
* @returns {Promise<void>} Nothing.
*/
async function generateAndApplyCommitMessage() {
const api = getGitApi();
if (!api) {
throw new Error("VS Code Git extension not available.");
}
console.debug("[llm-commit-msg] Preparing diff");
let { repo, diff } = await getRepositoryDiff(api);
if (typeof diff !== "string") {
// Ensure a string diff by falling back to shell git.
const cwd = repo?.rootUri?.fsPath || process.cwd();
diff = await gitDiffFallback(cwd, true);
}
if (!diff || (typeof diff === "string" && diff.trim().length === 0)) {
throw new Error(
"No changes to generate a commit message from. Stage changes first.",
);
}
console.debug("[llm-commit-msg] Loading settings");
const config = vscode.workspace.getConfiguration("llmCommitMsg");
/** @type {string | undefined} */
const endpoint = config.get("endpoint");
/** @type {string | undefined} */
const model = config.get("model");
if (!endpoint || !model) {
throw new Error(
"LLM Commit Message settings are not configured. Please set endpoint and model in Settings.",
);
}
console.info(`[llm-commit-msg] Contacting LLM with details: endpoint=${endpoint} model=${model}`);
const message = await generateCommitMessageWithLLM(endpoint, model, diff);
console.debug("[llm-commit-msg] Applying message");
if (repo?.inputBox) {
repo.inputBox.value = message;
console.info("[llm-commit-msg] Commit message applied to Source Control input box.");
} else {
await vscode.env.clipboard.writeText(message);
vscode.window.showInformationMessage(
"Commit message copied to clipboard (no repository input box found).",
);
console.info("[llm-commit-msg] Commit message copied to clipboard (no input box).");
}
}
/**
* Activate the extension.
*
* @param {vscode.ExtensionContext} context VS Code extension context.
*
* @returns {void} Nothing.
*/
function activate(context) {
console.log('Extension "llm-commit-msg" active');
const disposable = vscode.commands.registerCommand(
"llm-commit-msg.generateCommitMessage",
async () => {
const start = Date.now();
let errorMsg;
try {
await generateAndApplyCommitMessage();
} catch (error) {
errorMsg = error instanceof Error ? error.message : String(error);
}
const elapsedMs = Date.now() - start;
const seconds = Math.max(0, Math.round(elapsedMs / 100) / 10);
if (errorMsg) {
vscode.window.showErrorMessage(
`Generate commit message - failure (${seconds}s). Error: ${errorMsg}`
);
} else {
vscode.window.showInformationMessage(
`Generate commit message - success (${seconds}s)`
);
}
},
);
context.subscriptions.push(disposable);
}
/**
* Deactivate the extension.
*
* @returns {void} Nothing.
*/
function deactivate() { }
module.exports = {
activate,
deactivate,
// Export internals for testing
getGitApi,
getRepositoryDiff,
generateCommitMessageWithLLM,
generateAndApplyCommitMessage,
};