-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile-utils.ts
46 lines (37 loc) · 1.35 KB
/
file-utils.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
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { format } from 'date-fns';
import type { Message } from '@callstack/byorg-core';
export const CHATS_SAVE_DIRECTORY = '~/ai-chats';
function escapeFilename(filename: string) {
const base = filename.split(' ', 5).join(' ');
return base.replace(/[/\\:*?"<>|.]/g, '_');
}
export function getDefaultFilename(messages: Message[]) {
const currentDate = new Date();
const firstMessagePart = escapeFilename(messages[0]?.content ?? '');
return `${format(currentDate, 'yyyy-MM-dd HH-mm')} ${firstMessagePart}`;
}
export function getUniqueFilename(filePath: string) {
const { name, ext, dir } = path.parse(filePath);
const extension = ext === '' ? '.txt' : ext;
if (!fs.existsSync(`${dir}/${name}${extension}`)) {
return `${dir}/${name}${extension}`;
}
let numerator = 1;
// Case when -1 exists, we increase as long as we find a free numerator
while (fs.existsSync(`${dir}/${name}-${numerator}${extension}`)) {
numerator++;
}
return `${dir}/${name}-${numerator}${extension}`;
}
export function getConversationStoragePath() {
const chatsSaveDirectory = CHATS_SAVE_DIRECTORY.replace('~', os.homedir());
if (fs.existsSync(chatsSaveDirectory)) {
return chatsSaveDirectory;
} else {
fs.mkdirSync(chatsSaveDirectory);
return chatsSaveDirectory;
}
}