forked from RomanHotsiy/commitgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
49 lines (40 loc) · 1.34 KB
/
config.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
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { homedir } from 'os';
import enquirer from 'enquirer';
import { ClientConfig, refreshAccessToken } from './client.js';
const CONFIG_FILE_NAME = `${homedir()}/.commit-gpt.json`;
export async function ensureSessionToken(clean?: boolean): Promise<string> {
let config: Partial<ClientConfig> = {};
if (existsSync(CONFIG_FILE_NAME) && !clean) {
config = JSON.parse(readFileSync(CONFIG_FILE_NAME, 'utf-8'));
}
if (!config.sessionToken) {
config.sessionToken = await promptToken();
}
while (true) {
try {
await refreshAccessToken(config.sessionToken);
writeFileSync(CONFIG_FILE_NAME, JSON.stringify(config, null, 2));
return config.sessionToken;
} catch (e) {
console.log('Invalid token. Please try again.');
config.sessionToken = await promptToken();
}
}
}
async function promptToken() {
try {
console.log(
'Follow instructions here to get your OpenAI session token: https://github.com/RomanHotsiy/commitgpt#get-your-session-token'
);
const answer = await enquirer.prompt<{ sessionToken: string }>({
type: 'password',
name: 'sessionToken',
message: 'Paste your session token here:',
});
return answer.sessionToken;
} catch (e) {
console.log('Aborted.');
process.exit(1);
}
}