forked from onlook-dev/onlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.ts
More file actions
109 lines (97 loc) · 3.49 KB
/
files.ts
File metadata and controls
109 lines (97 loc) · 3.49 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
import { existsSync, promises as fs } from 'fs';
import * as path from 'path';
import prettier from 'prettier';
import crypto from 'crypto';
export async function readFile(filePath: string): Promise<string | null> {
try {
const fullPath = path.resolve(filePath);
const data = await fs.readFile(fullPath, 'utf8');
return data;
} catch (error: any) {
// Return null if file doesn't exist, otherwise throw the error
if (error.code === 'ENOENT') {
return null;
}
console.error('Error reading file:', error);
throw error;
}
}
export async function writeFile(
filePath: string,
content: string,
encoding: 'utf8' | 'base64' = 'utf8',
): Promise<void> {
if (!filePath) {
throw new Error('File path is required');
}
try {
const fullPath = path.resolve(filePath);
const isNewFile = !existsSync(fullPath);
let fileContent: string | Buffer = content;
if (encoding === 'base64') {
try {
// Strip data URL prefix if present and validate base64
const base64Data = content.replace(/^data:[^,]+,/, '');
if (!isValidBase64(base64Data)) {
throw new Error('Invalid base64 content');
}
fileContent = Buffer.from(base64Data, 'base64');
} catch (e: any) {
throw new Error(`Invalid base64 content: ${e.message}`);
}
}
// Ensure parent directory exists
const parentDir = path.dirname(fullPath);
await fs.mkdir(parentDir, { recursive: true });
await fs.writeFile(fullPath, fileContent, { encoding });
if (isNewFile) {
console.log('New file created:', fullPath);
}
} catch (error: any) {
const errorMessage = `Failed to write to ${filePath}: ${error.message}`;
console.error(errorMessage);
throw error;
}
}
// Helper function to validate base64 strings
function isValidBase64(str: string): boolean {
try {
return Buffer.from(str, 'base64').toString('base64') === str;
} catch {
return false;
}
}
export async function formatContent(filePath: string, content: string): Promise<string> {
try {
const config = (await prettier.resolveConfig(filePath)) || {};
const formattedContent = await prettier.format(content, {
...config,
filepath: filePath,
plugins: [], // This prevents us from using plugins we don't have installed
});
return formattedContent;
} catch (error: any) {
console.error('Error formatting file:', error);
return content;
}
}
export function createHash(content: string): string {
return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
}
export async function checkIfCacheDirectoryExists(projectDir: string): Promise<void> {
const cacheDir = path.join(projectDir, '.onlook', 'cache');
try {
await fs.mkdir(cacheDir, { recursive: true });
} catch (error) {
console.error(`Failed to create cache directory: ${error}`);
}
}
export async function removeCacheDirectory(projectDir: string): Promise<void> {
const cacheDir = path.join(projectDir, '.onlook');
try {
await fs.rm(cacheDir, { recursive: true, force: true });
console.log(`Removed cache directory: ${cacheDir}`);
} catch (error) {
console.error(`Failed to remove cache directory: ${error}`);
}
}