-
Notifications
You must be signed in to change notification settings - Fork 44
/
index.js
executable file
·204 lines (154 loc) · 5.53 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
#!/usr/bin/env node
'use strict'
import { execSync } from "child_process";
import inquirer from "inquirer";
import { getArgs, checkGitRepository } from "./helpers.js";
import { addGitmojiToCommitMessage } from './gitmoji.js';
import { AI_PROVIDER, MODEL, args } from "./config.js"
import openai from "./openai.js"
import ollama from "./ollama.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 provider = AI_PROVIDER === 'ollama' ? ollama : openai
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;
}
const getPromptForSingleCommit = (diff) => {
return provider.getPromptForSingleCommit(diff, { commitType, language })
};
const generateSingleCommit = async (diff) => {
const prompt = getPromptForSingleCommit(diff)
console.log(prompt)
if (!await provider.filterApi({ prompt, filterFee: args['filter-fee'] })) process.exit(1);
const text = await provider.sendMessage(prompt, { apiKey, model: MODEL });
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 = provider.getPromptForMultipleCommits(diff, { commitType, numOptions, language })
if (!await provider.filterApi({ prompt, filterFee: args['filter-fee'], numCompletion: numOptions })) process.exit(1);
const text = await provider.sendMessage(prompt, { apiKey, model: MODEL });
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);
};
// Добавьте эту функцию после импортов
const filterLockFiles = (diff) => {
const lines = diff.split('\n');
let isLockFile = false;
const filteredLines = lines.filter(line => {
if (line.match(/^diff --git a\/(.*\/)?(yarn\.lock|pnpm-lock\.yaml|package-lock\.json)/)) {
isLockFile = true;
return false;
}
if (isLockFile && line.startsWith('diff --git')) {
isLockFile = false;
}
return !isLockFile;
});
return filteredLines.join('\n');
};
async function generateAICommit() {
const isGitRepository = checkGitRepository();
if (!isGitRepository) {
console.error("This is not a git repository 🙅♂️");
process.exit(1);
}
let diff = execSync("git diff --staged").toString();
// Filter lock files
const originalDiff = diff;
diff = filterLockFiles(diff);
// Check if lock files were changed
if (diff !== originalDiff) {
console.log("Changes detected in lock files. These changes will be included in the commit but won't be analyzed for commit message generation.");
}
// Handle empty diff after filtering
if (!diff.trim()) {
console.log("No changes to commit except lock files 🙅");
console.log("Maybe you forgot to add files? Try running git add . and then run this script again.");
process.exit(1);
}
args.list
? await generateListCommits(diff)
: await generateSingleCommit(diff);
}
await generateAICommit();