forked from insulineru/ai-commit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
Β·255 lines (193 loc) Β· 6.72 KB
/
index.js
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
#!/usr/bin/env node
'use strict'
import { execSync } from "child_process";
import { ChatGPTAPI } from "chatgpt";
import inquirer from "inquirer";
import { getArgs, checkGitRepository } from "./helpers.js";
import { addGitmojiToCommitMessage } from './gitmoji.js';
import { filterApi } from "./filterApi.js";
import { AI_PROVIDER, MODEL, args } from "./config.js"
const REGENERATE_MSG = "β»οΈ Regenerate Commit Messages";
console.log('Ai provider: ', AI_PROVIDER);
const ENDPOINT = args.ENDPOINT || process.env.ENDPOINT
const apiKey = args.apiKey || process.env.OPENAI_API_KEY;
const language = args.language || process.env.AI_COMMIT_LANGUAGE || 'english';
if (AI_PROVIDER == 'openai' && !apiKey) {
console.error("Please set the OPENAI_API_KEY environment variable.");
process.exit(1);
}
let template = args.template || process.env.AI_COMMIT_COMMIT_TEMPLATE
const doAddEmoji = args.emoji || process.env.AI_COMMIT_ADD_EMOJI
const commitType = args['commit-type'];
const processTemplate = ({ template, commitMessage }) => {
if (!template.includes('COMMIT_MESSAGE')) {
console.log(`Warning: template doesn't include {COMMIT_MESSAGE}`)
return commitMessage;
}
let finalCommitMessage = template.replaceAll("{COMMIT_MESSAGE}", commitMessage);
if (finalCommitMessage.includes('GIT_BRANCH')) {
const currentBranch = execSync("git branch --show-current").toString().replaceAll("\n", "");
console.log('Using currentBranch: ', currentBranch);
finalCommitMessage = finalCommitMessage.replaceAll("{GIT_BRANCH}", currentBranch)
}
return finalCommitMessage;
}
const makeCommit = (input) => {
console.log("Committing Message... π ");
execSync(`git commit -F -`, { input });
console.log("Commit Successful! π");
};
const processEmoji = (msg, doAddEmoji) => {
if (doAddEmoji) {
return addGitmojiToCommitMessage(msg);
}
return msg;
}
/**
* send prompt to ai.
*/
const sendMessage = async (input) => {
if (AI_PROVIDER == 'ollama') {
//mistral as default since it's fast and clever model
const model = MODEL || 'mistral'
const url = 'http://localhost:11434/api/generate'
const data = {
model,
prompt: input,
stream: false
}
console.log('prompting ollama...', url, model)
try {
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
})
const responseJson=await response.json();
const answer = responseJson.response
console.log('response: ', answer)
console.log('prompting ai done!')
return answer
} catch (err) {
throw new Error('local model issues. details:' err.message)
}
}
if (AI_PROVIDER == 'openai') {
console.log('prompting chat gpt...')
const api = new ChatGPTAPI({
apiKey,
});
const { text } = await api.sendMessage(input);
console.log('prompting ai done!')
return text
}
}
const getPromptForSingleCommit = (diff) => {
if (AI_PROVIDER == "openai") {
return (
"I want you to act as the author of a commit message in git."
`I'll enter a git diff, and your job is to convert it into a useful commit message in ${language} language`
(commitType ? ` with commit type '${commitType}'. ` : ". ")
"Do not preface the commit with anything, use the present tense, return the full sentence, and use the conventional commits specification (<type in lowercase>: <subject>): "
diff
);
}
//for less smart models, give simpler instruction.
return (
"Summarize this git diff into a useful, 10 words commit message"
(commitType ? ` with commit type '${commitType}.'` : "")
": " diff
);
};
const generateSingleCommit = async (diff) => {
const prompt = getPromptForSingleCommit(diff)
if (!await filterApi({ prompt, filterFee: args['filter-fee'] })) process.exit(1);
const text = await sendMessage(prompt);
let finalCommitMessage = processEmoji(text, args.emoji);
if (args.template) {
finalCommitMessage = processTemplate({
template: args.template,
commitMessage: finalCommitMessage,
})
console.log(
`Proposed Commit With Template:\n------------------------------\n${finalCommitMessage}\n------------------------------`
);
} else {
console.log(
`Proposed Commit:\n------------------------------\n${finalCommitMessage}\n------------------------------`
);
}
if (args.force) {
makeCommit(finalCommitMessage);
return;
}
const answer = await inquirer.prompt([
{
type: "confirm",
name: "continue",
message: "Do you want to continue?",
default: true,
},
]);
if (!answer.continue) {
console.log("Commit aborted by user π
ββοΈ");
process.exit(1);
}
makeCommit(finalCommitMessage);
};
const generateListCommits = async (diff, numOptions = 5) => {
const prompt =
"I want you to act as the author of a commit message in git."
`I'll enter a git diff, and your job is to convert it into a useful commit message in ${language} language`
(commitType ? ` with commit type '${commitType}.', ` : ", ")
`and make ${numOptions} options that are separated by ";".`
"For each option, use the present tense, return the full sentence, and use the conventional commits specification (<type in lowercase>: <subject>):"
diff;
if (!await filterApi({ prompt, filterFee: args['filter-fee'], numCompletion: numOptions })) process.exit(1);
const text = await sendMessage(prompt);
let msgs = text.split(";").map((msg) => msg.trim()).map(msg => processEmoji(msg, args.emoji));
if (args.template) {
msgs = msgs.map(msg => processTemplate({
template: args.template,
commitMessage: msg,
}))
}
// add regenerate option
msgs.push(REGENERATE_MSG);
const answer = await inquirer.prompt([
{
type: "list",
name: "commit",
message: "Select a commit message",
choices: msgs,
},
]);
if (answer.commit === REGENERATE_MSG) {
await generateListCommits(diff);
return;
}
makeCommit(answer.commit);
};
async function generateAICommit() {
const isGitRepository = checkGitRepository();
if (!isGitRepository) {
console.error("This is not a git repository π
ββοΈ");
process.exit(1);
}
const diff = execSync("git diff --staged").toString();
// Handle empty diff
if (!diff) {
console.log("No changes to commit π
");
console.log(
"May be you forgot to add the files? Try git add . and then run this script again."
);
process.exit(1);
}
args.list
? await generateListCommits(diff)
: await generateSingleCommit(diff);
}
await generateAICommit();