-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
vfsUtil.ts
1666 lines (1491 loc) · 65.4 KB
/
vfsUtil.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as collections from "./_namespaces/collections.js";
import * as documents from "./_namespaces/documents.js";
import * as Harness from "./_namespaces/Harness.js";
import * as ts from "./_namespaces/ts.js";
import * as vpath from "./_namespaces/vpath.js";
/**
* Posix-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.)
*/
export const builtFolder = "/.ts";
/**
* Posix-style path to additional mountable folders (./tests/projects in this repo)
*/
export const projectsFolder = "/.projects";
/**
* Posix-style path to additional test libraries
*/
export const testLibFolder = "/.lib";
/**
* Posix-style path to sources under test
*/
export const srcFolder = "/.src";
// file type
const S_IFMT = 0o170000; // file type
const S_IFSOCK = 0o140000; // socket
const S_IFLNK = 0o120000; // symbolic link
const S_IFREG = 0o100000; // regular file
const S_IFBLK = 0o060000; // block device
const S_IFDIR = 0o040000; // directory
const S_IFCHR = 0o020000; // character device
const S_IFIFO = 0o010000; // FIFO
let devCount = 0; // A monotonically increasing count of device ids
let inoCount = 0; // A monotonically increasing count of inodes
export interface DiffOptions {
includeChangedFileWithSameContent?: boolean;
baseIsNotShadowRoot?: boolean;
}
export const timeIncrements = 1000;
/**
* Represents a virtual POSIX-like file system.
*/
export class FileSystem {
/** Indicates whether the file system is case-sensitive (`false`) or case-insensitive (`true`). */
public readonly ignoreCase: boolean;
/** Gets the comparison function used to compare two paths. */
public readonly stringComparer: (a: string, b: string) => number;
// lazy-initialized state that should be mutable even if the FileSystem is frozen.
private _lazy: {
links?: collections.SortedMap<string, Inode>;
shadows?: Map<number, Inode>;
meta?: collections.Metadata;
} = {};
private _cwd: string; // current working directory
private _time: number;
private _shadowRoot: FileSystem | undefined;
private _dirStack: string[] | undefined;
constructor(ignoreCase: boolean, options: FileSystemOptions = {}) {
const { time = timeIncrements, files, meta } = options;
this.ignoreCase = ignoreCase;
this.stringComparer = this.ignoreCase ? vpath.compareCaseInsensitive : vpath.compareCaseSensitive;
this._time = time;
if (meta) {
for (const key of Object.keys(meta)) {
this.meta.set(key, meta[key]);
}
}
if (files) {
this._applyFiles(files, /*dirname*/ "");
}
let cwd = options.cwd;
if ((!cwd || !vpath.isRoot(cwd)) && this._lazy.links) {
for (const name of this._lazy.links.keys()) {
cwd = cwd ? vpath.resolve(name, cwd) : name;
break;
}
}
if (cwd) {
vpath.validate(cwd, vpath.ValidationFlags.Absolute);
this.mkdirpSync(cwd);
}
this._cwd = cwd || "";
}
/**
* Gets metadata for this `FileSystem`.
*/
public get meta(): collections.Metadata {
if (!this._lazy.meta) {
this._lazy.meta = new collections.Metadata(this._shadowRoot ? this._shadowRoot.meta : undefined);
}
return this._lazy.meta;
}
/**
* Gets a value indicating whether the file system is read-only.
*/
public get isReadonly(): boolean {
return Object.isFrozen(this);
}
/**
* Makes the file system read-only.
*/
public makeReadonly(): this {
Object.freeze(this);
return this;
}
/**
* Gets the file system shadowed by this file system.
*/
public get shadowRoot(): FileSystem | undefined {
return this._shadowRoot;
}
/**
* Snapshots the current file system, effectively shadowing itself. This is useful for
* generating file system patches using `.diff()` from one snapshot to the next. Performs
* no action if this file system is read-only.
*/
public snapshot(): void {
if (this.isReadonly) return;
const fs = new FileSystem(this.ignoreCase, { time: this._time });
fs._lazy = this._lazy;
fs._cwd = this._cwd;
fs._time = this._time;
fs._shadowRoot = this._shadowRoot;
fs._dirStack = this._dirStack;
fs.makeReadonly();
this._lazy = {};
this._shadowRoot = fs;
}
/**
* Gets a shadow copy of this file system. Changes to the shadow copy do not affect the
* original, allowing multiple copies of the same core file system without multiple copies
* of the same data.
*/
public shadow(ignoreCase: boolean = this.ignoreCase): FileSystem {
if (!this.isReadonly) throw new Error("Cannot shadow a mutable file system.");
if (ignoreCase && !this.ignoreCase) throw new Error("Cannot create a case-insensitive file system from a case-sensitive one.");
const fs = new FileSystem(ignoreCase, { time: this._time });
fs._shadowRoot = this;
fs._cwd = this._cwd;
return fs;
}
/**
* Gets or sets the timestamp (in milliseconds) used for file status, returning the previous timestamp.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html
*/
public time(value?: number): number {
if (value !== undefined) {
if (this.isReadonly) throw createIOError("EPERM");
this._time = value;
}
else if (!this.isReadonly) {
this._time += timeIncrements;
}
return this._time;
}
/**
* Gets the metadata object for a path.
* @param path
*/
public filemeta(path: string): collections.Metadata {
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
return this._filemeta(node);
}
private _filemeta(node: Inode): collections.Metadata {
if (!node.meta) {
const parentMeta = node.shadowRoot && this._shadowRoot && this._shadowRoot._filemeta(node.shadowRoot);
node.meta = new collections.Metadata(parentMeta);
}
return node.meta;
}
/**
* Get the pathname of the current working directory.
*
* @link - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
*/
public cwd(): string {
if (!this._cwd) throw new Error("The current working directory has not been set.");
const { node } = this._walk(this._cwd);
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
return this._cwd;
}
/**
* Changes the current working directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html
*/
public chdir(path: string): void {
if (this.isReadonly) throw createIOError("EPERM");
path = this._resolve(path);
const { node } = this._walk(path);
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
this._cwd = path;
}
/**
* Pushes the current directory onto the directory stack and changes the current working directory to the supplied path.
*/
public pushd(path?: string): void {
if (this.isReadonly) throw createIOError("EPERM");
if (path) path = this._resolve(path);
if (this._cwd) {
if (!this._dirStack) this._dirStack = [];
this._dirStack.push(this._cwd);
}
if (path && path !== this._cwd) {
this.chdir(path);
}
}
/**
* Pops the previous directory from the location stack and changes the current directory to that directory.
*/
public popd(): void {
if (this.isReadonly) throw createIOError("EPERM");
const path = this._dirStack && this._dirStack.pop();
if (path) {
this.chdir(path);
}
}
/**
* Update the file system with a set of files.
*/
public apply(files: FileSet): void {
this._applyFiles(files, this._cwd);
}
/**
* Scan file system entries along a path. If `path` is a symbolic link, it is dereferenced.
* @param path The path at which to start the scan.
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public scanSync(path: string, axis: Axis, traversal: Traversal): string[] {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path)), axis, traversal, /*noFollow*/ false, results);
return results;
}
/**
* Scan file system entries along a path.
* @param path The path at which to start the scan.
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public lscanSync(path: string, axis: Axis, traversal: Traversal): string[] {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path, /*noFollow*/ true)), axis, traversal, /*noFollow*/ true, results);
return results;
}
private _scan(path: string, stats: Stats, axis: Axis, traversal: Traversal, noFollow: boolean, results: string[]) {
if (axis === "ancestors-or-self" || axis === "self" || axis === "descendants-or-self") {
if (!traversal.accept || traversal.accept(path, stats)) {
results.push(path);
}
}
if (axis === "ancestors-or-self" || axis === "ancestors") {
const dirname = vpath.dirname(path);
if (dirname !== path) {
try {
const stats = this._stat(this._walk(dirname, noFollow));
if (!traversal.traverse || traversal.traverse(dirname, stats)) {
this._scan(dirname, stats, "ancestors-or-self", traversal, noFollow, results);
}
}
catch { /*ignored*/ }
}
}
if (axis === "descendants-or-self" || axis === "descendants") {
if (stats.isDirectory() && (!traversal.traverse || traversal.traverse(path, stats))) {
for (const file of this.readdirSync(path)) {
try {
const childpath = vpath.combine(path, file);
const stats = this._stat(this._walk(childpath, noFollow));
this._scan(childpath, stats, "descendants-or-self", traversal, noFollow, results);
}
catch { /*ignored*/ }
}
}
}
}
/**
* Mounts a physical or virtual file system at a location in this virtual file system.
*
* @param source The path in the physical (or other virtual) file system.
* @param target The path in this virtual file system.
* @param resolver An object used to resolve files in `source`.
*/
public mountSync(source: string, target: string, resolver: FileSystemResolver): void {
if (this.isReadonly) throw createIOError("EROFS");
source = vpath.validate(source, vpath.ValidationFlags.Absolute);
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(target), /*noFollow*/ true);
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent ? parent.dev : ++devCount, S_IFDIR, /*mode*/ 0o777, time);
node.source = source;
node.resolver = resolver;
this._addLink(parent, links, basename, node, time);
}
/**
* Recursively remove all files and directories underneath the provided path.
*/
public rimrafSync(path: string): void {
try {
const stats = this.lstatSync(path);
if (stats.isFile() || stats.isSymbolicLink()) {
this.unlinkSync(path);
}
else if (stats.isDirectory()) {
for (const file of this.readdirSync(path)) {
this.rimrafSync(vpath.combine(path, file));
}
this.rmdirSync(path);
}
}
catch (e) {
if (e.code === "ENOENT") return;
throw e;
}
}
/**
* Make a directory and all of its parent paths (if they don't exist).
*/
public mkdirpSync(path: string): void {
path = this._resolve(path);
const result = this._walk(path, /*noFollow*/ true, (error, result) => {
if (error.code === "ENOENT") {
this._mkdir(result);
return "retry";
}
return "throw";
});
if (!result.node) this._mkdir(result);
}
public getFileListing(): string {
let result = "";
const printLinks = (dirname: string | undefined, links: collections.SortedMap<string, Inode>) => {
for (const [name, node] of links) {
const path = dirname ? vpath.combine(dirname, name) : name;
const marker = vpath.compare(this._cwd, path, this.ignoreCase) === 0 ? "*" : " ";
if (result) result += "\n";
result += marker;
if (isDirectory(node)) {
result += vpath.addTrailingSeparator(path);
printLinks(path, this._getLinks(node));
}
else if (isFile(node)) {
result += path;
}
else if (isSymlink(node)) {
result += path + " -> " + node.symlink;
}
}
};
printLinks(/*dirname*/ undefined, this._getRootLinks());
return result;
}
/**
* Print diagnostic information about the structure of the file system to the console.
*/
public debugPrint(): void {
console.log(this.getFileListing());
}
// POSIX API (aligns with NodeJS "fs" module API)
/**
* Determines whether a path exists.
*/
public existsSync(path: string): boolean {
const result = this._walk(this._resolve(path), /*noFollow*/ true, () => "stop");
return result !== undefined && result.node !== undefined;
}
/**
* Get file status. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public statSync(path: string): Stats {
return this._stat(this._walk(this._resolve(path)));
}
/**
* Change file access times
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public utimesSync(path: string, atime: Date, mtime: Date): void {
if (this.isReadonly) throw createIOError("EROFS");
if (!isFinite(+atime) || !isFinite(+mtime)) throw createIOError("EINVAL");
const entry = this._walk(this._resolve(path));
if (!entry || !entry.node) {
throw createIOError("ENOENT");
}
entry.node.atimeMs = +atime;
entry.node.mtimeMs = +mtime;
entry.node.ctimeMs = this.time();
}
/**
* Get file status. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/lstat.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public lstatSync(path: string): Stats {
return this._stat(this._walk(this._resolve(path), /*noFollow*/ true));
}
private _stat(entry: WalkResult) {
const node = entry.node;
if (!node) throw createIOError(`ENOENT`, entry.realpath);
return new Stats(
node.dev,
node.ino,
node.mode,
node.nlink,
/*rdev*/ 0,
/*size*/ isFile(node) ? this._getSize(node) : isSymlink(node) ? node.symlink.length : 0,
/*blksize*/ 4096,
/*blocks*/ 0,
node.atimeMs,
node.mtimeMs,
node.ctimeMs,
node.birthtimeMs,
);
}
/**
* Read a directory. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readdirSync(path: string): string[] {
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
return ts.arrayFrom(this._getLinks(node).keys());
}
/**
* Make a directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public mkdirSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
this._mkdir(this._walk(this._resolve(path), /*noFollow*/ true));
}
private _mkdir({ parent, links, node: existingNode, basename }: WalkResult) {
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent ? parent.dev : ++devCount, S_IFDIR, /*mode*/ 0o777, time);
this._addLink(parent, links, basename, node, time);
}
/**
* Remove a directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/rmdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public rmdirSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
path = this._resolve(path);
const { parent, links, node, basename } = this._walk(path, /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
if (this._getLinks(node).size !== 0) throw createIOError("ENOTEMPTY");
this._removeLink(parent, links, basename, node);
}
/**
* Link one file to another file (also known as a "hard link").
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public linkSync(oldpath: string, newpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { node } = this._walk(this._resolve(oldpath));
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EPERM");
const { parent, links, basename, node: existingNode } = this._walk(this._resolve(newpath), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (existingNode) throw createIOError("EEXIST");
this._addLink(parent, links, basename, node);
}
/**
* Remove a directory entry.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/unlink.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public unlinkSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node, basename } = this._walk(this._resolve(path), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EISDIR");
this._removeLink(parent, links, basename, node);
}
/**
* Rename a file.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public renameSync(oldpath: string, newpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent: oldParent, links: oldParentLinks, node, basename: oldBasename } = this._walk(this._resolve(oldpath), /*noFollow*/ true);
if (!oldParent) throw createIOError("EPERM");
if (!node) throw createIOError("ENOENT");
const { parent: newParent, links: newParentLinks, node: existingNode, basename: newBasename } = this._walk(this._resolve(newpath), /*noFollow*/ true);
if (!newParent) throw createIOError("EPERM");
const time = this.time();
if (existingNode) {
if (isDirectory(node)) {
if (!isDirectory(existingNode)) throw createIOError("ENOTDIR");
// if both old and new arguments point to the same directory, just pass. So we could rename /src/a/1 to /src/A/1 in Win.
// if not and the directory pointed by the new path is not empty, throw an error.
if (this.stringComparer(oldpath, newpath) !== 0 && this._getLinks(existingNode).size > 0) throw createIOError("ENOTEMPTY");
}
else {
if (isDirectory(existingNode)) throw createIOError("EISDIR");
}
this._removeLink(newParent, newParentLinks, newBasename, existingNode, time);
}
this._replaceLink(oldParent, oldParentLinks, oldBasename, newParent, newParentLinks, newBasename, node, time);
}
/**
* Make a symbolic link.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/symlink.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public symlinkSync(target: string, linkpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(linkpath), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent.dev, S_IFLNK, /*mode*/ 0o666, time);
node.symlink = vpath.validate(target, vpath.ValidationFlags.RelativeOrAbsolute);
this._addLink(parent, links, basename, node, time);
}
/**
* Resolve a pathname.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public realpathSync(path: string): string {
const { realpath } = this._walk(this._resolve(path));
return realpath;
}
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding?: null): Buffer; // eslint-disable-line no-restricted-syntax
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding: BufferEncoding): string;
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer; // eslint-disable-line no-restricted-syntax
public readFileSync(path: string, encoding: BufferEncoding | null = null) { // eslint-disable-line no-restricted-syntax
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EISDIR");
if (!isFile(node)) throw createIOError("EBADF");
const fileBuffer = this._getBuffer(node, encoding ?? undefined);
return !fileBuffer.encoding ? fileBuffer.data.slice() : fileBuffer.data;
}
/**
* Write to a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
// eslint-disable-next-line no-restricted-syntax
public writeFileSync(path: string, data: string | Buffer, encoding: string | null = null): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(path), /*noFollow*/ false);
if (!parent) throw createIOError("EPERM");
const time = this.time();
let node = existingNode;
if (!node) {
node = this._mknod(parent.dev, S_IFREG, 0o666, time);
this._addLink(parent, links, basename, node, time);
}
if (isDirectory(node)) throw createIOError("EISDIR");
if (!isFile(node)) throw createIOError("EBADF");
node.buffer = Buffer.isBuffer(data) ?
{ encoding: undefined, data: data.slice() } :
{ encoding: (encoding ?? "utf8") as BufferEncoding, data };
// Updated the size if it's easy to get, otherwise set to undefined. _getSize will compute the correct size
node.size = !node.buffer.encoding ? node.buffer.data.byteLength : undefined;
node.mtimeMs = time;
node.ctimeMs = time;
}
/**
* Generates a `FileSet` patch containing all the entries in this `FileSystem` that are not in `base`.
* @param base The base file system. If not provided, this file system's `shadowRoot` is used (if present).
*/
public diff(base?: FileSystem | undefined, options: DiffOptions = {}): FileSet | undefined {
if (!base && !options.baseIsNotShadowRoot) base = this.shadowRoot;
const differences: FileSet = {};
const hasDifferences = base ?
FileSystem.rootDiff(differences, this, base, options) :
FileSystem.trackCreatedInodes(differences, this, this._getRootLinks());
return hasDifferences ? differences : undefined;
}
public static defaultEncoding: BufferEncoding | undefined = "utf8";
/**
* Generates a `FileSet` patch containing all the entries in `changed` that are not in `base`.
*/
public static diff(changed: FileSystem, base: FileSystem, options: DiffOptions = {}): FileSet | undefined {
const differences: FileSet = {};
return FileSystem.rootDiff(differences, changed, base, options) ?
differences :
undefined;
}
private static diffWorker(container: FileSet, changed: FileSystem, changedLinks: ReadonlyMap<string, Inode> | undefined, base: FileSystem, baseLinks: ReadonlyMap<string, Inode> | undefined, options: DiffOptions) {
if (changedLinks && !baseLinks) return FileSystem.trackCreatedInodes(container, changed, changedLinks);
if (baseLinks && !changedLinks) return FileSystem.trackDeletedInodes(container, baseLinks);
if (changedLinks && baseLinks) {
let hasChanges = false;
// track base items missing in changed
baseLinks.forEach((node, basename) => {
if (!changedLinks.has(basename)) {
container[basename] = isDirectory(node) ? new Rmdir() : new Unlink();
hasChanges = true;
}
});
// track changed items missing or differing in base
changedLinks.forEach((changedNode, basename) => {
const baseNode = baseLinks.get(basename);
if (baseNode) {
if (isDirectory(changedNode) && isDirectory(baseNode)) {
return hasChanges = FileSystem.directoryDiff(container, basename, changed, changedNode, base, baseNode, options) || hasChanges;
}
if (isFile(changedNode) && isFile(baseNode)) {
return hasChanges = FileSystem.fileDiff(container, basename, changed, changedNode, base, baseNode, options) || hasChanges;
}
if (isSymlink(changedNode) && isSymlink(baseNode)) {
return hasChanges = FileSystem.symlinkDiff(container, basename, changedNode, baseNode) || hasChanges;
}
}
return hasChanges = FileSystem.trackCreatedInode(container, basename, changed, changedNode) || hasChanges;
});
return hasChanges;
}
return false;
}
private static rootDiff(container: FileSet, changed: FileSystem, base: FileSystem, options: DiffOptions) {
while (!changed._lazy.links && changed._shadowRoot) changed = changed._shadowRoot;
while (!base._lazy.links && base._shadowRoot) base = base._shadowRoot;
// no difference if the file systems are the same reference
if (changed === base) return false;
// no difference if the root links are empty and unshadowed
if (!changed._lazy.links && !changed._shadowRoot && !base._lazy.links && !base._shadowRoot) return false;
return FileSystem.diffWorker(container, changed, changed._getRootLinks(), base, base._getRootLinks(), options);
}
private static directoryDiff(container: FileSet, basename: string, changed: FileSystem, changedNode: DirectoryInode, base: FileSystem, baseNode: DirectoryInode, options: DiffOptions) {
while (!changedNode.links && changedNode.shadowRoot) changedNode = changedNode.shadowRoot;
while (!baseNode.links && baseNode.shadowRoot) baseNode = baseNode.shadowRoot;
// no difference if the nodes are the same reference
if (changedNode === baseNode) return false;
// no difference if both nodes are non shadowed and have no entries
if (isEmptyNonShadowedDirectory(changedNode) && isEmptyNonShadowedDirectory(baseNode)) return false;
// no difference if both nodes are unpopulated and point to the same mounted file system
if (
!changedNode.links && !baseNode.links &&
changedNode.resolver && changedNode.source !== undefined &&
baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source
) return false;
// no difference if both nodes have identical children
const children: FileSet = {};
if (!FileSystem.diffWorker(children, changed, changed._getLinks(changedNode), base, base._getLinks(baseNode), options)) {
return false;
}
container[basename] = new Directory(children);
return true;
}
private static fileDiff(container: FileSet, basename: string, changed: FileSystem, changedNode: FileInode, base: FileSystem, baseNode: FileInode, options: DiffOptions) {
changedNode = walkSameNodes(changedNode);
baseNode = walkSameNodes(baseNode);
// no difference if the nodes are the same reference
if (changedNode === baseNode) return false;
// no difference if both nodes are non shadowed and have no entries
if (isEmptyNonShadowedFile(changedNode) && isEmptyNonShadowedFile(baseNode)) return false;
// no difference if both nodes are unpopulated and point to the same mounted file system
if (
!changedNode.buffer && !baseNode.buffer &&
changedNode.resolver && changedNode.source !== undefined &&
baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source
) return false;
const encoding = changedNode.buffer?.encoding ?? baseNode.buffer?.encoding ?? FileSystem.defaultEncoding;
const changedBuffer = changed._getBuffer(changedNode, encoding);
const baseBuffer = base._getBuffer(baseNode, encoding);
// no difference if both buffers are the same reference
if (changedBuffer === baseBuffer) {
if (!options.includeChangedFileWithSameContent || changedNode.mtimeMs === baseNode.mtimeMs) return false;
container[basename] = new SameFileWithModifiedTime(changedBuffer.data, { encoding: changedBuffer.encoding });
return true;
}
// no difference if both buffers are identical
if (
!changedBuffer.encoding && !baseBuffer.encoding && Buffer.compare(changedBuffer.data, baseBuffer.data) === 0 // same buffer content
|| changedBuffer.encoding === baseBuffer.encoding && changedBuffer.data === baseBuffer.data // same string content
) {
if (!options.includeChangedFileWithSameContent) return false;
container[basename] = new SameFileContentFile(changedBuffer.data, { encoding: changedBuffer.encoding });
return true;
}
container[basename] = new File(changedBuffer.data, { encoding: changedBuffer.encoding });
return true;
function walkSameNodes(node: FileInode) {
while (
!node.buffer &&
node.shadowRoot &&
(!options.includeChangedFileWithSameContent || node.mtimeMs === node.shadowRoot.mtimeMs)
) node = node.shadowRoot;
return node;
}
}
private static symlinkDiff(container: FileSet, basename: string, changedNode: SymlinkInode, baseNode: SymlinkInode) {
// no difference if the nodes are the same reference
if (changedNode.symlink === baseNode.symlink) return false;
container[basename] = new Symlink(changedNode.symlink);
return true;
}
private static trackCreatedInode(container: FileSet, basename: string, changed: FileSystem, node: Inode) {
if (isDirectory(node)) {
const children: FileSet = {};
FileSystem.trackCreatedInodes(children, changed, changed._getLinks(node));
container[basename] = new Directory(children);
}
else if (isSymlink(node)) {
container[basename] = new Symlink(node.symlink);
}
else {
const buffer = changed._getBuffer(node, FileSystem.defaultEncoding);
container[basename] = new File(buffer.data, { encoding: buffer.encoding ?? undefined });
}
return true;
}
private static trackCreatedInodes(container: FileSet, changed: FileSystem, changedLinks: ReadonlyMap<string, Inode>) {
// no difference if links are empty
if (!changedLinks.size) return false;
changedLinks.forEach((node, basename) => {
FileSystem.trackCreatedInode(container, basename, changed, node);
});
return true;
}
private static trackDeletedInodes(container: FileSet, baseLinks: ReadonlyMap<string, Inode>) {
// no difference if links are empty
if (!baseLinks.size) return false;
baseLinks.forEach((node, basename) => {
container[basename] = isDirectory(node) ? new Rmdir() : new Unlink();
});
return true;
}
private _mknod(dev: number, type: typeof S_IFREG, mode: number, time?: number): FileInode;
private _mknod(dev: number, type: typeof S_IFDIR, mode: number, time?: number): DirectoryInode;
private _mknod(dev: number, type: typeof S_IFLNK, mode: number, time?: number): SymlinkInode;
private _mknod(dev: number, type: number, mode: number, time = this.time()): Inode {
return {
dev,
ino: ++inoCount,
mode: (mode & ~S_IFMT & ~0o022 & 0o7777) | (type & S_IFMT),
atimeMs: time,
mtimeMs: time,
ctimeMs: time,
birthtimeMs: time,
nlink: 0,
};
}
private _addLink(parent: DirectoryInode | undefined, links: collections.SortedMap<string, Inode>, name: string, node: Inode, time = this.time()) {
links.set(name, node);
node.nlink++;
node.ctimeMs = time;
if (parent) parent.mtimeMs = time;
if (!parent && !this._cwd) this._cwd = name;
}
private _removeLink(parent: DirectoryInode | undefined, links: collections.SortedMap<string, Inode>, name: string, node: Inode, time = this.time()) {
links.delete(name);
node.nlink--;
node.ctimeMs = time;
if (parent) parent.mtimeMs = time;
}
private _replaceLink(oldParent: DirectoryInode, oldLinks: collections.SortedMap<string, Inode>, oldName: string, newParent: DirectoryInode, newLinks: collections.SortedMap<string, Inode>, newName: string, node: Inode, time: number) {
if (oldParent !== newParent) {
this._removeLink(oldParent, oldLinks, oldName, node, time);
this._addLink(newParent, newLinks, newName, node, time);
}
else {
oldLinks.delete(oldName);
oldLinks.set(newName, node);
oldParent.mtimeMs = time;
newParent.mtimeMs = time;
}
}
private _getRootLinks() {
if (!this._lazy.links) {
this._lazy.links = new collections.SortedMap<string, Inode>(this.stringComparer);
if (this._shadowRoot) {
this._copyShadowLinks(this._shadowRoot._getRootLinks(), this._lazy.links);
}
}
return this._lazy.links;
}
private _getLinks(node: DirectoryInode) {
if (!node.links) {
const links = new collections.SortedMap<string, Inode>(this.stringComparer);
const { source, resolver } = node;
if (source && resolver) {
node.source = undefined;
node.resolver = undefined;
for (const name of resolver.readdirSync(source)) {
const path = vpath.combine(source, name);
const stats = resolver.statSync(path);
switch (stats.mode & S_IFMT) {
case S_IFDIR:
const dir = this._mknod(node.dev, S_IFDIR, 0o777);
dir.source = vpath.combine(source, name);
dir.resolver = resolver;
this._addLink(node, links, name, dir);
break;
case S_IFREG:
const file = this._mknod(node.dev, S_IFREG, 0o666);
file.source = vpath.combine(source, name);
file.resolver = resolver;
file.size = stats.size;
this._addLink(node, links, name, file);
break;
}
}
}
else if (this._shadowRoot && node.shadowRoot) {
this._copyShadowLinks(this._shadowRoot._getLinks(node.shadowRoot), links);
}
node.links = links;
}
return node.links;
}
private _getShadow(root: DirectoryInode): DirectoryInode;
private _getShadow(root: Inode): Inode;
private _getShadow(root: Inode) {
const shadows = this._lazy.shadows || (this._lazy.shadows = new Map<number, Inode>());
let shadow = shadows.get(root.ino);
if (!shadow) {
shadow = {
dev: root.dev,
ino: root.ino,
mode: root.mode,
atimeMs: root.atimeMs,
mtimeMs: root.mtimeMs,
ctimeMs: root.ctimeMs,
birthtimeMs: root.birthtimeMs,
nlink: root.nlink,
shadowRoot: root,
};
if (isSymlink(root)) (shadow as SymlinkInode).symlink = root.symlink;
shadows.set(shadow.ino, shadow);
}
return shadow;
}
private _copyShadowLinks(source: ReadonlyMap<string, Inode>, target: collections.SortedMap<string, Inode>) {
for (const [name, root] of source) {
target.set(name, this._getShadow(root));