-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathgenerate-commit-msg.ts
More file actions
168 lines (149 loc) · 5.75 KB
/
generate-commit-msg.ts
File metadata and controls
168 lines (149 loc) · 5.75 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
import * as fs from 'fs-extra';
import { ChatCompletionMessageParam } from 'openai/resources';
import * as vscode from 'vscode';
import { ConfigKeys, ConfigurationManager } from './config';
import { getDiffStaged } from './git-utils';
import { ChatGPTAPI } from './openai-utils';
import { getMainCommitPrompt } from './prompts';
import { ProgressHandler } from './utils';
import { GeminiAPI } from './gemini-utils';
import { ClaudeAPI } from './claude-utils';
/**
* Generates a chat completion prompt for the commit message based on the provided diff.
*
* @param {string} diff - The diff string representing changes to be committed.
* @param {string} additionalContext - Additional context for the changes.
* @returns {Promise<Array<{ role: string, content: string }>>} - A promise that resolves to an array of messages for the chat completion.
*/
const generateCommitMessageChatCompletionPrompt = async (
diff: string,
additionalContext?: string
) => {
const INIT_MESSAGES_PROMPT = await getMainCommitPrompt();
const chatContextAsCompletionRequest = [...INIT_MESSAGES_PROMPT];
if (additionalContext) {
chatContextAsCompletionRequest.push({
role: 'user',
content: `Additional context for the changes:\n${additionalContext}`
});
}
chatContextAsCompletionRequest.push({
role: 'user',
content: diff
});
return chatContextAsCompletionRequest;
};
/**
* Retrieves the repository associated with the provided argument.
*
* @param {any} arg - The input argument containing the root URI of the repository.
* @returns {Promise<vscode.SourceControlRepository>} - A promise that resolves to the repository object.
*/
export async function getRepo(arg) {
const gitApi = vscode.extensions.getExtension('vscode.git')?.exports.getAPI(1);
if (!gitApi) {
throw new Error('Git extension not found');
}
if (typeof arg === 'object' && arg.rootUri) {
const resourceUri = arg.rootUri;
const realResourcePath: string = fs.realpathSync(resourceUri!.fsPath);
for (let i = 0; i < gitApi.repositories.length; i++) {
const repo = gitApi.repositories[i];
if (realResourcePath.startsWith(repo.rootUri.fsPath)) {
return repo;
}
}
}
return gitApi.repositories[0];
}
/**
* Generates a commit message based on the changes staged in the repository.
*
* @param {any} arg - The input argument containing the root URI of the repository.
* @returns {Promise<void>} - A promise that resolves when the commit message has been generated and set in the SCM input box.
*/
export async function generateCommitMsg(arg) {
return ProgressHandler.withProgress('', async (progress) => {
try {
const configManager = ConfigurationManager.getInstance();
const repo = await getRepo(arg);
const aiProvider = configManager.getConfig<string>(ConfigKeys.AI_PROVIDER, 'openai');
progress.report({ message: 'Getting staged changes...' });
const { diff, error } = await getDiffStaged(repo);
if (error) {
throw new Error(`Failed to get staged changes: ${error}`);
}
if (!diff || diff === 'No changes staged.') {
throw new Error('No changes staged for commit');
}
const scmInputBox = repo.inputBox;
if (!scmInputBox) {
throw new Error('Unable to find the SCM input box');
}
const additionalContext = scmInputBox.value.trim();
progress.report({
message: additionalContext
? 'Analyzing changes with additional context...'
: 'Analyzing changes...'
});
const messages = await generateCommitMessageChatCompletionPrompt(
diff,
additionalContext
);
progress.report({
message: additionalContext
? 'Generating commit message with additional context...'
: 'Generating commit message...'
});
try {
let commitMessage: string | undefined;
if (aiProvider === 'gemini') {
const geminiApiKey = configManager.getConfig<string>(ConfigKeys.GEMINI_API_KEY);
if (!geminiApiKey) {
throw new Error('Gemini API Key not configured');
}
commitMessage = await GeminiAPI(messages);
} else if (aiProvider === 'claude') {
// Claude uses CLI, no API key needed (already authenticated via 'claude setup-token')
commitMessage = await ClaudeAPI(messages);
} else {
const openaiApiKey = configManager.getConfig<string>(ConfigKeys.OPENAI_API_KEY);
if (!openaiApiKey) {
throw new Error('OpenAI API Key not configured');
}
commitMessage = await ChatGPTAPI(messages as ChatCompletionMessageParam[]);
}
if (commitMessage) {
scmInputBox.value = commitMessage;
} else {
throw new Error('Failed to generate commit message');
}
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (aiProvider === 'openai' && err.response?.status) {
switch (err.response.status) {
case 401:
errorMessage = 'Invalid OpenAI API key or unauthorized access';
break;
case 429:
errorMessage = 'Rate limit exceeded. Please try again later';
break;
case 500:
errorMessage = 'OpenAI server error. Please try again later';
break;
case 503:
errorMessage = 'OpenAI service is temporarily unavailable';
break;
}
} else if (aiProvider === 'gemini') {
errorMessage = `Gemini API error: ${err.message}`;
} else if (aiProvider === 'claude') {
errorMessage = `Claude API error: ${err.message}`;
}
throw new Error(errorMessage);
}
} catch (error) {
throw error;
}
});
}