-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvirtual-fs.ts
More file actions
67 lines (58 loc) · 1.89 KB
/
virtual-fs.ts
File metadata and controls
67 lines (58 loc) · 1.89 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
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileExists } from '@code-pushup/utils';
import type { FileChange, FileSystemAdapter, Tree } from './types.js';
const DEFAULT_FS: FileSystemAdapter = {
readFile,
writeFile,
exists: fileExists,
mkdir,
};
export function createTree(
root: string,
fs: FileSystemAdapter = DEFAULT_FS,
): Tree {
const pending = new Map<FileChange['path'], Omit<FileChange, 'path'>>();
const resolve = (filePath: string): string => path.resolve(root, filePath);
return {
root,
exists: async (filePath: string): Promise<boolean> =>
pending.has(filePath) || fs.exists(resolve(filePath)),
read: async (filePath: string): Promise<string | null> => {
const entry = pending.get(filePath);
if (entry) {
return entry.content;
}
const absolutePath = resolve(filePath);
if (!(await fs.exists(absolutePath))) {
return null;
}
return fs.readFile(absolutePath, 'utf8');
},
write: async (filePath: string, content: string): Promise<void> => {
const entry = pending.get(filePath);
if (entry) {
pending.set(filePath, { ...entry, content });
} else {
const type = (await fs.exists(resolve(filePath))) ? 'UPDATE' : 'CREATE';
pending.set(filePath, { content, type });
}
},
listChanges: (): FileChange[] =>
[...pending.entries()].map(([filePath, { content, type }]) => ({
path: filePath,
type,
content,
})),
async flush(): Promise<void> {
await Promise.all(
[...pending.entries()].map(async ([filePath, { content }]) => {
const absolutePath = resolve(filePath);
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
await fs.writeFile(absolutePath, content);
}),
);
pending.clear();
},
};
}