forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.d
4217 lines (3646 loc) · 132 KB
/
path.d
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
// Written in the D programming language.
/** This module is used to manipulate path strings.
All functions, with the exception of $(LREF expandTilde) (and in some
cases $(LREF absolutePath) and $(LREF relativePath)), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use $(REF isDir, std,file) and
$(REF exists, std,file).
Note that on Windows, both the backslash (``\``) and the slash (``/``)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a $(I new) separator is
added, a backslash will be used. Furthermore, the $(LREF buildNormalizedPath)
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
$(LREF isValidFilename) and $(LREF isValidPath) functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Normalization) $(TD
$(LREF absolutePath)
$(LREF asAbsolutePath)
$(LREF asNormalizedPath)
$(LREF asRelativePath)
$(LREF buildNormalizedPath)
$(LREF buildPath)
$(LREF chainPath)
$(LREF expandTilde)
))
$(TR $(TD Partitioning) $(TD
$(LREF baseName)
$(LREF dirName)
$(LREF dirSeparator)
$(LREF driveName)
$(LREF pathSeparator)
$(LREF pathSplitter)
$(LREF relativePath)
$(LREF rootName)
$(LREF stripDrive)
))
$(TR $(TD Validation) $(TD
$(LREF isAbsolute)
$(LREF isDirSeparator)
$(LREF isRooted)
$(LREF isValidFilename)
$(LREF isValidPath)
))
$(TR $(TD Extension) $(TD
$(LREF defaultExtension)
$(LREF extension)
$(LREF setExtension)
$(LREF stripExtension)
$(LREF withDefaultExtension)
$(LREF withExtension)
))
$(TR $(TD Other) $(TD
$(LREF filenameCharCmp)
$(LREF filenameCmp)
$(LREF globMatch)
$(LREF CaseSensitive)
))
))
Authors:
Lars Tandle Kyllingstad,
$(HTTP digitalmars.com, Walter Bright),
Grzegorz Adam Hankiewicz,
Thomas K$(UUML)hne,
$(HTTP erdani.org, Andrei Alexandrescu)
Copyright:
Copyright (c) 2000-2014, the authors. All rights reserved.
License:
$(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0)
Source:
$(PHOBOSSRC std/path.d)
*/
module std.path;
// FIXME
import std.file; //: getcwd;
static import std.meta;
import std.range.primitives;
import std.traits;
version(unittest)
{
private:
struct TestAliasedString
{
string get() @safe @nogc pure nothrow { return _s; }
alias get this;
@disable this(this);
string _s;
}
bool testAliasedString(alias func, Args...)(string s, Args args)
{
return func(TestAliasedString(s), args) == func(s, args);
}
}
/** String used to separate directory names in a path. Under
POSIX this is a slash, under Windows a backslash.
*/
version(Posix) enum string dirSeparator = "/";
else version(Windows) enum string dirSeparator = "\\";
else static assert(0, "unsupported platform");
/** Path separator string. A colon under POSIX, a semicolon
under Windows.
*/
version(Posix) enum string pathSeparator = ":";
else version(Windows) enum string pathSeparator = ";";
else static assert(0, "unsupported platform");
/** Determines whether the given character is a directory separator.
On Windows, this includes both ``\`` and ``/``.
On POSIX, it's just ``/``.
*/
bool isDirSeparator(dchar c) @safe pure nothrow @nogc
{
if (c == '/') return true;
version(Windows) if (c == '\\') return true;
return false;
}
///
@safe pure nothrow @nogc unittest
{
version(Windows)
{
assert( '/'.isDirSeparator);
assert( '\\'.isDirSeparator);
}
else
{
assert( '/'.isDirSeparator);
assert(!'\\'.isDirSeparator);
}
}
/* Determines whether the given character is a drive separator.
On Windows, this is true if c is the ':' character that separates
the drive letter from the rest of the path. On POSIX, this always
returns false.
*/
private bool isDriveSeparator(dchar c) @safe pure nothrow @nogc
{
version(Windows) return c == ':';
else return false;
}
/* Combines the isDirSeparator and isDriveSeparator tests. */
version(Windows) private bool isSeparator(dchar c) @safe pure nothrow @nogc
{
return isDirSeparator(c) || isDriveSeparator(c);
}
version(Posix) private alias isSeparator = isDirSeparator;
/* Helper function that determines the position of the last
drive/directory separator in a string. Returns -1 if none
is found.
*/
private ptrdiff_t lastSeparator(R)(R path)
if (isRandomAccessRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
auto i = (cast(ptrdiff_t) path.length) - 1;
while (i >= 0 && !isSeparator(path[i])) --i;
return i;
}
version (Windows)
{
private bool isUNC(R)(R path)
if (isRandomAccessRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
return path.length >= 3 && isDirSeparator(path[0]) && isDirSeparator(path[1])
&& !isDirSeparator(path[2]);
}
private ptrdiff_t uncRootLength(R)(R path)
if (isRandomAccessRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
in { assert(isUNC(path)); }
do
{
ptrdiff_t i = 3;
while (i < path.length && !isDirSeparator(path[i])) ++i;
if (i < path.length)
{
auto j = i;
do { ++j; } while (j < path.length && isDirSeparator(path[j]));
if (j < path.length)
{
do { ++j; } while (j < path.length && !isDirSeparator(path[j]));
i = j;
}
}
return i;
}
private bool hasDrive(R)(R path)
if (isRandomAccessRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
return path.length >= 2 && isDriveSeparator(path[1]);
}
private bool isDriveRoot(R)(R path)
if (isRandomAccessRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
return path.length >= 3 && isDriveSeparator(path[1])
&& isDirSeparator(path[2]);
}
}
/* Helper functions that strip leading/trailing slashes and backslashes
from a path.
*/
private auto ltrimDirSeparators(R)(R path)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
static if (isRandomAccessRange!R && hasSlicing!R || isNarrowString!R)
{
int i = 0;
while (i < path.length && isDirSeparator(path[i]))
++i;
return path[i .. path.length];
}
else
{
while (!path.empty && isDirSeparator(path.front))
path.popFront();
return path;
}
}
@safe unittest
{
import std.array;
import std.utf : byDchar;
assert(ltrimDirSeparators("//abc//").array == "abc//");
assert(ltrimDirSeparators("//abc//"d).array == "abc//"d);
assert(ltrimDirSeparators("//abc//".byDchar).array == "abc//"d);
}
private auto rtrimDirSeparators(R)(R path)
if (isBidirectionalRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
static if (isRandomAccessRange!R && hasSlicing!R && hasLength!R || isNarrowString!R)
{
auto i = (cast(ptrdiff_t) path.length) - 1;
while (i >= 0 && isDirSeparator(path[i]))
--i;
return path[0 .. i+1];
}
else
{
while (!path.empty && isDirSeparator(path.back))
path.popBack();
return path;
}
}
@safe unittest
{
import std.array;
import std.utf : byDchar;
assert(rtrimDirSeparators("//abc//").array == "//abc");
assert(rtrimDirSeparators("//abc//"d).array == "//abc"d);
assert(rtrimDirSeparators(MockBiRange!char("//abc//")).array == "//abc");
}
private auto trimDirSeparators(R)(R path)
if (isBidirectionalRange!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
return ltrimDirSeparators(rtrimDirSeparators(path));
}
@safe unittest
{
import std.array;
import std.utf : byDchar;
assert(trimDirSeparators("//abc//").array == "abc");
assert(trimDirSeparators("//abc//"d).array == "abc"d);
assert(trimDirSeparators(MockBiRange!char("//abc//")).array == "abc");
}
/** This `enum` is used as a template argument to functions which
compare file names, and determines whether the comparison is
case sensitive or not.
*/
enum CaseSensitive : bool
{
/// File names are case insensitive
no = false,
/// File names are case sensitive
yes = true,
/** The default (or most common) setting for the current platform.
That is, `no` on Windows and Mac OS X, and `yes` on all
POSIX systems except OS X (Linux, *BSD, etc.).
*/
osDefault = osDefaultCaseSensitivity
}
///
@safe unittest
{
assert(baseName!(CaseSensitive.no)("dir/file.EXT", ".ext") == "file");
assert(baseName!(CaseSensitive.yes)("dir/file.EXT", ".ext") != "file");
version(Posix)
assert(relativePath!(CaseSensitive.no)("/FOO/bar", "/foo/baz") == "../bar");
else
assert(relativePath!(CaseSensitive.no)(`c:\FOO\bar`, `c:\foo\baz`) == `..\bar`);
}
version (Windows) private enum osDefaultCaseSensitivity = false;
else version (OSX) private enum osDefaultCaseSensitivity = false;
else version (Posix) private enum osDefaultCaseSensitivity = true;
else static assert(0);
/**
Params:
cs = Whether or not suffix matching is case-sensitive.
path = A path name. It can be a string, or any random-access range of
characters.
suffix = An optional suffix to be removed from the file name.
Returns: The name of the file in the path name, without any leading
directory and with an optional suffix chopped off.
If `suffix` is specified, it will be compared to `path`
using `filenameCmp!cs`,
where `cs` is an optional template parameter determining whether
the comparison is case sensitive or not. See the
$(LREF filenameCmp) documentation for details.
Note:
This function $(I only) strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use $(LREF stripExtension).
To obtain the filename without leading directories and without
an extension, combine the functions like this:
---
assert(baseName(stripExtension("dir/file.ext")) == "file");
---
Standards:
This function complies with
$(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html,
the POSIX requirements for the 'basename' shell utility)
(with suitable adaptations for Windows paths).
*/
auto baseName(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)
{
return _baseName(path);
}
/// ditto
auto baseName(C)(C[] path)
if (isSomeChar!C)
{
return _baseName(path);
}
/// ditto
inout(C)[] baseName(CaseSensitive cs = CaseSensitive.osDefault, C, C1)
(inout(C)[] path, in C1[] suffix)
@safe pure //TODO: nothrow (because of filenameCmp())
if (isSomeChar!C && isSomeChar!C1)
{
auto p = baseName(path);
if (p.length > suffix.length
&& filenameCmp!cs(cast(const(C)[])p[$-suffix.length .. $], suffix) == 0)
{
return p[0 .. $-suffix.length];
}
else return p;
}
///
@safe unittest
{
assert(baseName("dir/file.ext") == "file.ext");
assert(baseName("dir/file.ext", ".ext") == "file");
assert(baseName("dir/file.ext", ".xyz") == "file.ext");
assert(baseName("dir/filename", "name") == "file");
assert(baseName("dir/subdir/") == "subdir");
version (Windows)
{
assert(baseName(`d:file.ext`) == "file.ext");
assert(baseName(`d:\dir\file.ext`) == "file.ext");
}
}
@safe unittest
{
assert(baseName("").empty);
assert(baseName("file.ext"w) == "file.ext");
assert(baseName("file.ext"d, ".ext") == "file");
assert(baseName("file", "file"w.dup) == "file");
assert(baseName("dir/file.ext"d.dup) == "file.ext");
assert(baseName("dir/file.ext", ".ext"d) == "file");
assert(baseName("dir/file"w, "file"d) == "file");
assert(baseName("dir///subdir////") == "subdir");
assert(baseName("dir/subdir.ext/", ".ext") == "subdir");
assert(baseName("dir/subdir/".dup, "subdir") == "subdir");
assert(baseName("/"w.dup) == "/");
assert(baseName("//"d.dup) == "/");
assert(baseName("///") == "/");
assert(baseName!(CaseSensitive.yes)("file.ext", ".EXT") == "file.ext");
assert(baseName!(CaseSensitive.no)("file.ext", ".EXT") == "file");
{
auto r = MockRange!(immutable(char))(`dir/file.ext`);
auto s = r.baseName();
foreach (i, c; `file`)
assert(s[i] == c);
}
version (Windows)
{
assert(baseName(`dir\file.ext`) == `file.ext`);
assert(baseName(`dir\file.ext`, `.ext`) == `file`);
assert(baseName(`dir\file`, `file`) == `file`);
assert(baseName(`d:file.ext`) == `file.ext`);
assert(baseName(`d:file.ext`, `.ext`) == `file`);
assert(baseName(`d:file`, `file`) == `file`);
assert(baseName(`dir\\subdir\\\`) == `subdir`);
assert(baseName(`dir\subdir.ext\`, `.ext`) == `subdir`);
assert(baseName(`dir\subdir\`, `subdir`) == `subdir`);
assert(baseName(`\`) == `\`);
assert(baseName(`\\`) == `\`);
assert(baseName(`\\\`) == `\`);
assert(baseName(`d:\`) == `\`);
assert(baseName(`d:`).empty);
assert(baseName(`\\server\share\file`) == `file`);
assert(baseName(`\\server\share\`) == `\`);
assert(baseName(`\\server\share`) == `\`);
auto r = MockRange!(immutable(char))(`\\server\share`);
auto s = r.baseName();
foreach (i, c; `\`)
assert(s[i] == c);
}
assert(baseName(stripExtension("dir/file.ext")) == "file");
static assert(baseName("dir/file.ext") == "file.ext");
static assert(baseName("dir/file.ext", ".ext") == "file");
static struct DirEntry { string s; alias s this; }
assert(baseName(DirEntry("dir/file.ext")) == "file.ext");
}
@safe unittest
{
assert(testAliasedString!baseName("file"));
enum S : string { a = "file/path/to/test" }
assert(S.a.baseName == "test");
char[S.a.length] sa = S.a[];
assert(sa.baseName == "test");
}
private R _baseName(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) || isNarrowString!R)
{
auto p1 = stripDrive(path);
if (p1.empty)
{
version (Windows) if (isUNC(path))
return path[0 .. 1];
static if (isSomeString!R)
return null;
else
return p1; // which is empty
}
auto p2 = rtrimDirSeparators(p1);
if (p2.empty) return p1[0 .. 1];
return p2[lastSeparator(p2)+1 .. p2.length];
}
/** Returns the parent directory of path. On Windows, this
includes the drive letter if present.
Params:
path = A path name.
Returns:
A slice of `path` or ".".
Standards:
This function complies with
$(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
the POSIX requirements for the 'dirname' shell utility)
(with suitable adaptations for Windows paths).
*/
auto dirName(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)
{
return _dirName(path);
}
/// ditto
auto dirName(C)(C[] path)
if (isSomeChar!C)
{
return _dirName(path);
}
///
@safe unittest
{
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
}
@safe unittest
{
assert(testAliasedString!dirName("file"));
enum S : string { a = "file/path/to/test" }
assert(S.a.dirName == "file/path/to");
char[S.a.length] sa = S.a[];
assert(sa.dirName == "file/path/to");
}
@safe unittest
{
static assert(dirName("dir/file") == "dir");
import std.array;
import std.utf : byChar, byWchar, byDchar;
assert(dirName("".byChar).array == ".");
assert(dirName("file"w.byWchar).array == "."w);
assert(dirName("dir/"d.byDchar).array == "."d);
assert(dirName("dir///".byChar).array == ".");
assert(dirName("dir/subdir/".byChar).array == "dir");
assert(dirName("/dir/file"w.byWchar).array == "/dir"w);
assert(dirName("/file"d.byDchar).array == "/"d);
assert(dirName("/".byChar).array == "/");
assert(dirName("///".byChar).array == "/");
version (Windows)
{
assert(dirName(`dir\`.byChar).array == `.`);
assert(dirName(`dir\\\`.byChar).array == `.`);
assert(dirName(`dir\file`.byChar).array == `dir`);
assert(dirName(`dir\\\file`.byChar).array == `dir`);
assert(dirName(`dir\subdir\`.byChar).array == `dir`);
assert(dirName(`\dir\file`.byChar).array == `\dir`);
assert(dirName(`\file`.byChar).array == `\`);
assert(dirName(`\`.byChar).array == `\`);
assert(dirName(`\\\`.byChar).array == `\`);
assert(dirName(`d:`.byChar).array == `d:`);
assert(dirName(`d:file`.byChar).array == `d:`);
assert(dirName(`d:\`.byChar).array == `d:\`);
assert(dirName(`d:\file`.byChar).array == `d:\`);
assert(dirName(`d:\dir\file`.byChar).array == `d:\dir`);
assert(dirName(`\\server\share\dir\file`.byChar).array == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`.byChar).array == `\\server\share`);
assert(dirName(`\\server\share`.byChar).array == `\\server\share`);
}
//static assert(dirName("dir/file".byChar).array == "dir");
}
private auto _dirName(R)(R path)
{
static auto result(bool dot, typeof(path[0 .. 1]) p)
{
static if (isSomeString!R)
return dot ? "." : p;
else
{
import std.range : choose, only;
return choose(dot, only(cast(ElementEncodingType!R)'.'), p);
}
}
if (path.empty)
return result(true, path[0 .. 0]);
auto p = rtrimDirSeparators(path);
if (p.empty)
return result(false, path[0 .. 1]);
version (Windows)
{
if (isUNC(p) && uncRootLength(p) == p.length)
return result(false, p);
if (p.length == 2 && isDriveSeparator(p[1]) && path.length > 2)
return result(false, path[0 .. 3]);
}
auto i = lastSeparator(p);
if (i == -1)
return result(true, p);
if (i == 0)
return result(false, p[0 .. 1]);
version (Windows)
{
// If the directory part is either d: or d:\
// do not chop off the last symbol.
if (isDriveSeparator(p[i]) || isDriveSeparator(p[i-1]))
return result(false, p[0 .. i+1]);
}
// Remove any remaining trailing (back)slashes.
return result(false, rtrimDirSeparators(p[0 .. i]));
}
/** Returns the root directory of the specified path, or `null` if the
path is not rooted.
Params:
path = A path name.
Returns:
A slice of `path`.
*/
auto rootName(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)
{
return _rootName(path);
}
/// ditto
auto rootName(C)(C[] path)
if (isSomeChar!C)
{
return _rootName(path);
}
///
@safe unittest
{
assert(rootName("") is null);
assert(rootName("foo") is null);
assert(rootName("/") == "/");
assert(rootName("/foo/bar") == "/");
version (Windows)
{
assert(rootName("d:foo") is null);
assert(rootName(`d:\foo`) == `d:\`);
assert(rootName(`\\server\share\foo`) == `\\server\share`);
assert(rootName(`\\server\share`) == `\\server\share`);
}
}
@safe unittest
{
assert(testAliasedString!rootName("/foo/bar"));
enum S : string { a = "/foo/bar" }
assert(S.a.rootName == "/");
char[S.a.length] sa = S.a[];
assert(sa.rootName == "/");
}
@safe unittest
{
import std.array;
import std.utf : byChar;
assert(rootName("".byChar).array == "");
assert(rootName("foo".byChar).array == "");
assert(rootName("/".byChar).array == "/");
assert(rootName("/foo/bar".byChar).array == "/");
version (Windows)
{
assert(rootName("d:foo".byChar).array == "");
assert(rootName(`d:\foo`.byChar).array == `d:\`);
assert(rootName(`\\server\share\foo`.byChar).array == `\\server\share`);
assert(rootName(`\\server\share`.byChar).array == `\\server\share`);
}
}
private auto _rootName(R)(R path)
{
if (path.empty)
goto Lnull;
version (Posix)
{
if (isDirSeparator(path[0])) return path[0 .. 1];
}
else version (Windows)
{
if (isDirSeparator(path[0]))
{
if (isUNC(path)) return path[0 .. uncRootLength(path)];
else return path[0 .. 1];
}
else if (path.length >= 3 && isDriveSeparator(path[1]) &&
isDirSeparator(path[2]))
{
return path[0 .. 3];
}
}
else static assert(0, "unsupported platform");
assert(!isRooted(path));
Lnull:
static if (is(StringTypeOf!R))
return null; // legacy code may rely on null return rather than slice
else
return path[0 .. 0];
}
/**
Get the drive portion of a path.
Params:
path = string or range of characters
Returns:
A slice of `path` that is the drive, or an empty range if the drive
is not specified. In the case of UNC paths, the network share
is returned.
Always returns an empty range on POSIX.
*/
auto driveName(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)
{
return _driveName(path);
}
/// ditto
auto driveName(C)(C[] path)
if (isSomeChar!C)
{
return _driveName(path);
}
///
@safe unittest
{
import std.range : empty;
version (Posix) assert(driveName("c:/foo").empty);
version (Windows)
{
assert(driveName(`dir\file`).empty);
assert(driveName(`d:file`) == "d:");
assert(driveName(`d:\file`) == "d:");
assert(driveName("d:") == "d:");
assert(driveName(`\\server\share\file`) == `\\server\share`);
assert(driveName(`\\server\share\`) == `\\server\share`);
assert(driveName(`\\server\share`) == `\\server\share`);
static assert(driveName(`d:\file`) == "d:");
}
}
@safe unittest
{
assert(testAliasedString!driveName("d:/file"));
version(Posix)
immutable result = "";
else version(Windows)
immutable result = "d:";
enum S : string { a = "d:/file" }
assert(S.a.driveName == result);
char[S.a.length] sa = S.a[];
assert(sa.driveName == result);
}
@safe unittest
{
import std.array;
import std.utf : byChar;
version (Posix) assert(driveName("c:/foo".byChar).empty);
version (Windows)
{
assert(driveName(`dir\file`.byChar).empty);
assert(driveName(`d:file`.byChar).array == "d:");
assert(driveName(`d:\file`.byChar).array == "d:");
assert(driveName("d:".byChar).array == "d:");
assert(driveName(`\\server\share\file`.byChar).array == `\\server\share`);
assert(driveName(`\\server\share\`.byChar).array == `\\server\share`);
assert(driveName(`\\server\share`.byChar).array == `\\server\share`);
static assert(driveName(`d:\file`).array == "d:");
}
}
private auto _driveName(R)(R path)
{
version (Windows)
{
if (hasDrive(path))
return path[0 .. 2];
else if (isUNC(path))
return path[0 .. uncRootLength(path)];
}
static if (isSomeString!R)
return cast(ElementEncodingType!R[]) null; // legacy code may rely on null return rather than slice
else
return path[0 .. 0];
}
/** Strips the drive from a Windows path. On POSIX, the path is returned
unaltered.
Params:
path = A pathname
Returns: A slice of path without the drive component.
*/
auto stripDrive(R)(R path)
if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)
{
return _stripDrive(path);
}
/// ditto
auto stripDrive(C)(C[] path)
if (isSomeChar!C)
{
return _stripDrive(path);
}
///
@safe unittest
{
version (Windows)
{
assert(stripDrive(`d:\dir\file`) == `\dir\file`);
assert(stripDrive(`\\server\share\dir\file`) == `\dir\file`);
}
}
@safe unittest
{
assert(testAliasedString!stripDrive("d:/dir/file"));
version(Posix)
immutable result = "d:/dir/file";
else version(Windows)
immutable result = "/dir/file";
enum S : string { a = "d:/dir/file" }
assert(S.a.stripDrive == result);
char[S.a.length] sa = S.a[];
assert(sa.stripDrive == result);
}
@safe unittest
{
version(Windows)
{
assert(stripDrive(`d:\dir\file`) == `\dir\file`);
assert(stripDrive(`\\server\share\dir\file`) == `\dir\file`);
static assert(stripDrive(`d:\dir\file`) == `\dir\file`);
auto r = MockRange!(immutable(char))(`d:\dir\file`);
auto s = r.stripDrive();
foreach (i, c; `\dir\file`)
assert(s[i] == c);
}
version(Posix)
{
assert(stripDrive(`d:\dir\file`) == `d:\dir\file`);
auto r = MockRange!(immutable(char))(`d:\dir\file`);
auto s = r.stripDrive();
foreach (i, c; `d:\dir\file`)
assert(s[i] == c);
}
}
private auto _stripDrive(R)(R path)
{
version(Windows)
{
if (hasDrive!(BaseOf!R)(path)) return path[2 .. path.length];
else if (isUNC!(BaseOf!R)(path)) return path[uncRootLength!(BaseOf!R)(path) .. path.length];
}
return path;
}
/* Helper function that returns the position of the filename/extension
separator dot in path.
Params:
path = file spec as string or indexable range
Returns:
index of extension separator (the dot), or -1 if not found
*/
private ptrdiff_t extSeparatorPos(R)(const R path)
if (isRandomAccessRange!R && hasLength!R && isSomeChar!(ElementType!R) ||
isNarrowString!R)
{
for (auto i = path.length; i-- > 0 && !isSeparator(path[i]); )
{
if (path[i] == '.' && i > 0 && !isSeparator(path[i-1]))
return i;
}
return -1;
}