/
mock_file_system.ts
332 lines (290 loc) Β· 10.8 KB
/
mock_file_system.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {basename, dirname, resolve} from '../../src/helpers';
import {AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString} from '../../src/types';
/**
* An in-memory file system that can be used in unit tests.
*/
export abstract class MockFileSystem implements FileSystem {
private _fileTree: Folder = {};
private _cwd: AbsoluteFsPath;
constructor(private _isCaseSensitive = false, cwd: AbsoluteFsPath = '/' as AbsoluteFsPath) {
this._cwd = this.normalize(cwd);
}
isCaseSensitive() {
return this._isCaseSensitive;
}
exists(path: AbsoluteFsPath): boolean {
return this.findFromPath(path).entity !== null;
}
readFile(path: AbsoluteFsPath): string {
const {entity} = this.findFromPath(path);
if (isFile(entity)) {
return entity.toString();
} else {
throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`);
}
}
readFileBuffer(path: AbsoluteFsPath): Uint8Array {
const {entity} = this.findFromPath(path);
if (isFile(entity)) {
return entity instanceof Uint8Array ? entity : new Buffer(entity);
} else {
throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`);
}
}
writeFile(path: AbsoluteFsPath, data: string|Uint8Array, exclusive: boolean = false): void {
const [folderPath, basename] = this.splitIntoFolderAndFile(path);
const {entity} = this.findFromPath(folderPath);
if (entity === null || !isFolder(entity)) {
throw new MockFileSystemError(
'ENOENT', path, `Unable to write file "${path}". The containing folder does not exist.`);
}
if (exclusive && entity[basename] !== undefined) {
throw new MockFileSystemError(
'EEXIST', path, `Unable to exclusively write file "${path}". The file already exists.`);
}
entity[basename] = data;
}
removeFile(path: AbsoluteFsPath): void {
const [folderPath, basename] = this.splitIntoFolderAndFile(path);
const {entity} = this.findFromPath(folderPath);
if (entity === null || !isFolder(entity)) {
throw new MockFileSystemError(
'ENOENT', path, `Unable to remove file "${path}". The containing folder does not exist.`);
}
if (isFolder(entity[basename])) {
throw new MockFileSystemError(
'EISDIR', path, `Unable to remove file "${path}". The path to remove is a folder.`);
}
delete entity[basename];
}
symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void {
const [folderPath, basename] = this.splitIntoFolderAndFile(path);
const {entity} = this.findFromPath(folderPath);
if (entity === null || !isFolder(entity)) {
throw new MockFileSystemError(
'ENOENT', path,
`Unable to create symlink at "${path}". The containing folder does not exist.`);
}
entity[basename] = new SymLink(target);
}
readdir(path: AbsoluteFsPath): PathSegment[] {
const {entity} = this.findFromPath(path);
if (entity === null) {
throw new MockFileSystemError(
'ENOENT', path, `Unable to read directory "${path}". It does not exist.`);
}
if (isFile(entity)) {
throw new MockFileSystemError(
'ENOTDIR', path, `Unable to read directory "${path}". It is a file.`);
}
return Object.keys(entity) as PathSegment[];
}
lstat(path: AbsoluteFsPath): FileStats {
const {entity} = this.findFromPath(path);
if (entity === null) {
throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`);
}
return new MockFileStats(entity);
}
stat(path: AbsoluteFsPath): FileStats {
const {entity} = this.findFromPath(path, {followSymLinks: true});
if (entity === null) {
throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`);
}
return new MockFileStats(entity);
}
copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void {
this.writeFile(to, this.readFile(from));
}
moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void {
this.writeFile(to, this.readFile(from));
const result = this.findFromPath(dirname(from));
const folder = result.entity as Folder;
const name = basename(from);
delete folder[name];
}
ensureDir(path: AbsoluteFsPath): void {
const segments = this.splitPath(path).map(segment => this.getCanonicalPath(segment));
let current: Folder = this._fileTree;
// Convert the root folder to a canonical empty string `''` (on Windows it would be `'C:'`).
segments[0] = '';
for (const segment of segments) {
if (isFile(current[segment])) {
throw new Error(`Folder already exists as a file.`);
}
if (!current[segment]) {
current[segment] = {};
}
current = current[segment] as Folder;
}
}
removeDeep(path: AbsoluteFsPath): void {
const [folderPath, basename] = this.splitIntoFolderAndFile(path);
const {entity} = this.findFromPath(folderPath);
if (entity === null || !isFolder(entity)) {
throw new MockFileSystemError(
'ENOENT', path,
`Unable to remove folder "${path}". The containing folder does not exist.`);
}
delete entity[basename];
}
isRoot(path: AbsoluteFsPath): boolean {
return this.dirname(path) === path;
}
extname(path: AbsoluteFsPath|PathSegment): string {
const match = /.+(\.[^.]*)$/.exec(path);
return match !== null ? match[1] : '';
}
realpath(filePath: AbsoluteFsPath): AbsoluteFsPath {
const result = this.findFromPath(filePath, {followSymLinks: true});
if (result.entity === null) {
throw new MockFileSystemError(
'ENOENT', filePath, `Unable to find the real path of "${filePath}". It does not exist.`);
} else {
return result.path;
}
}
pwd(): AbsoluteFsPath {
return this._cwd;
}
chdir(path: AbsoluteFsPath): void {
this._cwd = this.normalize(path);
}
getDefaultLibLocation(): AbsoluteFsPath {
// Mimic the node module resolution algorithm and start in the current directory, then look
// progressively further up the tree until reaching the FS root.
// E.g. if the current directory is /foo/bar, look in /foo/bar/node_modules, then
// /foo/node_modules, then /node_modules.
let path = 'node_modules/typescript/lib';
let resolvedPath = this.resolve(path);
// Construct a path for the top-level node_modules to identify the stopping point.
const topLevelNodeModules = this.resolve('/' + path);
while (resolvedPath !== topLevelNodeModules) {
if (this.exists(resolvedPath)) {
return resolvedPath;
}
// Not here, look one level higher.
path = '../' + path;
resolvedPath = this.resolve(path);
}
// The loop exits before checking the existence of /node_modules/typescript at the top level.
// This is intentional - if no /node_modules/typescript exists anywhere in the tree, there's
// nothing this function can do about it, and TS may error later if it looks for a lib.d.ts file
// within this directory. It might be okay, though, if TS never checks for one.
return topLevelNodeModules;
}
abstract resolve(...paths: string[]): AbsoluteFsPath;
abstract dirname<T extends string>(file: T): T;
abstract join<T extends string>(basePath: T, ...paths: string[]): T;
abstract relative<T extends PathString>(from: T, to: T): PathSegment|AbsoluteFsPath;
abstract basename(filePath: string, extension?: string): PathSegment;
abstract isRooted(path: string): boolean;
abstract normalize<T extends PathString>(path: T): T;
protected abstract splitPath<T extends PathString>(path: T): string[];
dump(): Folder {
return this.cloneFolder(this._fileTree);
}
init(folder: Folder): void {
this._fileTree = this.cloneFolder(folder);
}
private cloneFolder(folder: Folder): Folder {
const clone: Folder = {};
for (const path in folder) {
const item = folder[path];
const canonicalPath = this.getCanonicalPath(path);
if (isSymLink(item)) {
clone[canonicalPath] = new SymLink(this.getCanonicalPath(item.path));
} else if (isFolder(item)) {
clone[canonicalPath] = this.cloneFolder(item);
} else {
clone[canonicalPath] = folder[path];
}
}
return clone;
}
protected findFromPath(path: AbsoluteFsPath, options?: {followSymLinks: boolean}): FindResult {
const followSymLinks = !!options && options.followSymLinks;
const segments = this.splitPath(path);
if (segments.length > 1 && segments[segments.length - 1] === '') {
// Remove a trailing slash (unless the path was only `/`)
segments.pop();
}
// Convert the root folder to a canonical empty string `""` (on Windows it would be `C:`).
segments[0] = '';
let current: Entity|null = this._fileTree;
while (segments.length) {
current = current[this.getCanonicalPath(segments.shift()!)];
if (current === undefined) {
return {path, entity: null};
}
if (segments.length > 0 && (!isFolder(current))) {
current = null;
break;
}
if (isFile(current)) {
break;
}
if (isSymLink(current)) {
if (followSymLinks) {
return this.findFromPath(resolve(current.path, ...segments), {followSymLinks});
} else {
break;
}
}
}
return {path, entity: current};
}
protected splitIntoFolderAndFile(path: AbsoluteFsPath): [AbsoluteFsPath, string] {
const segments = this.splitPath(this.getCanonicalPath(path));
const file = segments.pop()!;
return [path.substring(0, path.length - file.length - 1) as AbsoluteFsPath, file];
}
protected getCanonicalPath<T extends string>(p: T): T {
return this.isCaseSensitive() ? p : p.toLowerCase() as T;
}
}
export interface FindResult {
path: AbsoluteFsPath;
entity: Entity|null;
}
export type Entity = Folder|File|SymLink;
export interface Folder {
[pathSegments: string]: Entity;
}
export type File = string|Uint8Array;
export class SymLink {
constructor(public path: AbsoluteFsPath) {}
}
class MockFileStats implements FileStats {
constructor(private entity: Entity) {}
isFile(): boolean {
return isFile(this.entity);
}
isDirectory(): boolean {
return isFolder(this.entity);
}
isSymbolicLink(): boolean {
return isSymLink(this.entity);
}
}
class MockFileSystemError extends Error {
constructor(public code: string, public path: string, message: string) {
super(message);
}
}
export function isFile(item: Entity|null): item is File {
return Buffer.isBuffer(item) || typeof item === 'string';
}
export function isSymLink(item: Entity|null): item is SymLink {
return item instanceof SymLink;
}
export function isFolder(item: Entity|null): item is Folder {
return item !== null && !isFile(item) && !isSymLink(item);
}