forked from shanginn/git-aicommit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocommit.js
executable file
·170 lines (144 loc) · 5.05 KB
/
autocommit.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
#!/usr/bin/env node
import { execSync, spawn } from "child_process";
import rc from 'rc';
import {
ChatPromptTemplate,
HumanMessagePromptTemplate,
PromptTemplate,
SystemMessagePromptTemplate
} from "langchain/prompts";
import defaultConfig from './config.js';
import {ChatOpenAI} from "langchain/chat_models/openai";
import {getModelContextSize} from "./count_tokens.js";
const config = rc(
'git-aicommit',
{
...defaultConfig,
openAiKey: process.env.OPENAI_API_KEY,
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY
},
);
try {
execSync(
'git rev-parse --is-inside-work-tree',
{encoding: 'utf8', stdio: 'ignore'}
);
} catch (e) {
console.error("This is not a git repository");
process.exit(1);
}
if (!config.openAiKey && !config.azureOpenAiKey) {
console.error("Please set OPENAI_API_KEY or AZURE_OPENAI_API_KEY");
process.exit(1);
}
// if any settings related to AZURE are set, if there are items that are not set, will error.
if (config.azureOpenAiKey && !(
config.azureOpenAiInstanceName && config.azureOpenAiDeploymentName && config.azureOpenAiVersion
)){
console.error("Please set AZURE_OPENAI_API_KEY, AZURE_OPENAI_API_INSTANCE_NAME, AZURE_OPENAI_API_DEPLOYMENT_NAME, AZURE_OPENAI_API_VERSION when Azure OpenAI Service.");
process.exit(1);
}
const excludeFromDiff = config.excludeFromDiff || [];
const diffFilter = config.diffFilter || 'ACMRTUXB';
const diffCommand = `git diff --staged \
--no-ext-diff \
--diff-filter=${diffFilter} \
-- ${excludeFromDiff.map(
(pattern) => `':(exclude)${pattern}'`
).join(' ')}
`;
let diff = execSync(diffCommand, {encoding: 'utf8'});
if (!diff) {
console.error("Diff seems empty. Please commit manually.");
process.exit(1);
}
const openai = new ChatOpenAI({
modelName: config.modelName,
openAIApiKey: config.openAiKey,
azureOpenAIApiKey: config.azureOpenAiKey,
azureOpenAIApiInstanceName: config.azureOpenAiInstanceName,
azureOpenAIApiDeploymentName: config.azureOpenAiDeploymentName,
azureOpenAIApiVersion: config.azureOpenAiVersion,
temperature: config.temperature,
maxTokens: config.maxTokens,
});
const systemMessagePromptTemplate = SystemMessagePromptTemplate.fromTemplate(
config.systemMessagePromptTemplate
);
const humanPromptTemplate = HumanMessagePromptTemplate.fromTemplate(
config.humanPromptTemplate
);
const chatPrompt = ChatPromptTemplate.fromPromptMessages([
systemMessagePromptTemplate,
humanPromptTemplate,
]);
const chatMessages = await chatPrompt.formatMessages({
diff: diff,
language: config.language,
});
const tokenCount = (await openai.getNumTokensFromMessages(chatMessages)).totalCount
const contextSize = getModelContextSize(config.modelName)
if (tokenCount > contextSize) {
console.log('Diff is too long. Splitting into multiple requests.')
// TODO: split smarter
const filenameRegex = /^a\/(.+?)\s+b\/(.+?)/;
const diffByFiles = diff
.split('diff ' + '--git ') // Wierd string concat in order to avoid splitting on this line when using autocommit in this repo :)
.filter((fileDiff) => fileDiff.length > 0)
.map((fileDiff) => {
const match = fileDiff.match(filenameRegex);
const filename = match ? match[1] : 'Unknown file';
const content = fileDiff
.replaceAll(filename, '')
.replaceAll('a/ b/\n', '')
return chatPrompt
.formatMessages({
diff: content,
language: config.language,
})
.then((prompt) => {
return openai.call(prompt)
.then((res) => {
return {
filename: filename,
changes: res.text.trim(),
}
})
.catch((e) => {
console.error(`Error during OpenAI request: ${e.message}`);
process.exit(1);
});
});
});
// wait for all promises to resolve
const mergeChanges = await Promise.all(diffByFiles);
diff = mergeChanges
.map((fileDiff) => {
return `diff --git ${fileDiff.filename}\n${fileDiff.changes}`
})
.join('\n\n')
}
const prompt = await chatPrompt.formatMessages({
diff: diff,
language: config.language,
})
const res = await openai.call(prompt)
.catch((e) => {
console.error(`Error during OpenAI request: ${e.message}`);
process.exit(1);
});
const commitMessage = res.text.trim();
if (!config.autocommit) {
console.log(`Autocommit is disabled. Here is the message:\n ${commitMessage}`);
} else {
console.log(`Committing with following message:\n ${commitMessage}`);
execSync(
`git commit -m "${commitMessage.replace(/"/g, '')}"`,
{encoding: 'utf8'}
);
}
if (config.openCommitTextEditor) {
spawn('git', ['commit', '--amend'], {
stdio: 'inherit'
});
}