-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfs-extra.js
More file actions
94 lines (86 loc) · 2.65 KB
/
fs-extra.js
File metadata and controls
94 lines (86 loc) · 2.65 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
import fse from 'fs-extra';
import { fs as memfs } from 'memfs';
import path from 'path';
let DONT_MOCK_PATTERNS = ['templates/'];
// Most of this CLI uses fs-extra for file-system operations
// This mock mocks this module to instead use memfs, while also allowing
// read operations to read from 'templates' so our tests do not need to
// mock templates
export default {
// allow mocking templates with memfs (normally tests read these from regular FS)
mockTemplates() {
DONT_MOCK_PATTERNS = [];
},
...memfs.promises,
pathExists(path) {
return this.exists(path);
},
exists(path) {
if (dontMock(path)) {
return fse.exists(path);
} else {
return new Promise((resolve) => {
memfs.exists(path, (exists) => resolve(exists));
});
}
},
isDirectory(src) {
return memfs.statSync(src).isDirectory(src);
},
appendFile: memfs.promises.appendFile,
// currently having to manually copy the sync methods over, there's prob a better way
rmSync: memfs.rmSync,
readFileSync(file, options) {
if (dontMock(file)) {
return fse.readFileSync(file, options);
}
return memfs.readFileSync(file, options);
},
outputFile: async (file, data, options) => {
const dirname = path.dirname(file);
const exists = memfs.existsSync(dirname);
if (!exists) {
memfs.mkdirSync(dirname, { recursive: true });
}
return Promise.resolve(memfs.writeFileSync(file, data, options));
},
writeFileSync: memfs.writeFileSync,
existsSync: memfs.existsSync,
appendFileSync: memfs.appendFileSync,
readdir(path, options) {
return Promise.resolve(this.readdirSync(path, options));
},
readdirSync(path, options) {
if (dontMock(path)) {
return fse.readdirSync(path, options);
}
return memfs.readdirSync(path, options);
},
copy(src, dest) {
return Promise.resolve(this.copySync(src, dest));
},
copySync(src, dest) {
// read templates from actual fs
const sourceFS = dontMock(src) ? fse : memfs;
memfs.mkdirSync(path.dirname(dest), { recursive: true });
if (sourceFS.existsSync(src) && sourceFS.statSync(src).isDirectory(src)) {
sourceFS.readdirSync(src).forEach((childItemName) => {
this.copySync(
path.join(src, childItemName),
path.join(dest, childItemName),
);
});
} else {
memfs.writeFileSync(dest, sourceFS.readFileSync(src, 'utf-8'));
}
},
readFile: (path, ...args) => {
if (dontMock(path)) {
return fse.readFile(path, ...args);
}
return memfs.promises.readFile(path, ...args);
},
};
function dontMock(src) {
return DONT_MOCK_PATTERNS.some((pattern) => src.includes(pattern));
}