-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFile.js
More file actions
3602 lines (3066 loc) · 102 KB
/
Copy pathFile.js
File metadata and controls
3602 lines (3066 loc) · 102 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';
// Use $ wrapper for imports to avoid name collision with locals and parameters
// (esp bad here is 'path' module):
const $ = {
fs: require('fs'),
json5: require('json5'),
mkdirp: require('mkdirp'),
os: require('os'),
path: require('path'),
rimraf: require('rimraf'),
tmp: require('tmp'),
which: require('which')
};
const platform = $.os.platform();
const isWin = /^win\d\d$/i.test(platform);
const isMac = /^darwin$/i.test(platform);
const driveLetterRe = /^[A-Z]:[\\]?$/i;
//================================================================================
/**
* This class wraps a path to a file or directory and provides methods to ease processing
* and operating on that path.
*
* ## Naming Conventions
*
* Any method that ends with 'Path' returns a string, while all other methods return a
* `File` (where appropriate). Methods often come in pairs: one that returns the result
* as a String and one that returns a `File`. Since it is best to stay in the realm of
* `File` objects, their names are the more concise.
*
* let absFile = file.absolutify(); // a File object
*
* let absPath = file.absolutePath(); // a string
*
* ### Synchronous vs Asynchronous
*
* All async methods return promises and have names that begin with 'async' (for example,
* `asyncFoo()`). Consider the `stat` method. It is synchronous while the asynchronous
* version is`asyncStat`.
*
* let st = file.stat(); // sync
*
* file.asyncStat().then(st => {
* // async
* });
*/
class File {
//noinspection JSUnusedGlobalSymbols
/**
* Returns the `File.Access` object describing the access modes available for the
* specified file. If an error is encountered determining the access (for example,
* the file does not exist), the `error` property of the returned object will be
* set accordingly.
*
* @param {String/File} filePath The `File` instance of path as a string.
* @return {File.Access} The `File.Access` descriptor.
*/
static access (filePath) {
if (!filePath) {
return this.Access.getError('ENOENT');
}
return this.from(filePath).access();
}
/**
* Creates a temporary directory and returns a Promise to its path as a `File`.
*
* When no arguments are passed the first result is cached (since one temp dir is
* often sufficient for a process).
*
* let temp;
* let temp2;
* let temp3;
*
* File.asyncTemp().then(t => temp = t); // generates temp dir
* File.asyncTemp().then(t => temp2 = t); // same dir (temp2 === temp)
*
* File.asyncTemp(null).then(t => temp3 = t); // new call to tmp.dir()
*
* Because only the first call to `temp()` does any real work, it is generally safe
* to use `temp()` (instead of `asyncTemp()`) when no options are passed and the one
* temporary folder is sufficient.
*
* @param {Object} [options] Options for `dir()` from the `tmp` module.
* @return {Promise<File>}
*/
static asyncTemp (options) {
let cached = this.hasOwnProperty('_temp');
let useCache = (options === undefined);
if (cached && useCache) {
return Promise.resolve(this._temp);
}
return new Promise((resolve, reject) => {
this.$tmp.dir(options, (err, name) => {
if (err) {
reject(err);
}
else {
let f = this.from(name);
if (useCache) {
// If we are after the shared temp, make sure it wasn't
// created during our async trip... If not, store this
// as the cached temp.
f = this._temp || (this._temp = f);
}
resolve(f);
}
});
});
}
/**
* Attempts to find the given program by its `name` in the system **PATH**. If it is
* found, a `File` instance is resolved. If not, `null` is resolved. If an error
* occurs, the promise will reject accordingly.
*
* @param {String} name The name of the program to find.
* @param {Object/String/String[]} options Options to control the process or a
* replacement value for the PATH as a string or array of strings.
* @param {String/String[]/File[]} options.path A replacement PATH
* @param {String} options.pathExt On Windows, this overrides the **PATHEXT**
* environment variable (normally, '.EXE;.CMD;.BAT;.COM').
* @return {Promise<File>}
*/
static asyncWhich (name, options) {
let opts = this._whichOptions(options);
return new Promise((resolve, reject) => {
$.which(name, opts, (err, result) => {
if (err) {
if (err.code === 'ENOENT') {
resolve(null);
}
else {
reject(err);
}
}
else {
resolve(this.from(result));
}
});
});
}
/**
* Returns the `process.cwd()` as a `File` instance.
* @return {File} The `process.cwd()` as a `File` instance.
*/
static cwd () {
return new this(process.cwd());
}
/**
* Returns `true` if the specified file exists, `false` if not.
* @param {String/File} filePath The `File` or path to test for existence.
* @return {Boolean} `true` if the file exists.
*/
static exists (filePath) {
let st = this.stat(filePath);
return !st.error;
}
/**
* Returns a `File` for the specified path (if it is not already a `File`).
* @param {String/File} filePath The `File` or path to convert to a `File`.
* @return {File} The `File` instance.
*/
static from (filePath) {
let file = filePath || null;
if (file && !file.$isFile) {
file = new this(filePath);
}
return file;
}
/**
* Returns the path as a string given a `File` or string.
* @param {String/File} filePath
* @return {String} The path.
*/
static fspath (filePath) {
return ((filePath && filePath.$isFile) ? filePath.fspath : filePath) || '';
}
/**
* Converts a file-system "glob" pattern into a `RegExp` instance.
*
* For example:
*
* glob('*.txt')
* glob('** /*.txt')
*
* See `File.Globber` for more details on `options`.
*
* @param {String} pattern The glob pattern to convert.
* @param {String} [options=null] Pass `'E'` to enable "extended" globs like
* in Bash. Pass 'S' to treat '*' as simple (shell-like) wildcards. This will which
* matches `'/'` characters with a `'*'`. By default, only `'**'` matches `'/'`.
* Other options are passed along a `RegExp` flags (e.g., 'i' and 'g').
* @return {RegExp}
*/
static glob (pattern, options) {
return this.Globber.get(options || '').compile(pattern);
}
/**
* Returns the `os.homedir()` as a `File` instance. On Windows, this is something
* like `'C:\Users\Name'`.
*
* @return {File} The `os.homedir()` as a `File` instance.
*/
static home () {
return new this(this.$os.homedir());
}
/**
* Returns `true` if the specified path is a directory, `false` if not.
* @param {String/File} filePath The `File` or path to test.
* @return {Boolean} Whether the file is a directory or not.
*/
static isDir (filePath) {
if (!filePath) {
return false;
}
return this.from(filePath).isDir();
}
/**
* Returns `true` if the specified path is a file, `false` if not.
* @param {String/File} filePath The `File` or path to test.
* @return {Boolean} Whether the file is a file or not (opposite of isDir).
*/
static isFile (filePath) {
if (!filePath) {
return false;
}
return this.from(filePath).isFile();
}
/**
* This method is the same as `join()` in the `path` module except that the items
* can be `File` instances or `String` and a `File` instance is returned.
* @param {File.../String...} parts Name fragments to join using `path.join()`.
* @return {File} The `File` instance from the resulting path.
*/
static join (...parts) {
let f = this.joinPath(...parts);
return new this(f);
}
/**
* This method is the same as `join()` in the `path` module except that the items
* can be `File` instances or `String`.
* @param {File.../String...} parts Name fragments to join using `path.join()`.
* @return {String} The resulting path.
*/
static joinPath (...parts) {
let n = parts && parts.length || 0;
for (let i = 0; i < n; ++i) {
let p = parts[i];
if (p.$isFile) {
parts[i] = p.path;
}
}
let ret = (n === 1) ? parts[0] : (n && this.$path.join(...parts));
return ret || '';
}
/**
* Returns the path as a string given a `File` or string.
* @param {String/File} filePath
* @return {String} The path.
*/
static path (filePath) {
return ((filePath && filePath.$isFile) ? filePath.path : filePath) || '';
}
/**
* Returns the folder into which applications should save data for their users. For
* example, on Windows this would be `'C:\Users\Name\AppData\Roaming\Company'` where
* "Name" is the user's name and "Company" is the owner of the data (typically the
* name of the company producing the application).
*
* This location is platform-specific:
*
* - Windows: C:\Users\Name\AppData\Roaming\Company
* - Mac OS X: /Users/Name/Library/Application Support/Company
* - Linux: /home/name/.local/share/data/company
* - Default: /home/name/.company
*
* The set of recognized platforms for profile locations is found in `profilers`.
*
* @param {String} company The name of the application's producer.
* @return {File} The `File` instance.
*/
static profile (company) {
company = company || this.COMPANY;
if (!company) {
throw new Error('Must provide company name to isolate profile data');
}
let fn = this.profilers.default;
return fn.call(this, this.home(), company);
}
/**
* This method is the same as `resolve()` in the `path` module except that the items
* can be `File` instances or `String` and a `File` instance is returned.
* @param {File.../String...} parts Name fragments to resolve using `path.resolve()`.
* @return {File} The `File` instance.
*/
static resolve (...parts) {
let f = this.resolvePath(...parts);
return new this(f);
}
/**
* This method is the same as `resolve()` in the `path` module except that the items
* can be `File` instances or `String`.
* @param {File.../String...} parts Name fragments to resolve using `path.resolve()`.
* @return {String} The resulting path.
*/
static resolvePath (...parts) {
for (let i = 0, n = parts.length; i < n; ++i) {
let p = parts[i];
if (p.$isFile) {
p = p.path;
}
parts[i] = this._detildify(p);
}
return (parts && parts.length && this.$path.resolve(...parts)) || '';
}
/**
* Splits the given `File` or path into an array of parts.
* @param {String/File} filePath
* @return {String[]} The path parts.
*/
static split (filePath) {
let path = this.path(filePath);
return path.split(this.re.split);
}
/**
* Compares two files using the `File` instances' `compare('d')` method to sort
* folder before files (each group being sorted by name).
* @param filePath1 A `File` instance or string path.
* @param filePath2 A `File` instance or string path.
* @return {Number}
*/
static sorter (filePath1, filePath2) {
let a = this.from(filePath1);
return a.compare(filePath2, 'd');
}
/**
* Compares two files using the `File` instances' `compare('f')` method to sort
* files before folders (each group being sorted by name).
* @param filePath1 A `File` instance or string path.
* @param filePath2 A `File` instance or string path.
* @return {Number}
*/
static sorterFilesFirst (filePath1, filePath2) {
let a = this.from(filePath1);
return a.compare(filePath2, 'f');
}
/**
* Compares two files using the `File` instances' `compare(false)` method to sort
* files and folder together by name.
* @param filePath1 A `File` instance or string path.
* @param filePath2 A `File` instance or string path.
* @return {Number}
*/
static sorterByPath (filePath1, filePath2) {
let a = this.from(filePath1);
return a.compare(filePath2, false);
}
/**
* Returns the `fs.Stats` for the specified `File` or path. If the file does not
* exist, or an error is encountered determining the stats, the `error` property
* will be set accordingly.
*
* @param {String/File} filePath
* @return {fs.Stats}
*/
static stat (filePath) {
let f = this.from(filePath);
if (!f) {
return this.Stat.getError('ENOENT');
}
return f.stat();
}
/**
* Creates a temporary directory and returns its path as a `File`.
*
* When no arguments are passed the first result is cached (since one temp dir is
* often sufficient for a process).
*
* let temp = File.temp(); // generates temp dir
*
* let temp2 = File.temp(); // === temp
*
* let temp3 = File.temp(null); // new call to tmp.dirSync()
*
* @param {Object} [options] Options for `dirSync()` from the `tmp` module.
* @return {File}
*/
static temp (options) {
let cached = this.hasOwnProperty('_temp');
let useCache = (options === undefined);
if (cached && useCache) {
return this._temp;
}
let result = this.$tmp.dirSync(options);
result = this.from(result.name);
if (useCache) {
this._temp = result;
}
return result;
}
/**
* Attempts to find the given program by its `name` in the system **PATH**. If it is
* found, a `File` instance is returned. If not, `null` is returns. If an error
* occurs, an `Error` is thrown accordingly.
*
* @param {String} name The name of the program to find.
* @param {Object/String/String[]} options Options to control the process or a
* replacement value for the PATH as a string or array of strings.
* @param {String/String[]/File[]} options.path A replacement PATH
* @param {String} options.pathExt On Windows, this overrides the **PATHEXT**
* environment variable (normally, '.EXE;.CMD;.BAT;.COM').
* @return {File}
*/
static which (name, options) {
let opts = this._whichOptions(options);
try {
// throws on not found...
return this.from($.which.sync(name, opts));
}
catch (e) {
if (e.code === 'ENOENT') {
return null;
}
throw e;
}
}
//-----------------------------------------------------------------
/**
* Initialize an instance by joining the given path fragments.
* @param {File/String...} parts The path fragments.
*/
constructor (...parts) {
this.path = this.constructor.joinPath(...parts);
}
//----------------------------
// Properties
/**
* @property {String} name
* @readonly
* The name of the file at the end of the path. For example, given '/foo/bar/baz',
* the `name` is 'baz'.
*
* Paths that end with a separator (e.g., '/foo/bar/') are treated as if the trailing
* separator were not present. That is, 'bar' would be the `name` of '/foo/bar/'. This
* is to be consistent with this behavior:
*
* File.from('/foo/bar/').equals('/foo/bar'); // === true
*
* Typically known as `basename` on Linux-like systems.
*/
get name () {
let name = this._name;
if (name === undefined) {
let index = this.lastSeparator();
let path = this.path;
let end = path.length;
if (index === path.length - 1) {
// e.g. 'foo/bar/'
index = this.lastSeparator((end = index) - 1);
}
// even if index = -1, index+1=0 which is what we want...
this._name = name = path.substring(index + 1, end) || '';
}
return name;
}
/**
* @property {File} parent
* @readonly
* The parent directory of this file. For example, for '/foo/bar/baz' the `parent` is
* '/foo/bar'. This is `null` for the file system root.
*
* Paths that end with a separator (e.g., '/foo/bar/') are treated as if the trailing
* separator were not present. That is, '/foo' would be the `parent` of '/foo/bar/'.
* This is to be consistent with this behavior:
*
* File.from('/foo/bar/').equals('/foo/bar'); // === true
*
* Typically known as `dirname` on Linux-like systems.
*/
get parent () {
let parent = this._parent;
if (parent === undefined) {
let path = this.path;
let sep = this.lastSeparator();
let ret;
if (sep > -1) {
if (sep === path.length - 1) {
// e.g. 'foo/bar/'
sep = this.lastSeparator(sep - 1);
}
ret = path.substr(0, sep);
if (sep === 2 && driveLetterRe.test(ret)) {
ret += '\\';
if (ret === path) {
ret = null;
}
}
}
if (!ret) {
let abs = this.absolutePath();
ret = this.$path.resolve(abs, '..');
if (abs === ret) {
ret = null;
}
}
this._parent = parent = this.constructor.from(ret);
}
return parent;
}
/**
* @property {String} extent
* @readonly
* The type of the file at the end of the path. For example, given '/foo/bar/baz.js',
* the `extent` is 'js'. Returns `''` for files with no extension (e.g. README).
*/
get extent () {
let ext = this._extent;
if (ext === undefined) {
let name = this.name;
let index = name.lastIndexOf('.');
this._extent = ext = ((index > -1) && name.substr(index + 1)) || '';
}
return ext;
}
/**
* @property {String} fspath
* @readonly
* The same as `path` property except resolved for `'~'` pseudo-roots and hence
* useful for `fs` module calls.
*/
get fspath () {
return this.constructor._detildify(this.path);
}
//-----------------------------------------------------------------
// Path calculation
/**
* Return absolute path to this file.
* @return {String}
*/
absolutePath () {
return this.constructor.resolvePath(this.path);
}
//noinspection JSUnusedGlobalSymbols
/**
* Returns a `File` instance created from the `absolutePath`.
* @return {File}
*/
absolutify () {
return this.constructor.from(this.absolutePath()); // null/blank handling
}
asyncCanonicalPath () {
let path = this.absolutePath();
return new Promise(resolve => {
this.$fs.realpath(path, (err, result) => {
if (err) {
resolve(null);
}
else {
resolve(result);
}
});
})
}
asyncCanonicalize () {
return this.asyncCanonicalPath().then(path => {
return this.constructor.from(path);
});
}
/**
* Returns the canonical path to this file.
* @return {String} The canonical path of this file or `null` if no file exists.
*/
canonicalPath () {
try {
return this.$fs.realpathSync(this.absolutePath());
} catch (e) {
return null;
}
}
/**
* Returns a `File` instance created from the canonical path
* @return {File} The `File` with the canonical path or `null` if no file exists.
*/
canonicalize () {
return this.constructor.from(this.canonicalPath()); // null/blank handling
}
joinPath (...parts) {
return this.constructor.joinPath(this, ...parts);
}
join (...parts) {
return this.constructor.join(this, ...parts);
}
lastSeparator (start) {
let path = this.path,
i = path.lastIndexOf('/', start);
if (this.constructor.WIN) {
// Windows respects both / and \ as path separators
i = Math.max(i, path.lastIndexOf('\\'));
}
return i;
}
nativePath (separator) {
let p = this.path;
return p && p.replace(this.re.split, separator || this.constructor.separator);
}
nativize (separator) {
return this.constructor.from(this.nativePath(separator));
}
normalize () {
return this.constructor.from(this.normalizedPath());
}
normalizedPath () {
let p = this.path;
return p && this.$path.normalize(p);
}
/**
* Returns the relative path of this file in relation to the `from` file or path.
* @param {String/File} from The base location from which this file is relative.
* @return {String}
*/
relativePath (from) {
if (from.$isFile) {
from = from.absolutePath();
}
let p = this.absolutePath();
return p && from && this.$path.relative(from, p);
}
/**
* Returns a `File` object containing the relative path of this file in relation to
* the `from` file or path.
* @param {String/File} from The base location from which this file is relative.
* @return {File}
*/
relativize (from) {
return this.constructor.from(this.relativePath(from));
}
resolvePath (...parts) {
return this.constructor.resolvePath(this, ...parts);
}
resolve (...parts) {
return this.constructor.resolve(this, ...parts);
}
slashifiedPath () {
return this.path.replace(this.re.backslash, '/');
}
/**
* Replace forward/backward slashes with forward slashes.
* @return {String}
*/
slashify () {
return this.constructor.from(this.slashifiedPath());
}
split () {
return this.constructor.split(this);
}
toString () {
return this.path;
}
terminatedPath (separator, match) {
if (separator == null || separator === true) {
separator = this.constructor.separator;
}
match = match || this.re.slash;
let p = this.path;
if (p && p.length) {
let n = p.length - 1;
let c = p[n];
if (separator) {
if (!match.test(c)) {
p += separator;
}
}
else {
while (n >= 0 && match.test(c)) {
p = p.substr(0, n--);
c = p[n];
}
}
}
return p || '';
}
terminate (separator, match) {
return this.constructor.from(this.terminatedPath(separator, match));
}
unterminatedPath (match) {
return this.terminatedPath(false, match);
}
unterminate (match) {
return this.constructor.from(this.unterminatedPath(match));
}
//-----------------------------------------------------------------
// Path checks
/**
* Compare this `File` to the other `File` or path and return -1, 0 or 1 if this
* file is less-then, equal to or great then the `other`.
* @param {File/String} other The file or path to which to compare this `File`.
* @param {'d'/'f'/false} [first='d'] Pass `'d'` to group directories before files,
* `'f'` to group files before directories or `false` to sort only by path.
* @return {Number} -1, 0 or 1 if this file is, respectively, less-than, equal to
* or great-than the `other`.
*/
compare (other, first) {
other = this.constructor.from(other);
if (!other) {
return 1;
}
if (this._stat && other._stat) {
let p = this.parent;
first = (first === false) ? 0 : (first || 'd');
if (first && p && p.equals(other.parent)) {
// Two files in the same parent folder both w/stats
let d1 = this._stat.isDirectory();
let d2 = other._stat.isDirectory();
if (d1 !== d2) {
let c = d1 ? -1 : 1;
if (first === 'f') {
c = -c;
}
return c;
}
}
}
// Treat '/foo/bar' and '/foo/bar/' as equal (by stripping trailing delimiters)
let a = this.unterminatedPath();
let b = other.unterminatedPath();
// If the platform has case-insensitive file names, ignore case...
if (this.constructor.NOCASE) {
a = a.toLocaleLowerCase();
b = b.toLocaleLowerCase();
}
return (a < b) ? -1 : ((b < a) ? 1 : 0);
}
equals (other) {
let c = this.compare(other);
return c === 0;
}
isAbsolute () {
let p = this.path;
return p ? this.re.abs.test(p) || this.$path.isAbsolute(p) : false;
}
isRelative () {
return this.path ? !this.isAbsolute() : false;
}
prefixes (subPath) {
subPath = this.constructor.from(subPath);
if (subPath) {
// Ensure we don't have trailing slashes ('/foo/bar/' => '/foo/bar')
let a = this.slashify().unterminatedPath();
let b = subPath.slashifiedPath();
if (this.constructor.NOCASE) {
a = a.toLocaleLowerCase();
b = b.toLocaleLowerCase();
}
if (a === b) {
return true;
}
if (b.startsWith(a)) {
// a = '/foo/bar'
// b = '/foo/bar/zip' ==> true
// b = '/foo/barf' ==> false
return b[a.length] === '/';
}
}
return false;
}
//-----------------------------------------------------------------
// File system checks
/**
* Returns a `File.Access` object describing the access available for this file. If
* the file does not exist, or some other error is encountered, the `error` property
* will be set.
*
* let acc = File.from(s).access();
*
* if (acc.rw) {
* // file at location s has R and W permission
* }
* else if (acc.error === 'ENOENT') {
* // no file ...
* }
* else if (acc.error) {
* // some other error
* }
*
* Alternatively:
*
* if (File.from(s).can('rw')) {
* // file at location s has R and W permission
* }
*
* @return {File.Access}
*/
access () {
let st = this.stat();
let Access = this.constructor.Access;
if (st.error) {
return Access.getError(st.error);
}
return Access[st.mode & Access.rwx.mask];
}
/**
* Returns `true` if the desired access is available for this file.
* @param {'r'/'rw'/'rx'/'rwx'/'w'/'wx'/'x'} mode
* @return {Boolean}
*/
can (mode) {
let acc = this.access();
return acc[mode];
}
/**
* Returns `true` if this file exists, `false` if not.
* @return {Boolean}
*/
exists () {
let st = this.stat();
return !st.error;
}
/**
* Returns `true` if the specified path exists relative to this path.
* @param {String} rel A path relative to this path.
* @return {Boolean}
*/
has (rel) {
let f = this.resolve(rel);
return f.exists();
}
/**
* Returns `true` if the specified directory exists relative to this path.
* @param {String} rel A path relative to this path.
* @return {Boolean}
*/
hasDir (rel) {
let f = this.resolve(rel);
return f.isDir();
}
/**
* Returns `true` if the specified file exists relative to this path.
* @param {String} rel A path relative to this path.
* @return {Boolean}
*/
hasFile (rel) {
let f = this.join(rel);
return f.isFile();
}
/**
* Returns `true` if this file is a hidden file.
* @param {Boolean} [asNative] Pass `true` to match native Explorer/Finder meaning
* of hidden state.
* @return {Boolean}
*/
isHidden (asNative) {
const Win = this.constructor.Win;