-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
override-fs-with-fakes.ts
67 lines (61 loc) · 2.3 KB
/
override-fs-with-fakes.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainer } from "@ogre-tools/injectable";
import fsInjectable from "../common/fs/fs.injectable";
import { createFsFromVolume, Volume } from "memfs";
import type {
ensureDirSync as ensureDirSyncImpl,
readJsonSync as readJsonSyncImpl,
writeJsonSync as writeJsonSyncImpl,
} from "fs-extra";
export const getOverrideFsWithFakes = () => {
const root = createFsFromVolume(Volume.fromJSON({}));
const readJsonSync = ((file, opts) => {
const options = typeof opts === "string"
? {
encoding: opts,
}
: opts;
const value = root.readFileSync(file, options as any) as string;
return JSON.parse(value, options?.reviver);
}) as typeof readJsonSyncImpl;
const writeJsonSync = ((file, object, opts) => {
const options = typeof opts === "string"
? {
encoding: opts,
}
: opts;
root.writeFileSync(file, JSON.stringify(object, options?.replacer, options?.spaces), options as any);
}) as typeof writeJsonSyncImpl;
const ensureDirSync = ((path, opts) => {
const mode = typeof opts === "number"
? opts
: opts?.mode;
root.mkdirpSync(path, mode);
}) as typeof ensureDirSyncImpl;
return (di: DiContainer) => {
di.override(fsInjectable, () => ({
pathExists: async (path) => root.existsSync(path),
pathExistsSync: root.existsSync,
readFile: root.promises.readFile as any,
readFileSync: root.readFileSync as any,
readJson: async (file, opts) => readJsonSync(file, opts),
readJsonSync,
writeFile: root.promises.writeFile as any,
writeFileSync: root.writeFileSync as any,
writeJson: async (file, obj, opts) => writeJsonSync(file, obj, opts as any),
writeJsonSync,
readdir: root.promises.readdir as any,
lstat: root.promises.lstat as any,
rm: root.promises.rm,
access: root.promises.access,
copy: async (src, dest) => { throw new Error(`Tried to copy '${src}' to '${dest}'. Copying is not yet supported`); },
ensureDir: async (path, opts) => ensureDirSync(path, opts),
ensureDirSync,
createReadStream: root.createReadStream as any,
stat: root.promises.stat as any,
}));
};
};