forked from tschaub/mock-fs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinding.js
More file actions
1292 lines (1183 loc) · 38.4 KB
/
Copy pathbinding.js
File metadata and controls
1292 lines (1183 loc) · 38.4 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
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
'use strict';
const path = require('path');
const File = require('./file');
const FileDescriptor = require('./descriptor');
const Directory = require('./directory');
const SymbolicLink = require('./symlink');
const {FSError} = require('./error');
const constants = require('constants');
const getPathParts = require('./filesystem').getPathParts;
const MODE_TO_KTYPE = {
[constants.S_IFREG]: constants.UV_DIRENT_FILE,
[constants.S_IFDIR]: constants.UV_DIRENT_DIR,
[constants.S_IFBLK]: constants.UV_DIRENT_BLOCK,
[constants.S_IFCHR]: constants.UV_DIRENT_CHAR,
[constants.S_IFLNK]: constants.UV_DIRENT_LINK,
[constants.S_IFIFO]: constants.UV_DIRENT_FIFO,
[constants.S_IFSOCK]: constants.UV_DIRENT_SOCKET
};
/** Workaround for optimizations in node 8+ */
const fsBinding = process.binding('fs');
const kUsePromises = fsBinding.kUsePromises;
let statValues;
let bigintStatValues;
if (fsBinding.statValues) {
statValues = fsBinding.statValues; // node 10+
bigintStatValues = fsBinding.bigintStatValues;
}
const MAX_LINKS = 50;
/**
* Call the provided function and either return the result or call the callback
* with it (depending on if a callback is provided).
* @param {function()} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @param {Object} thisArg This argument for the following function.
* @param {function()} func Function to call.
* @return {*} Return (if callback is not provided).
*/
function maybeCallback(callback, ctx, thisArg, func) {
let err = null;
let val;
if (kUsePromises && callback === kUsePromises) {
// support nodejs v10+ fs.promises
try {
val = func.call(thisArg);
} catch (e) {
err = e;
}
return new Promise(function(resolve, reject) {
process.nextTick(function() {
if (err) {
reject(err);
} else {
resolve(val);
}
});
});
} else if (callback && typeof callback === 'function') {
try {
val = func.call(thisArg);
} catch (e) {
err = e;
}
process.nextTick(function() {
if (val === undefined) {
callback(err);
} else {
callback(err, val);
}
});
} else if (ctx && typeof ctx === 'object') {
try {
return func.call(thisArg);
} catch (e) {
// default to errno for UNKNOWN
ctx.code = e.code || 'UNKNOWN';
ctx.errno = e.errno || FSError.codes.UNKNOWN.errno;
}
} else {
return func.call(thisArg);
}
}
/**
* set syscall property on context object, only for nodejs v10+.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @param {String} syscall Name of syscall.
*/
function markSyscall(ctx, syscall) {
if (ctx && typeof ctx === 'object') {
ctx.syscall = syscall;
}
}
/**
* Handle FSReqWrap oncomplete.
* @param {Function} callback The callback.
* @return {Function} The normalized callback.
*/
function normalizeCallback(callback) {
if (callback && typeof callback.oncomplete === 'function') {
// Unpack callback from FSReqWrap
callback = callback.oncomplete.bind(callback);
}
return callback;
}
function getDirentType(mode) {
const ktype = MODE_TO_KTYPE[mode & constants.S_IFMT];
if (ktype === undefined) {
return constants.UV_DIRENT_UNKNOWN;
}
return ktype;
}
function notImplemented() {
throw new Error('Method not implemented');
}
function deBuffer(p) {
return Buffer.isBuffer(p) ? p.toString() : p;
}
/**
* Create a new binding with the given file system.
* @param {FileSystem} system Mock file system.
* @constructor
*/
function Binding(system) {
/**
* Mock file system.
* @type {FileSystem}
*/
this._system = system;
/**
* Lookup of open files.
* @type {Object.<number, FileDescriptor>}
*/
this._openFiles = {};
/**
* Counter for file descriptors.
* @type {number}
*/
this._counter = -1;
const stdin = new FileDescriptor(constants.O_RDWR);
stdin.setItem(new File.StandardInput());
this.trackDescriptor(stdin);
const stdout = new FileDescriptor(constants.O_RDWR);
stdout.setItem(new File.StandardOutput());
this.trackDescriptor(stdout);
const stderr = new FileDescriptor(constants.O_RDWR);
stderr.setItem(new File.StandardError());
this.trackDescriptor(stderr);
}
/**
* Get the file system underlying this binding.
* @return {FileSystem} The underlying file system.
*/
Binding.prototype.getSystem = function() {
return this._system;
};
/**
* Reset the file system underlying this binding.
* @param {FileSystem} system The new file system.
*/
Binding.prototype.setSystem = function(system) {
this._system = system;
};
/**
* Get a file descriptor.
* @param {number} fd File descriptor identifier.
* @return {FileDescriptor} File descriptor.
*/
Binding.prototype.getDescriptorById = function(fd) {
if (!this._openFiles.hasOwnProperty(fd)) {
throw new FSError('EBADF');
}
return this._openFiles[fd];
};
/**
* Keep track of a file descriptor as open.
* @param {FileDescriptor} descriptor The file descriptor.
* @return {number} Identifier for file descriptor.
*/
Binding.prototype.trackDescriptor = function(descriptor) {
const fd = ++this._counter;
this._openFiles[fd] = descriptor;
return fd;
};
/**
* Stop tracking a file descriptor as open.
* @param {number} fd Identifier for file descriptor.
*/
Binding.prototype.untrackDescriptorById = function(fd) {
if (!this._openFiles.hasOwnProperty(fd)) {
throw new FSError('EBADF');
}
delete this._openFiles[fd];
};
/**
* Resolve the canonicalized absolute pathname.
* @param {string|Buffer} filepath The file path.
* @param {string} encoding The encoding for the return.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {string|Buffer} The real path.
*/
Binding.prototype.realpath = function(filepath, encoding, callback, ctx) {
markSyscall(ctx, 'realpath');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
let realPath;
filepath = deBuffer(filepath);
const resolved = path.resolve(filepath);
const parts = getPathParts(resolved);
let item = this._system.getRoot();
let itemPath = '/';
let name, i, ii;
for (i = 0, ii = parts.length; i < ii; ++i) {
name = parts[i];
while (item instanceof SymbolicLink) {
itemPath = path.resolve(path.dirname(itemPath), item.getPath());
item = this._system.getItem(itemPath);
}
if (!item) {
throw new FSError('ENOENT', filepath);
}
if (item instanceof Directory) {
itemPath = path.resolve(itemPath, name);
item = item.getItem(name);
} else {
throw new FSError('ENOTDIR', filepath);
}
}
if (item) {
while (item instanceof SymbolicLink) {
itemPath = path.resolve(path.dirname(itemPath), item.getPath());
item = this._system.getItem(itemPath);
}
realPath = itemPath;
} else {
throw new FSError('ENOENT', filepath);
}
if (process.platform === 'win32' && realPath.startsWith('\\\\?\\')) {
// Remove win32 file namespace prefix \\?\
realPath = realPath.slice(4);
}
if (encoding === 'buffer') {
realPath = Buffer.from(realPath);
}
return realPath;
});
};
function fillStats(stats) {
const target = stats instanceof Float64Array ? statValues : bigintStatValues;
for (let i = 0; i < 36; i++) {
target[i] = stats[i];
}
}
/**
* Stat an item.
* @param {string} filepath Path.
* @param {function(Error, Float64Array|BigUint64Array)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Float64Array|BigUint64Array|undefined} Stats or undefined (if sync).
*/
Binding.prototype.stat = function(filepath, bigint, callback, ctx) {
markSyscall(ctx, 'stat');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
filepath = deBuffer(filepath);
let item = this._system.getItem(filepath);
if (item instanceof SymbolicLink) {
item = this._system.getItem(
path.resolve(path.dirname(filepath), item.getPath())
);
}
if (!item) {
throw new FSError('ENOENT', filepath);
}
const stats = item.getStats(bigint);
fillStats(stats);
return stats;
});
};
/**
* Stat an item.
* @param {number} fd File descriptor.
* @param {function(Error, Float64Array|BigUint64Array)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Float64Array|BigUint64Array|undefined} Stats or undefined (if sync).
*/
Binding.prototype.fstat = function(fd, bigint, callback, ctx) {
markSyscall(ctx, 'fstat');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
const item = descriptor.getItem();
const stats = item.getStats(bigint);
fillStats(stats);
return stats;
});
};
/**
* Close a file descriptor.
* @param {number} fd File descriptor.
* @param {function(Error)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.close = function(fd, callback, ctx) {
markSyscall(ctx, 'close');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
this.untrackDescriptorById(fd);
});
};
/**
* Open and possibly create a file.
* @param {string} pathname File path.
* @param {number} flags Flags.
* @param {number} mode Mode.
* @param {function(Error, string)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {string} File descriptor (if sync).
*/
Binding.prototype.open = function(pathname, flags, mode, callback, ctx) {
markSyscall(ctx, 'open');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
pathname = deBuffer(pathname);
const descriptor = new FileDescriptor(flags);
let item = this._system.getItem(pathname);
while (item instanceof SymbolicLink) {
item = this._system.getItem(
path.resolve(path.dirname(pathname), item.getPath())
);
}
if (descriptor.isExclusive() && item) {
throw new FSError('EEXIST', pathname);
}
if (descriptor.isCreate() && !item) {
const parent = this._system.getItem(path.dirname(pathname));
if (!parent) {
throw new FSError('ENOENT', pathname);
}
if (!(parent instanceof Directory)) {
throw new FSError('ENOTDIR', pathname);
}
item = new File();
if (mode) {
item.setMode(mode);
}
parent.addItem(path.basename(pathname), item);
}
if (descriptor.isRead()) {
if (!item) {
throw new FSError('ENOENT', pathname);
}
if (!item.canRead()) {
throw new FSError('EACCES', pathname);
}
}
if (descriptor.isWrite() && !item.canWrite()) {
throw new FSError('EACCES', pathname);
}
if (
item instanceof Directory &&
(descriptor.isTruncate() || descriptor.isAppend())
) {
throw new FSError('EISDIR', pathname);
}
if (descriptor.isTruncate()) {
if (!(item instanceof File)) {
throw new FSError('EBADF');
}
item.setContent('');
}
if (descriptor.isTruncate() || descriptor.isAppend()) {
descriptor.setPosition(item.getContent().length);
}
descriptor.setItem(item);
return this.trackDescriptor(descriptor);
});
};
/**
* Open a file handler. A new api in nodejs v10+ for fs.promises
* @param {string} pathname File path.
* @param {number} flags Flags.
* @param {number} mode Mode.
* @param {function} callback Callback (optional), expecting kUsePromises in nodejs v10+.
*/
Binding.prototype.openFileHandle = function(pathname, flags, mode, callback) {
const self = this;
return this.open(pathname, flags, mode, kUsePromises).then(function(fd) {
// nodejs v10+ fs.promises FileHandler constructor only ask these three properties.
return {
getAsyncId: notImplemented,
fd: fd,
close: function() {
return self.close(fd, kUsePromises);
}
};
});
};
/**
* Read from a file descriptor.
* @param {string} fd File descriptor.
* @param {Buffer} buffer Buffer that the contents will be written to.
* @param {number} offset Offset in the buffer to start writing to.
* @param {number} length Number of bytes to read.
* @param {?number} position Where to begin reading in the file. If null,
* data will be read from the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes read, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes read (if sync).
*/
Binding.prototype.read = function(
fd,
buffer,
offset,
length,
position,
callback,
ctx
) {
markSyscall(ctx, 'read');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
if (!descriptor.isRead()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (file instanceof Directory) {
throw new FSError('EISDIR');
}
if (!(file instanceof File)) {
// deleted or not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
const content = file.getContent();
const start = Math.min(position, content.length);
const end = Math.min(position + length, content.length);
const read = start < end ? content.copy(buffer, offset, start, end) : 0;
descriptor.setPosition(position + read);
return read;
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} src Source file.
* @param {string} dest Destination file.
* @param {number} flags Modifiers for copy operation.
* @param {function(Error)} callback Callback (optional) called
* with any error.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.copyFile = function(src, dest, flags, callback, ctx) {
markSyscall(ctx, 'copyfile');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
src = deBuffer(src);
dest = deBuffer(dest);
const srcFd = this.open(src, constants.O_RDONLY);
try {
const srcDescriptor = this.getDescriptorById(srcFd);
if (!srcDescriptor.isRead()) {
throw new FSError('EBADF');
}
const srcFile = srcDescriptor.getItem();
if (!(srcFile instanceof File)) {
throw new FSError('EBADF');
}
const srcContent = srcFile.getContent();
let destFlags =
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC;
if ((flags & constants.COPYFILE_EXCL) === constants.COPYFILE_EXCL) {
destFlags |= constants.O_EXCL;
}
const destFd = this.open(dest, destFlags);
try {
this.writeBuffer(destFd, srcContent, 0, srcContent.length, 0);
} finally {
this.close(destFd);
}
} finally {
this.close(srcFd);
}
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} fd File descriptor.
* @param {Array<Buffer>} buffers Array of buffers with contents to write.
* @param {?number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes written, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeBuffers = function(
fd,
buffers,
position,
callback,
ctx
) {
markSyscall(ctx, 'write');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
if (!descriptor.isWrite()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (!(file instanceof File)) {
// not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
let content = file.getContent();
const newContent = Buffer.concat(buffers);
const newLength = position + newContent.length;
if (content.length < newLength) {
const tempContent = Buffer.alloc(newLength);
content.copy(tempContent);
content = tempContent;
}
const written = newContent.copy(content, position);
file.setContent(content);
descriptor.setPosition(newLength);
return written;
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} fd File descriptor.
* @param {Buffer} buffer Buffer with contents to write.
* @param {number} offset Offset in the buffer to start writing from.
* @param {number} length Number of bytes to write.
* @param {?number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes written, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeBuffer = function(
fd,
buffer,
offset,
length,
position,
callback,
ctx
) {
markSyscall(ctx, 'write');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
if (!descriptor.isWrite()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (!(file instanceof File)) {
// not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
let content = file.getContent();
const newLength = position + length;
if (content.length < newLength) {
const newContent = Buffer.alloc(newLength);
content.copy(newContent);
content = newContent;
}
const sourceEnd = Math.min(offset + length, buffer.length);
const written = Buffer.from(buffer).copy(
content,
position,
offset,
sourceEnd
);
file.setContent(content);
descriptor.setPosition(newLength);
return written;
});
};
/**
* Write to a file descriptor given a string.
* @param {string} fd File descriptor.
* @param {string} string String with contents to write.
* @param {number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {string} encoding String encoding.
* @param {function(Error, number, string)} callback Callback (optional) called
* with any error, number of bytes written, and the string.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeString = function(
fd,
string,
position,
encoding,
callback,
ctx
) {
markSyscall(ctx, 'write');
const buffer = Buffer.from(string, encoding);
let wrapper;
if (callback && callback !== kUsePromises) {
if (callback.oncomplete) {
callback = callback.oncomplete.bind(callback);
}
wrapper = function(err, written, returned) {
callback(err, written, returned && string);
};
}
return this.writeBuffer(fd, buffer, 0, string.length, position, wrapper, ctx);
};
/**
* Rename a file.
* @param {string} oldPath Old pathname.
* @param {string} newPath New pathname.
* @param {function(Error)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {undefined}
*/
Binding.prototype.rename = function(oldPath, newPath, callback, ctx) {
markSyscall(ctx, 'rename');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
oldPath = deBuffer(oldPath);
newPath = deBuffer(newPath);
const oldItem = this._system.getItem(oldPath);
if (!oldItem) {
throw new FSError('ENOENT', oldPath);
}
const oldParent = this._system.getItem(path.dirname(oldPath));
const oldName = path.basename(oldPath);
const newItem = this._system.getItem(newPath);
const newParent = this._system.getItem(path.dirname(newPath));
const newName = path.basename(newPath);
if (newItem) {
// make sure they are the same type
if (oldItem instanceof File) {
if (newItem instanceof Directory) {
throw new FSError('EISDIR', newPath);
}
} else if (oldItem instanceof Directory) {
if (!(newItem instanceof Directory)) {
throw new FSError('ENOTDIR', newPath);
}
if (newItem.list().length > 0) {
throw new FSError('ENOTEMPTY', newPath);
}
}
newParent.removeItem(newName);
} else {
if (!newParent) {
throw new FSError('ENOENT', newPath);
}
if (!(newParent instanceof Directory)) {
throw new FSError('ENOTDIR', newPath);
}
}
oldParent.removeItem(oldName);
newParent.addItem(newName, oldItem);
});
};
/**
* Read a directory.
* @param {string} dirpath Path to directory.
* @param {string} encoding The encoding ('utf-8' or 'buffer').
* @param {boolean} withFileTypes whether or not to return fs.Dirent objects
* @param {function(Error, (Array.<string>|Array.<Buffer>)} callback Callback
* (optional) called with any error or array of items in the directory.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Array.<string>|Array.<Buffer>} Array of items in directory (if sync).
*/
Binding.prototype.readdir = function(
dirpath,
encoding,
withFileTypes,
callback,
ctx
) {
markSyscall(ctx, 'scandir');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
dirpath = deBuffer(dirpath);
let dpath = dirpath;
let dir = this._system.getItem(dirpath);
while (dir instanceof SymbolicLink) {
dpath = path.resolve(path.dirname(dpath), dir.getPath());
dir = this._system.getItem(dpath);
}
if (!dir) {
throw new FSError('ENOENT', dirpath);
}
if (!(dir instanceof Directory)) {
throw new FSError('ENOTDIR', dirpath);
}
if (!dir.canRead()) {
throw new FSError('EACCES', dirpath);
}
let list = dir.list();
if (encoding === 'buffer') {
list = list.map(function(item) {
return Buffer.from(item);
});
}
if (withFileTypes === true) {
const types = list.map(function(name) {
const stats = dir.getItem(name).getStats();
return getDirentType(stats.mode);
});
list = [list, types];
}
return list;
});
};
/**
* Create a directory.
* @param {string} pathname Path to new directory.
* @param {number} mode Permissions.
* @param {boolean} recursive Recursively create deep directory. (added in nodejs v10+)
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.mkdir = function(pathname, mode, recursive, callback, ctx) {
markSyscall(ctx, 'mkdir');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
pathname = deBuffer(pathname);
const item = this._system.getItem(pathname);
if (item) {
if (recursive && item instanceof Directory) {
// silently pass existing folder in recursive mode
return;
}
throw new FSError('EEXIST', pathname);
}
const _mkdir = function(_pathname) {
const parentDir = path.dirname(_pathname);
let parent = this._system.getItem(parentDir);
if (!parent) {
if (!recursive) {
throw new FSError('ENOENT', _pathname);
}
parent = _mkdir(parentDir, true);
}
this.access(parentDir, parseInt('0002', 8));
const dir = new Directory();
if (mode) {
dir.setMode(mode);
}
return parent.addItem(path.basename(_pathname), dir);
}.bind(this);
_mkdir(pathname);
});
};
/**
* Remove a directory.
* @param {string} pathname Path to directory.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.rmdir = function(pathname, callback, ctx) {
markSyscall(ctx, 'rmdir');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
pathname = deBuffer(pathname);
const item = this._system.getItem(pathname);
if (!item) {
throw new FSError('ENOENT', pathname);
}
if (!(item instanceof Directory)) {
throw new FSError('ENOTDIR', pathname);
}
if (item.list().length > 0) {
throw new FSError('ENOTEMPTY', pathname);
}
this.access(path.dirname(pathname), parseInt('0002', 8));
const parent = this._system.getItem(path.dirname(pathname));
parent.removeItem(path.basename(pathname));
});
};
const PATH_CHARS =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const MAX_ATTEMPTS = 62 * 62 * 62;
/**
* Create a directory based on a template.
* See http://web.mit.edu/freebsd/head/lib/libc/stdio/mktemp.c
* @param {string} template Path template (trailing Xs will be replaced).
* @param {string} encoding The encoding ('utf-8' or 'buffer').
* @param {function(Error, string)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.mkdtemp = function(prefix, encoding, callback, ctx) {
if (encoding && typeof encoding !== 'string') {
callback = encoding;
encoding = 'utf-8';
}
markSyscall(ctx, 'mkdtemp');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
prefix = prefix.replace(/X{0,6}$/, 'XXXXXX');
const parentPath = path.dirname(prefix);
const parent = this._system.getItem(parentPath);
if (!parent) {
throw new FSError('ENOENT', prefix);
}
if (!(parent instanceof Directory)) {
throw new FSError('ENOTDIR', prefix);
}
this.access(parentPath, parseInt('0002', 8));
const template = path.basename(prefix);
let unique = false;
let count = 0;
let name;
while (!unique && count < MAX_ATTEMPTS) {
let position = template.length - 1;
let replacement = '';
while (template.charAt(position) === 'X') {
replacement += PATH_CHARS.charAt(
Math.floor(PATH_CHARS.length * Math.random())
);
position -= 1;
}
const candidate = template.slice(0, position + 1) + replacement;
if (!parent.getItem(candidate)) {
name = candidate;
unique = true;
}
count += 1;
}
if (!name) {
throw new FSError('EEXIST', prefix);
}
const dir = new Directory();
parent.addItem(name, dir);
let uniquePath = path.join(parentPath, name);
if (encoding === 'buffer') {
uniquePath = Buffer.from(uniquePath);
}
return uniquePath;
});
};
/**
* Truncate a file.
* @param {number} fd File descriptor.
* @param {number} len Number of bytes.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.ftruncate = function(fd, len, callback, ctx) {
markSyscall(ctx, 'ftruncate');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
if (!descriptor.isWrite()) {
throw new FSError('EINVAL');
}
const file = descriptor.getItem();
if (!(file instanceof File)) {
throw new FSError('EINVAL');
}
const content = file.getContent();
const newContent = Buffer.alloc(len);
content.copy(newContent);
file.setContent(newContent);
});
};
/**
* Legacy support.
* @param {number} fd File descriptor.
* @param {number} len Number of bytes.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.truncate = Binding.prototype.ftruncate;
/**
* Change user and group owner.
* @param {string} pathname Path.
* @param {number} uid User id.
* @param {number} gid Group id.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.chown = function(pathname, uid, gid, callback, ctx) {
markSyscall(ctx, 'chown');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
pathname = deBuffer(pathname);
const item = this._system.getItem(pathname);
if (!item) {
throw new FSError('ENOENT', pathname);
}
item.setUid(uid);
item.setGid(gid);
});
};
/**
* Change user and group owner.
* @param {number} fd File descriptor.
* @param {number} uid User id.
* @param {number} gid Group id.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.fchown = function(fd, uid, gid, callback, ctx) {
markSyscall(ctx, 'fchown');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = this.getDescriptorById(fd);
const item = descriptor.getItem();
item.setUid(uid);
item.setGid(gid);
});
};
/**
* Change permissions.
* @param {string} pathname Path.
* @param {number} mode Mode.
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.chmod = function(pathname, mode, callback, ctx) {
markSyscall(ctx, 'chmod');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
pathname = deBuffer(pathname);