-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
181 lines (147 loc) · 5.78 KB
/
main.ts
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
import { parse } from "https://deno.land/std/flags/mod.ts";
import { config } from "https://deno.land/x/dotenv/mod.ts";
import { OpenAI } from 'https://deno.land/x/openai/mod.ts';
import { Confirm } from "https://deno.land/x/cliffy/prompt/confirm.ts";
import { Select } from "https://deno.land/x/cliffy/prompt/select.ts";
import chalk from "https://deno.land/x/[email protected]/source/index.js";
import { TerminalSpinner } from "https://deno.land/x/spinners/mod.ts";
const HELP_MESSAGE = `
Usage: deno run --allow-net --allow-read --allow-run --allow-env main.ts [options] [dir]
Options:
-h, --help Show this help message and exit
-d, --dir Directory where to perform the diff (default: current directory)
--debug Show debug information
`;
const args = parse(Deno.args, {
alias: { h: "help", d: "dir" },
boolean: ["help", "debug"],
string: ["dir"],
});
if (args.help) {
console.log(HELP_MESSAGE);
Deno.exit(0);
}
const directory = args.dir || Deno.cwd();
const openaiApiKeyFromEnv = Deno.env.get("OPENAI_API_KEY");
const modelVersionFromEnv = Deno.env.get("MODEL_VERSION");
const numCommitMessagesFromEnv = Deno.env.get("NUM_COMMIT_MESSAGES");
const { OPENAI_API_KEY, MODEL_VERSION, NUM_COMMIT_MESSAGES } = {
OPENAI_API_KEY: openaiApiKeyFromEnv || config().OPENAI_API_KEY,
MODEL_VERSION: modelVersionFromEnv || config().MODEL_VERSION,
NUM_COMMIT_MESSAGES: numCommitMessagesFromEnv || config().NUM_COMMIT_MESSAGES,
};
const openai = new OpenAI(OPENAI_API_KEY);
if (!OPENAI_API_KEY) {
console.error("Error: OPENAI_API_KEY not found in .env file.");
Deno.exit(1);
}
async function getDiff(): Promise<string> {
const cmd = Deno.run({
cmd: ["git", "diff", "--unified=0"],
cwd: directory,
stdout: "piped",
stderr: "piped",
});
const output = await cmd.output();
const error = await cmd.stderrOutput();
const status = await cmd.status();
if (!status.success) {
console.error(new TextDecoder().decode(error));
Deno.exit(1);
}
return new TextDecoder().decode(output);
}
function hasChanges(diff: string): boolean {
return diff.trim().length > 0;
}
async function getCommitMessages(diff: string): Promise<{ value: string; name: string; }[]> {
const terminalSpinner = new TerminalSpinner("Getting commits from OpenAI...");
terminalSpinner.start();
const response = await openai.createChatCompletion({
model: MODEL_VERSION,
messages: [{ role: "user", content: `Suggest ${NUM_COMMIT_MESSAGES} Git commit messages for the following diff:\n\n${diff}` }],
});
terminalSpinner.succeed("Commits fetched from OpenAI!");
if (!response.choices || response.choices.length === 0) {
console.error(chalk.red("Error: Unexpected response from OpenAI API. Please try running the tool again."));
if (args.debug) {
console.error(chalk.red("Debug information:"));
console.error(response);
}
Deno.exit(1);
}
const messages = response.choices[0].message.content.trim().split('\n');
return messages.map((message) => {
const value = message.replace(/^\d+\. /, '');
return { value: value, name: message };
});
}
async function commitWithMessage(message: string) {
// Stage all changes in the working directory
await Deno.run({
cmd: ["git", "add", "."],
cwd: directory,
stdout: "piped",
stderr: "piped",
}).status();
// Commit staged changes with the provided message
const cmd = Deno.run({
cmd: ["git", "commit", "-m", message],
cwd: directory,
stdout: "piped",
stderr: "piped",
});
const output = await cmd.output();
const error = await cmd.stderrOutput();
const status = await cmd.status();
if (!status.success) {
console.error(new TextDecoder().decode(error));
Deno.exit(1);
}
console.log(new TextDecoder().decode(output));
}
async function selectCommitMessage(commitMessages: { value: string; name: string; }[]): Promise<string | null> {
const options = [
...commitMessages,
{
value: "refresh",
name: chalk.blue("Get more commit messages..."),
},
];
const selectedMessage = await Select.prompt({
message: chalk.bold.yellow("Select a commit message:"),
options: options,
});
return selectedMessage === "refresh" ? null : selectedMessage;
}
(async () => {
try {
const diff = await getDiff();
if (!hasChanges(diff)) {
console.log(chalk.yellow("No changes detected. Exiting."));
Deno.exit(0);
}
let commitMessages = await getCommitMessages(diff);
let selectedMessage: string | null;
do {
selectedMessage = await selectCommitMessage(commitMessages);
if (selectedMessage === null) {
commitMessages = await getCommitMessages(diff);
}
} while (selectedMessage === null);
console.log(chalk.green("Selected commit message:"), selectedMessage);
const confirmation = await Confirm.prompt({
message: chalk.bold.yellow(`Do you want to commit with the message "${selectedMessage}"?`),
default: "y",
type: "confirm",
});
if (confirmation) {
await commitWithMessage(selectedMessage);
console.log(chalk.green(`Committed with message: "${selectedMessage}"`));
} else {
console.log(chalk.red("Commit canceled."));
}
} catch (error) {
console.error(chalk.red("Error:"), error.message);
}
})();