-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathapi.ts
More file actions
155 lines (121 loc) · 3.73 KB
/
api.ts
File metadata and controls
155 lines (121 loc) · 3.73 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
import { intro, outro } from '@clack/prompts';
import { execSync } from 'child_process';
import axios from 'axios';
import chalk from 'chalk';
import {
ChatCompletionRequestMessage,
Configuration as OpenAiApiConfiguration,
OpenAIApi
} from 'openai';
import { CONFIG_MODES, getConfig } from './commands/config';
const config = getConfig();
let apiKey = config?.OPENAI_API_KEY;
let basePath = config?.OPENAI_BASE_PATH;
let maxTokens = config?.OPENAI_MAX_TOKENS;
const [command, mode] = process.argv.slice(2);
if (!apiKey && command !== 'config' && mode !== CONFIG_MODES.set) {
intro('opencommit');
outro(
'OPENAI_API_KEY is not set, please run `oc config set OPENAI_API_KEY=<your token>. Make sure you add payment details, so API works.`'
);
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
process.exit(1);
}
const MODEL = config?.model || 'gpt-3.5-turbo';
class OpenAi {
private openAiApiConfiguration = new OpenAiApiConfiguration({
apiKey: apiKey
});
private openAI!: OpenAIApi;
constructor() {
if (basePath) {
this.openAiApiConfiguration.basePath = basePath;
}
this.openAI = new OpenAIApi(this.openAiApiConfiguration);
}
public generateCommitMessage = async (
messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> => {
try {
const { data } = await this.openAI.createChatCompletion({
model: MODEL,
messages,
temperature: 0,
top_p: 0.1,
max_tokens: maxTokens ?? 196
});
const message = data.choices[0].message;
const prefix = generatePrefix();
const finalMessage = (prefix != "undefined" ? prefix + ' ' : '') + (message?.content || '')
return finalMessage;
} catch (error: unknown) {
outro(`${chalk.red('✖')} ${error}`);
if (
axios.isAxiosError<{ error?: { message: string } }>(error) &&
error.response?.status === 401
) {
const openAiError = error.response.data.error;
if (openAiError?.message) outro(openAiError.message);
outro(
'For help look into README https://github.com/di-sukharev/opencommit#setup'
);
}
process.exit(1);
}
};
}
export const getOpenCommitLatestVersion = async (): Promise<
string | undefined
> => {
try {
const { data } = await axios.get(
'https://unpkg.com/opencommit/package.json'
);
return data.version;
} catch (_) {
outro('Error while getting the latest version of opencommit');
return undefined;
}
};
function generatePrefix(): string | undefined {
const prefix = config?.prefix
if (prefix === undefined) {
return undefined;
}
const prefixIsRegexString = prefix.startsWith('/') && prefix.endsWith('/');
if (prefixIsRegexString) {
try {
return generatePrefixFromRegex(prefix);
} catch (error) {
console.error(`Failed to generate prefix from regex: ${error}`);
return undefined;
}
}
return prefix;
}
export const api = new OpenAi();
function generatePrefixFromRegex(regex: string): string | undefined {
// We currently only support regex input from git branch name
const branch = getCurrentGitBranch();
if (branch === undefined) {
return undefined;
}
const regexWithoutSlashes = regex.slice(1, -1);
const regexObject = new RegExp(regexWithoutSlashes);
const match = branch.match(regexObject);
if (match === null) {
return undefined;
}
return match[0];
}
function getCurrentGitBranch(): string | undefined {
try {
const branchName = execSync('git symbolic-ref --short HEAD', { encoding: 'utf8' }).trim();
return branchName;
} catch (error) {
console.error(`Failed to get current git branch: ${error}`);
return undefined;
}
}