-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
2830 lines (2658 loc) · 77.2 KB
/
index.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 { LRUCache } from 'lru-cache'
import { posix, win32 } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
lstatSync,
readdir as readdirCB,
readdirSync,
readlinkSync,
realpathSync as rps,
} from 'fs'
import * as actualFS from 'node:fs'
const realpathSync = rps.native
// TODO: test perf of fs/promises realpath vs realpathCB,
// since the promises one uses realpath.native
import { lstat, readdir, readlink, realpath } from 'node:fs/promises'
import { Minipass } from 'minipass'
import type { Dirent, Stats } from 'node:fs'
/**
* An object that will be used to override the default `fs`
* methods. Any methods that are not overridden will use Node's
* built-in implementations.
*
* - lstatSync
* - readdir (callback `withFileTypes` Dirent variant, used for
* readdirCB and most walks)
* - readdirSync
* - readlinkSync
* - realpathSync
* - promises: Object containing the following async methods:
* - lstat
* - readdir (Dirent variant only)
* - readlink
* - realpath
*/
export interface FSOption {
lstatSync?: (path: string) => Stats
readdir?: (
path: string,
options: { withFileTypes: true },
cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,
) => void
readdirSync?: (
path: string,
options: { withFileTypes: true },
) => Dirent[]
readlinkSync?: (path: string) => string
realpathSync?: (path: string) => string
promises?: {
lstat?: (path: string) => Promise<Stats>
readdir?: (
path: string,
options: { withFileTypes: true },
) => Promise<Dirent[]>
readlink?: (path: string) => Promise<string>
realpath?: (path: string) => Promise<string>
[k: string]: any
}
[k: string]: any
}
interface FSValue {
lstatSync: (path: string) => Stats
readdir: (
path: string,
options: { withFileTypes: true },
cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,
) => void
readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]
readlinkSync: (path: string) => string
realpathSync: (path: string) => string
promises: {
lstat: (path: string) => Promise<Stats>
readdir: (
path: string,
options: { withFileTypes: true },
) => Promise<Dirent[]>
readlink: (path: string) => Promise<string>
realpath: (path: string) => Promise<string>
[k: string]: any
}
[k: string]: any
}
const defaultFS: FSValue = {
lstatSync,
readdir: readdirCB,
readdirSync,
readlinkSync,
realpathSync,
promises: {
lstat,
readdir,
readlink,
realpath,
},
}
// if they just gave us require('fs') then use our default
const fsFromOption = (fsOption?: FSOption): FSValue =>
!fsOption || fsOption === defaultFS || fsOption === actualFS ?
defaultFS
: {
...defaultFS,
...fsOption,
promises: {
...defaultFS.promises,
...(fsOption.promises || {}),
},
}
// turn something like //?/c:/ into c:\
const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i
const uncToDrive = (rootPath: string): string =>
rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\')
// windows paths are separated by either / or \
const eitherSep = /[\\\/]/
const UNKNOWN = 0 // may not even exist, for all we know
const IFIFO = 0b0001
const IFCHR = 0b0010
const IFDIR = 0b0100
const IFBLK = 0b0110
const IFREG = 0b1000
const IFLNK = 0b1010
const IFSOCK = 0b1100
const IFMT = 0b1111
export type Type =
| 'Unknown'
| 'FIFO'
| 'CharacterDevice'
| 'Directory'
| 'BlockDevice'
| 'File'
| 'SymbolicLink'
| 'Socket'
// mask to unset low 4 bits
const IFMT_UNKNOWN = ~IFMT
// set after successfully calling readdir() and getting entries.
const READDIR_CALLED = 0b0000_0001_0000
// set after a successful lstat()
const LSTAT_CALLED = 0b0000_0010_0000
// set if an entry (or one of its parents) is definitely not a dir
const ENOTDIR = 0b0000_0100_0000
// set if an entry (or one of its parents) does not exist
// (can also be set on lstat errors like EACCES or ENAMETOOLONG)
const ENOENT = 0b0000_1000_0000
// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK
// set if we fail to readlink
const ENOREADLINK = 0b0001_0000_0000
// set if we know realpath() will fail
const ENOREALPATH = 0b0010_0000_0000
const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH
const TYPEMASK = 0b0011_1111_1111
const entToType = (s: Dirent | Stats) =>
s.isFile() ? IFREG
: s.isDirectory() ? IFDIR
: s.isSymbolicLink() ? IFLNK
: s.isCharacterDevice() ? IFCHR
: s.isBlockDevice() ? IFBLK
: s.isSocket() ? IFSOCK
: s.isFIFO() ? IFIFO
: UNKNOWN
// normalize unicode path names
const normalizeCache = new Map<string, string>()
const normalize = (s: string) => {
const c = normalizeCache.get(s)
if (c) return c
const n = s.normalize('NFKD')
normalizeCache.set(s, n)
return n
}
const normalizeNocaseCache = new Map<string, string>()
const normalizeNocase = (s: string) => {
const c = normalizeNocaseCache.get(s)
if (c) return c
const n = normalize(s.toLowerCase())
normalizeNocaseCache.set(s, n)
return n
}
/**
* Options that may be provided to the Path constructor
*/
export interface PathOpts {
fullpath?: string
relative?: string
relativePosix?: string
parent?: PathBase
/**
* See {@link FSOption}
*/
fs?: FSOption
}
/**
* An LRUCache for storing resolved path strings or Path objects.
* @internal
*/
export class ResolveCache extends LRUCache<string, string> {
constructor() {
super({ max: 256 })
}
}
// In order to prevent blowing out the js heap by allocating hundreds of
// thousands of Path entries when walking extremely large trees, the "children"
// in this tree are represented by storing an array of Path entries in an
// LRUCache, indexed by the parent. At any time, Path.children() may return an
// empty array, indicating that it doesn't know about any of its children, and
// thus has to rebuild that cache. This is fine, it just means that we don't
// benefit as much from having the cached entries, but huge directory walks
// don't blow out the stack, and smaller ones are still as fast as possible.
//
//It does impose some complexity when building up the readdir data, because we
//need to pass a reference to the children array that we started with.
/**
* an LRUCache for storing child entries.
* @internal
*/
export class ChildrenCache extends LRUCache<PathBase, Children> {
constructor(maxSize: number = 16 * 1024) {
super({
maxSize,
// parent + children
sizeCalculation: a => a.length + 1,
})
}
}
/**
* Array of Path objects, plus a marker indicating the first provisional entry
*
* @internal
*/
export type Children = PathBase[] & { provisional: number }
const setAsCwd = Symbol('PathScurry setAsCwd')
/**
* Path objects are sort of like a super-powered
* {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}
*
* Each one represents a single filesystem entry on disk, which may or may not
* exist. It includes methods for reading various types of information via
* lstat, readlink, and readdir, and caches all information to the greatest
* degree possible.
*
* Note that fs operations that would normally throw will instead return an
* "empty" value. This is in order to prevent excessive overhead from error
* stack traces.
*/
export abstract class PathBase implements Dirent {
/**
* the basename of this path
*
* **Important**: *always* test the path name against any test string
* usingthe {@link isNamed} method, and not by directly comparing this
* string. Otherwise, unicode path strings that the system sees as identical
* will not be properly treated as the same path, leading to incorrect
* behavior and possible security issues.
*/
name: string
/**
* the Path entry corresponding to the path root.
*
* @internal
*/
root: PathBase
/**
* All roots found within the current PathScurry family
*
* @internal
*/
roots: { [k: string]: PathBase }
/**
* a reference to the parent path, or undefined in the case of root entries
*
* @internal
*/
parent?: PathBase
/**
* boolean indicating whether paths are compared case-insensitively
* @internal
*/
nocase: boolean
/**
* boolean indicating that this path is the current working directory
* of the PathScurry collection that contains it.
*/
isCWD: boolean = false
/**
* the string or regexp used to split paths. On posix, it is `'/'`, and on
* windows it is a RegExp matching either `'/'` or `'\\'`
*/
abstract splitSep: string | RegExp
/**
* The path separator string to use when joining paths
*/
abstract sep: string
// potential default fs override
#fs: FSValue
// Stats fields
#dev?: number
get dev() {
return this.#dev
}
#mode?: number
get mode() {
return this.#mode
}
#nlink?: number
get nlink() {
return this.#nlink
}
#uid?: number
get uid() {
return this.#uid
}
#gid?: number
get gid() {
return this.#gid
}
#rdev?: number
get rdev() {
return this.#rdev
}
#blksize?: number
get blksize() {
return this.#blksize
}
#ino?: number
get ino() {
return this.#ino
}
#size?: number
get size() {
return this.#size
}
#blocks?: number
get blocks() {
return this.#blocks
}
#atimeMs?: number
get atimeMs() {
return this.#atimeMs
}
#mtimeMs?: number
get mtimeMs() {
return this.#mtimeMs
}
#ctimeMs?: number
get ctimeMs() {
return this.#ctimeMs
}
#birthtimeMs?: number
get birthtimeMs() {
return this.#birthtimeMs
}
#atime?: Date
get atime() {
return this.#atime
}
#mtime?: Date
get mtime() {
return this.#mtime
}
#ctime?: Date
get ctime() {
return this.#ctime
}
#birthtime?: Date
get birthtime() {
return this.#birthtime
}
#matchName: string
#depth?: number
#fullpath?: string
#fullpathPosix?: string
#relative?: string
#relativePosix?: string
#type: number
#children: ChildrenCache
#linkTarget?: PathBase
#realpath?: PathBase
/**
* This property is for compatibility with the Dirent class as of
* Node v20, where Dirent['parentPath'] refers to the path of the
* directory that was passed to readdir. For root entries, it's the path
* to the entry itself.
*/
get parentPath(): string {
return (this.parent || this).fullpath()
}
/**
* Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
* this property refers to the *parent* path, not the path object itself.
*
* @deprecated
*/
get path(): string {
return this.parentPath
}
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(
name: string,
type: number = UNKNOWN,
root: PathBase | undefined,
roots: { [k: string]: PathBase },
nocase: boolean,
children: ChildrenCache,
opts: PathOpts,
) {
this.name = name
this.#matchName = nocase ? normalizeNocase(name) : normalize(name)
this.#type = type & TYPEMASK
this.nocase = nocase
this.roots = roots
this.root = root || this
this.#children = children
this.#fullpath = opts.fullpath
this.#relative = opts.relative
this.#relativePosix = opts.relativePosix
this.parent = opts.parent
if (this.parent) {
this.#fs = this.parent.#fs
} else {
this.#fs = fsFromOption(opts.fs)
}
}
/**
* Returns the depth of the Path object from its root.
*
* For example, a path at `/foo/bar` would have a depth of 2.
*/
depth(): number {
if (this.#depth !== undefined) return this.#depth
if (!this.parent) return (this.#depth = 0)
return (this.#depth = this.parent.depth() + 1)
}
/**
* @internal
*/
abstract getRootString(path: string): string
/**
* @internal
*/
abstract getRoot(rootPath: string): PathBase
/**
* @internal
*/
abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase
/**
* @internal
*/
childrenCache() {
return this.#children
}
/**
* Get the Path object referenced by the string path, resolved from this Path
*/
resolve(path?: string): PathBase {
if (!path) {
return this
}
const rootPath = this.getRootString(path)
const dir = path.substring(rootPath.length)
const dirParts = dir.split(this.splitSep)
const result: PathBase =
rootPath ?
this.getRoot(rootPath).#resolveParts(dirParts)
: this.#resolveParts(dirParts)
return result
}
#resolveParts(dirParts: string[]) {
let p: PathBase = this
for (const part of dirParts) {
p = p.child(part)
}
return p
}
/**
* Returns the cached children Path objects, if still available. If they
* have fallen out of the cache, then returns an empty array, and resets the
* READDIR_CALLED bit, so that future calls to readdir() will require an fs
* lookup.
*
* @internal
*/
children(): Children {
const cached = this.#children.get(this)
if (cached) {
return cached
}
const children: Children = Object.assign([], { provisional: 0 })
this.#children.set(this, children)
this.#type &= ~READDIR_CALLED
return children
}
/**
* Resolves a path portion and returns or creates the child Path.
*
* Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
* `'..'`.
*
* This should not be called directly. If `pathPart` contains any path
* separators, it will lead to unsafe undefined behavior.
*
* Use `Path.resolve()` instead.
*
* @internal
*/
child(pathPart: string, opts?: PathOpts): PathBase {
if (pathPart === '' || pathPart === '.') {
return this
}
if (pathPart === '..') {
return this.parent || this
}
// find the child
const children = this.children()
const name =
this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)
for (const p of children) {
if (p.#matchName === name) {
return p
}
}
// didn't find it, create provisional child, since it might not
// actually exist. If we know the parent isn't a dir, then
// in fact it CAN'T exist.
const s = this.parent ? this.sep : ''
const fullpath =
this.#fullpath ? this.#fullpath + s + pathPart : undefined
const pchild = this.newChild(pathPart, UNKNOWN, {
...opts,
parent: this,
fullpath,
})
if (!this.canReaddir()) {
pchild.#type |= ENOENT
}
// don't have to update provisional, because if we have real children,
// then provisional is set to children.length, otherwise a lower number
children.push(pchild)
return pchild
}
/**
* The relative path from the cwd. If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpath()
*/
relative(): string {
if (this.isCWD) return ''
if (this.#relative !== undefined) {
return this.#relative
}
const name = this.name
const p = this.parent
if (!p) {
return (this.#relative = this.name)
}
const pv = p.relative()
return pv + (!pv || !p.parent ? '' : this.sep) + name
}
/**
* The relative path from the cwd, using / as the path separator.
* If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpathPosix()
* On posix systems, this is identical to relative().
*/
relativePosix(): string {
if (this.sep === '/') return this.relative()
if (this.isCWD) return ''
if (this.#relativePosix !== undefined) return this.#relativePosix
const name = this.name
const p = this.parent
if (!p) {
return (this.#relativePosix = this.fullpathPosix())
}
const pv = p.relativePosix()
return pv + (!pv || !p.parent ? '' : '/') + name
}
/**
* The fully resolved path string for this Path entry
*/
fullpath(): string {
if (this.#fullpath !== undefined) {
return this.#fullpath
}
const name = this.name
const p = this.parent
if (!p) {
return (this.#fullpath = this.name)
}
const pv = p.fullpath()
const fp = pv + (!p.parent ? '' : this.sep) + name
return (this.#fullpath = fp)
}
/**
* On platforms other than windows, this is identical to fullpath.
*
* On windows, this is overridden to return the forward-slash form of the
* full UNC path.
*/
fullpathPosix(): string {
if (this.#fullpathPosix !== undefined) return this.#fullpathPosix
if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())
if (!this.parent) {
const p = this.fullpath().replace(/\\/g, '/')
if (/^[a-z]:\//i.test(p)) {
return (this.#fullpathPosix = `//?/${p}`)
} else {
return (this.#fullpathPosix = p)
}
}
const p = this.parent
const pfpp = p.fullpathPosix()
const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name
return (this.#fullpathPosix = fpp)
}
/**
* Is the Path of an unknown type?
*
* Note that we might know *something* about it if there has been a previous
* filesystem operation, for example that it does not exist, or is not a
* link, or whether it has child entries.
*/
isUnknown(): boolean {
return (this.#type & IFMT) === UNKNOWN
}
isType(type: Type): boolean {
return this[`is${type}`]()
}
getType(): Type {
return (
this.isUnknown() ? 'Unknown'
: this.isDirectory() ? 'Directory'
: this.isFile() ? 'File'
: this.isSymbolicLink() ? 'SymbolicLink'
: this.isFIFO() ? 'FIFO'
: this.isCharacterDevice() ? 'CharacterDevice'
: this.isBlockDevice() ? 'BlockDevice'
: /* c8 ignore start */ this.isSocket() ? 'Socket'
: 'Unknown'
)
/* c8 ignore stop */
}
/**
* Is the Path a regular file?
*/
isFile(): boolean {
return (this.#type & IFMT) === IFREG
}
/**
* Is the Path a directory?
*/
isDirectory(): boolean {
return (this.#type & IFMT) === IFDIR
}
/**
* Is the path a character device?
*/
isCharacterDevice(): boolean {
return (this.#type & IFMT) === IFCHR
}
/**
* Is the path a block device?
*/
isBlockDevice(): boolean {
return (this.#type & IFMT) === IFBLK
}
/**
* Is the path a FIFO pipe?
*/
isFIFO(): boolean {
return (this.#type & IFMT) === IFIFO
}
/**
* Is the path a socket?
*/
isSocket(): boolean {
return (this.#type & IFMT) === IFSOCK
}
/**
* Is the path a symbolic link?
*/
isSymbolicLink(): boolean {
return (this.#type & IFLNK) === IFLNK
}
/**
* Return the entry if it has been subject of a successful lstat, or
* undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* simply
* mean that we haven't called lstat on it.
*/
lstatCached(): PathBase | undefined {
return this.#type & LSTAT_CALLED ? this : undefined
}
/**
* Return the cached link target if the entry has been the subject of a
* successful readlink, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readlink() has been called at some point.
*/
readlinkCached(): PathBase | undefined {
return this.#linkTarget
}
/**
* Returns the cached realpath target if the entry has been the subject
* of a successful realpath, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* realpath() has been called at some point.
*/
realpathCached(): PathBase | undefined {
return this.#realpath
}
/**
* Returns the cached child Path entries array if the entry has been the
* subject of a successful readdir(), or [] otherwise.
*
* Does not read the filesystem, so an empty array *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readdir() has been called recently enough to still be valid.
*/
readdirCached(): PathBase[] {
const children = this.children()
return children.slice(0, children.provisional)
}
/**
* Return true if it's worth trying to readlink. Ie, we don't (yet) have
* any indication that readlink will definitely fail.
*
* Returns false if the path is known to not be a symlink, if a previous
* readlink failed, or if the entry does not exist.
*/
canReadlink(): boolean {
if (this.#linkTarget) return true
if (!this.parent) return false
// cases where it cannot possibly succeed
const ifmt = this.#type & IFMT
return !(
(ifmt !== UNKNOWN && ifmt !== IFLNK) ||
this.#type & ENOREADLINK ||
this.#type & ENOENT
)
}
/**
* Return true if readdir has previously been successfully called on this
* path, indicating that cachedReaddir() is likely valid.
*/
calledReaddir(): boolean {
return !!(this.#type & READDIR_CALLED)
}
/**
* Returns true if the path is known to not exist. That is, a previous lstat
* or readdir failed to verify its existence when that would have been
* expected, or a parent entry was marked either enoent or enotdir.
*/
isENOENT(): boolean {
return !!(this.#type & ENOENT)
}
/**
* Return true if the path is a match for the given path name. This handles
* case sensitivity and unicode normalization.
*
* Note: even on case-sensitive systems, it is **not** safe to test the
* equality of the `.name` property to determine whether a given pathname
* matches, due to unicode normalization mismatches.
*
* Always use this method instead of testing the `path.name` property
* directly.
*/
isNamed(n: string): boolean {
return !this.nocase ?
this.#matchName === normalize(n)
: this.#matchName === normalizeNocase(n)
}
/**
* Return the Path object corresponding to the target of a symbolic link.
*
* If the Path is not a symbolic link, or if the readlink call fails for any
* reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
*/
async readlink(): Promise<PathBase | undefined> {
const target = this.#linkTarget
if (target) {
return target
}
if (!this.canReadlink()) {
return undefined
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined
}
/* c8 ignore stop */
try {
const read = await this.#fs.promises.readlink(this.fullpath())
const linkTarget = (await this.parent.realpath())?.resolve(read)
if (linkTarget) {
return (this.#linkTarget = linkTarget)
}
} catch (er) {
this.#readlinkFail((er as NodeJS.ErrnoException).code)
return undefined
}
}
/**
* Synchronous {@link PathBase.readlink}
*/
readlinkSync(): PathBase | undefined {
const target = this.#linkTarget
if (target) {
return target
}
if (!this.canReadlink()) {
return undefined
}
/* c8 ignore start */
// already covered by the canReadlink test, here for ts grumples
if (!this.parent) {
return undefined
}
/* c8 ignore stop */
try {
const read = this.#fs.readlinkSync(this.fullpath())
const linkTarget = this.parent.realpathSync()?.resolve(read)
if (linkTarget) {
return (this.#linkTarget = linkTarget)
}
} catch (er) {
this.#readlinkFail((er as NodeJS.ErrnoException).code)
return undefined
}
}
#readdirSuccess(children: Children) {
// succeeded, mark readdir called bit
this.#type |= READDIR_CALLED
// mark all remaining provisional children as ENOENT
for (let p = children.provisional; p < children.length; p++) {
const c = children[p]
if (c) c.#markENOENT()
}
}
#markENOENT() {
// mark as UNKNOWN and ENOENT
if (this.#type & ENOENT) return
this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN
this.#markChildrenENOENT()
}
#markChildrenENOENT() {
// all children are provisional and do not exist
const children = this.children()
children.provisional = 0
for (const p of children) {
p.#markENOENT()
}
}
#markENOREALPATH() {
this.#type |= ENOREALPATH
this.#markENOTDIR()
}
// save the information when we know the entry is not a dir
#markENOTDIR() {
// entry is not a directory, so any children can't exist.
// this *should* be impossible, since any children created
// after it's been marked ENOTDIR should be marked ENOENT,
// so it won't even get to this point.
/* c8 ignore start */
if (this.#type & ENOTDIR) return
/* c8 ignore stop */
let t = this.#type
// this could happen if we stat a dir, then delete it,
// then try to read it or one of its children.
if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN
this.#type = t | ENOTDIR
this.#markChildrenENOENT()
}
#readdirFail(code: string = '') {
// markENOTDIR and markENOENT also set provisional=0
if (code === 'ENOTDIR' || code === 'EPERM') {
this.#markENOTDIR()
} else if (code === 'ENOENT') {
this.#markENOENT()
} else {
this.children().provisional = 0
}
}
#lstatFail(code: string = '') {
// Windows just raises ENOENT in this case, disable for win CI
/* c8 ignore start */
if (code === 'ENOTDIR') {
// already know it has a parent by this point
const p = this.parent as PathBase
p.#markENOTDIR()
} else if (code === 'ENOENT') {
/* c8 ignore stop */
this.#markENOENT()
}
}
#readlinkFail(code: string = '') {
let ter = this.#type
ter |= ENOREADLINK
if (code === 'ENOENT') ter |= ENOENT
// windows gets a weird error when you try to readlink a file
if (code === 'EINVAL' || code === 'UNKNOWN') {
// exists, but not a symlink, we don't know WHAT it is, so remove
// all IFMT bits.
ter &= IFMT_UNKNOWN
}
this.#type = ter
// windows just gets ENOENT in this case. We do cover the case,
// just disabled because it's impossible on Windows CI
/* c8 ignore start */
if (code === 'ENOTDIR' && this.parent) {
this.parent.#markENOTDIR()
}
/* c8 ignore stop */
}
#readdirAddChild(e: Dirent, c: Children) {
return (