-
Notifications
You must be signed in to change notification settings - Fork 19
/
NiceIO.cs
2775 lines (2389 loc) · 123 KB
/
NiceIO.cs
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
// The MIT License(MIT)
// =====================
//
// Copyright © `2015-2017` `Lucas Meijer`
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
using static NiceIO.NPath;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
//Lets make it hard to accidentally use System.IO.File & System.IO.Directly, and require that it is always completely spelled out.
using File = NiceIO.Do_Not_Use_File_Directly_Use_FileSystem_Active_Instead;
using Directory = NiceIO.Do_Not_Use_Directory_Directly_Use_FileSystem_Active_Instead;
namespace NiceIO
{
/// <summary>
/// A filesystem path.
/// </summary>
/// <remarks>
/// The path can be absolute or relative; the entity it refers to could be a file or a directory, and may or may not
/// actually exist in the filesystem.
/// </remarks>
//niceio gets included willy nilly by various projects, and they end up adding NPath to their public API without realizing it, which can lead to
//very annoying incompatibilities if you're using two projects that happen to do this. Let's make sure the default that it will not be public,
//and in the one or two places that we want it to be public be explicit about doing so
[DebuggerDisplay("{" + nameof(_path) + "}")]
[DataContract]
#if NICEIO_PUBLIC
public class NPath
#else
internal class NPath
#endif
: IComparable, IEquatable<NPath>
{
// Assume FS is case sensitive on Linux, and case insensitive on macOS and Windows.
//WARNING: Do not use FileSystem.Active to look for /proc. Since we're doing this in a static initializer, the k_IsWindows is not guaranteed to be set yet,
//and you can get very hard to track down situations where the currently active filesystem on windows is actually set to PosixFileSystem.
static readonly bool k_IsCaseSensitiveFileSystem = !CalculateIsWindows() && System.IO.Directory.Exists("/proc");
static readonly bool k_IsWindows = CalculateIsWindows();
private static bool CalculateIsWindows() => Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.Win32NT;
private static bool CalculateIsWindows10()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return false;
// Environment.OSVersion will only return versions higher than 6.2 if the owning process has been manifested as compatible with Windows 10:
// https://docs.microsoft.com/en-us/windows/win32/w8cookbook/windows-version-check
//
// Because NiceIO is a library, not its own executable, we are at the mercy of the consumer processes to manifest themselves correctly - and
// many of them don't. So, using Environment.OSVersion is not really safe.
//
// StackOverflow suggests using the file version info for a core OS file, such as kernel32.dll:
// https://stackoverflow.com/a/44665238/860530
var kernel32 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "kernel32.dll");
var versionInfo = FileVersionInfo.GetVersionInfo(kernel32);
return versionInfo.ProductMajorPart >= 10;
}
static readonly StringComparison PathStringComparison =
k_IsCaseSensitiveFileSystem ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
[DataMember]
private readonly string _path;
static NPath Empty => new NPath("");
#region construction
/// <summary>
/// Create a new NPath.
/// </summary>
/// <param name="path">The path that this NPath should represent.</param>
public NPath(string path)
{
if (path == null)
throw new ArgumentNullException();
_path = MakeCompletelyWellFormatted(path);
}
//keep this private, we need to guarantee all NPath's out there are guaranteed well formed.
private NPath(string path, bool guaranteed_well_formed)
{
if (!guaranteed_well_formed)
throw new ArgumentException("For not well formed paths, use the public NPath constructor");
_path = path;
}
static bool IsUNCPath(string path)
{
return path.Length > 2 && path[0] == '\\' && path[1] == '\\';
}
static string ConvertToForwardSlashPath(string path)
{
if (IsUNCPath(path)) // UNC path
return @"\\" + path.Substring(2).Replace(@"\", @"/");
return path.Replace(@"\", @"/");
}
static string MakeCompletelyWellFormatted(string path, bool doubleDotsAreCollapsed = false)
{
if (path == ".")
return ".";
if (path.Length == 0)
return ".";
var numberOfForwardSlashes = 0;
var hasNonDotsOrSeparators = false;
var startsWithDot = false;
char previousChar = '\0';
for (int i = 0; i != path.Length; i++)
{
var c = path[i];
var nextChar = path.Length > (i + 1) ? path[i + 1] : '\0';
var isDot = c == '.';
if (isDot && i == 0)
startsWithDot = true;
var isSlash = IsSlash(c);
hasNonDotsOrSeparators |= !isDot && !isSlash;
// MakeCompletelyWellFormatted + CollapseDoubleDots is fairly expensive, so only do it when needed:
// If we have a "..", that is not just a bunch of "../.." in front of the path and nowhere else
// (these have nothing to collapse on anyway)
if (!doubleDotsAreCollapsed && (hasNonDotsOrSeparators || !startsWithDot) && isDot &&
previousChar == '.')
return MakeCompletelyWellFormatted(CollapseDoubleDots(path), true);
if (isDot && (IsSlash(previousChar) || previousChar == '\0') && (IsSlash(nextChar) || nextChar == '\0'))
return MakeCompletelyWellFormatted(CollapseSingleDots(path));
if (c == '\\' && (!IsUNCPath(path) || i >= 2))
return MakeCompletelyWellFormatted(ConvertToForwardSlashPath(path));
if (c == '/' && previousChar == '/')
return MakeCompletelyWellFormatted(CollapseDoubleSlashes(path));
if (c == '/')
numberOfForwardSlashes++;
previousChar = c;
}
var lastChar = path[path.Length - 1];
var secondToLastChar = path.Length >= 2 ? path[path.Length - 2] : '\0';
// Remove trailing (non-root significant slash)
if (lastChar == '/')
{
// this is a root path
if (secondToLastChar == '\0' || secondToLastChar == ':')
return path;
if (numberOfForwardSlashes == 1 && IsUNCPath(path))
return path;
return path.Substring(0, path.Length - 1);
}
if (numberOfForwardSlashes == 0 && IsUNCPath(path))
return path + "/";
return path;
}
static string CollapseSingleDots(string path)
{
var result = ConvertToForwardSlashPath(path).Replace("/./", "/");
if (result.StartsWith("./", StringComparison.Ordinal))
result = result.Substring(2);
if (result.EndsWith("/.", StringComparison.Ordinal))
result = result.Substring(0, result.Length - 2);
return result;
}
static string CollapseDoubleSlashes(string path)
{
return ConvertToForwardSlashPath(path).Replace("//", "/");
}
static string CollapseDoubleDots(string path)
{
path = ConvertToForwardSlashPath(path);
var isRegularRoot = path[0] == '/';
var isRootWithDriveLetter = (path[1] == ':' && path[2] == '/');
var isUNCRoot = IsUNCPath(path);
bool isRoot = isRegularRoot || isRootWithDriveLetter || isUNCRoot;
var startIndex = 0;
if (isRoot) startIndex = 1;
if (isRootWithDriveLetter) startIndex = 3;
if (isUNCRoot) startIndex = path.IndexOf('/') + 1;
var stack = new Stack<string>();
int segmentStart = startIndex;
for (int i = startIndex; i != path.Length; i++)
{
if (path[i] == '/' || i == path.Length - 1)
{
int extra = (i == path.Length - 1) ? 1 : 0;
var substring = path.Substring(segmentStart, i - segmentStart + extra);
if (substring == "..")
{
if (stack.Count == 0)
{
if (isRoot)
throw new ArgumentException(
$"Cannot parse path because it's ..'ing beyond the root: {path}");
stack.Push(substring);
}
else
{
if (stack.Peek() == "..")
stack.Push(substring);
else
stack.Pop();
}
}
else
stack.Push(substring);
segmentStart = i + 1;
}
}
return path.Substring(0, startIndex) + string.Join("/", stack.Reverse().ToArray());
}
const int MethodImplOptions_AggressiveInlining = 256; // enum value is only in .NET 4.5+
[MethodImpl(MethodImplOptions_AggressiveInlining)]
private static bool IsSlash(char c) => c == '/' || c == '\\';
/// <summary>
/// Create a new NPath by appending a path fragment.
/// </summary>
/// <param name="append">The path fragment to append. This can be a filename, or a whole relative path.</param>
/// <returns>A new NPath which is the existing path with the fragment appended.</returns>
public NPath Combine(string append)
{
if (IsSlash(append[0]))
throw new ArgumentException($"You cannot .Combine a non-relative path: {append}");
return new NPath(_path + "/" + append);
}
/// <summary>
/// Create a new NPath by appending two path fragments, one after the other.
/// </summary>
/// <param name="append1">The first path fragment to append.</param>
/// <param name="append2">The second path fragment to append.</param>
/// <returns>A new NPath which is the existing path with the first fragment appended, then the second fragment appended.</returns>
public NPath Combine(string append1, string append2)
{
return new NPath(_path + "/" + append1 + "/" + append2);
}
/// <summary>
/// Create a new NPath by appending a path fragment.
/// </summary>
/// <param name="append">The path fragment to append.</param>
/// <returns>A new NPath which is the existing path with the fragment appended.</returns>
public NPath Combine(NPath append)
{
if (append == null)
throw new ArgumentNullException(nameof(append));
var firstChar = append._path[0];
if (IsSlash(firstChar))
throw new ArgumentException($"You cannot .Combine a non-relative path: {append._path}");
//if the to-append path starts by going up directories, we need to run our normalizing constructor, if not, we can take the fast path
if (firstChar == '.' || _path[0] == '.' || _path.Length == 1)
return new NPath(_path + "/" + append._path);
return new NPath(_path + "/" + append, true);
}
/// <summary>
/// Create a new NPath by appending multiple path fragments.
/// </summary>
/// <param name="append">The path fragments to append, in order.</param>
/// <returns>A new NPath which is this existing path with all the supplied path fragments appended, in order.</returns>
public NPath Combine(params NPath[] append)
{
var sb = new StringBuilder(ToString());
foreach (var a in append)
{
if (!a.IsRelative)
throw new ArgumentException($"You cannot .Combine a non-relative path: {a}");
sb.Append("/");
sb.Append(a);
}
return new NPath(sb.ToString());
}
/// <summary>
/// The parent path fragment (i.e. the directory) of the path.
/// </summary>
public NPath Parent
{
get
{
if (IsRoot)
throw new ArgumentException($"Parent invoked on {this}");
for (int i = _path.Length - 1; i >= 0; i--)
{
if (i == 0)
return _path[0] == '/' ? new NPath("/") : new NPath("");
if (_path[i] != '/') continue;
var isRooted = _path[i - 1] == ':' || _path[0] == '/';
var length = isRooted ? (i + 1) : i;
var substring = _path.Substring(0, length);
return new NPath(substring);
}
return Empty;
}
}
/// <summary>
/// Create a new NPath by computing the existing path relative to some other base path.
/// </summary>
/// <param name="path">The base path that the result should be relative to.</param>
/// <returns>A new NPath, which refers to the same target as the existing path, but is described relative to the given base path.</returns>
public NPath RelativeTo(NPath path)
{
if (IsRelative || path.IsRelative)
return MakeAbsolute().RelativeTo(path.MakeAbsolute());
var thisString = _path;
var pathString = path._path;
if (thisString == pathString)
return ".";
if (!HasSameDriveLetter(path) || !HasSameUNCServerName(path))
return this;
if (path.IsRoot)
return new NPath(thisString.Substring(pathString.Length));
if (thisString.StartsWith(pathString, PathStringComparison))
{
if (thisString.Length >= pathString.Length && (IsSlash(thisString[pathString.Length])))
return new NPath(thisString.Substring(Math.Min(pathString.Length + 1, thisString.Length)));
}
var sb = new StringBuilder();
foreach (var parent in path.RecursiveParents.ToArray())
{
sb.Append("../");
if (IsChildOf(parent))
{
sb.Append(thisString.Substring(parent.ToString().Length));
return new NPath(sb.ToString());
}
}
throw new ArgumentException();
}
/// <summary>
/// Create an NPath by changing the extension of this one.
/// </summary>
/// <param name="extension">The new extension to use. Starting it with a "." character is optional. If you pass an empty string, the resulting path will have the extension stripped entirely, including the dot character.</param>
/// <returns>A new NPath which is the existing path but with the new extension at the end.</returns>
public NPath ChangeExtension(string extension)
{
ThrowIfRoot();
var s = ToString();
int lastDot = -1;
for (int i = s.Length - 1; i >= 0; i--)
{
if (s[i] == '.')
{
lastDot = i;
break;
}
if (s[i] == '/')
break;
}
var newExtension = extension.Length == 0 ? extension : WithDot(extension);
if (lastDot == -1)
return s + newExtension;
return s.Substring(0, lastDot) + newExtension;
}
#endregion construction
#region inspection
/// <summary>
/// Whether this path is relative (i.e. not absolute) or not.
/// </summary>
public bool IsRelative
{
get
{
if (_path[0] == '/')
return false;
if (_path.Length >= 3 && _path[1] == ':' && _path[2] == '/')
return false;
if (_path[0] == '\\')
return false;
return true;
}
}
/// <summary>
/// The name of the file or directory given at the end of this path, including any extension.
/// </summary>
public string FileName
{
get
{
ThrowIfRoot();
if (_path.Length == 0)
return string.Empty;
if (_path == ".")
return string.Empty;
for (int i = _path.Length - 1; i >= 0; i--)
{
if (_path[i] == '/')
{
return i == _path.Length - 1 ? string.Empty : _path.Substring(i + 1);
}
}
return _path;
}
}
/// <summary>
/// The name of the file or directory given at the end of this path, excluding the extension.
/// </summary>
public string FileNameWithoutExtension => Path.GetFileNameWithoutExtension(FileName);
/// <summary>
/// Determines whether the given path is, or is a child of, a directory with the given name.
/// </summary>
/// <param name="dir">The name of the directory to search for.</param>
/// <returns>True if the path describes a file/directory that is or is a child of a directory with the given name; false otherwise.</returns>
public bool HasDirectory(string dir)
{
if (dir.Contains("/") || dir.Contains("\\"))
throw new ArgumentException($"Directory cannot contain slash {dir}");
if (dir == ".")
throw new ArgumentException("Single dot is not an allowed argument");
if (_path.StartsWith(dir + "/", PathStringComparison))
return true;
if (_path.EndsWith("/" + dir, PathStringComparison))
return true;
return _path.Contains("/" + dir + "/");
}
/// <summary>
/// The depth of the path, determined by the number of path separators present.
/// </summary>
public int Depth
{
get
{
if (IsRoot)
return 0;
if (IsCurrentDir)
return 0;
var depth = IsRelative ? 1 : 0;
for (var i = 0; i != _path.Length; i++)
{
if (_path[i] == '/')
depth++;
}
return depth;
}
}
/// <summary>
/// Tests whether the path is the current directory string ".".
/// </summary>
public bool IsCurrentDir => ToString() == ".";
/// <summary>
/// Tests whether the path exists.
/// </summary>
/// <param name="append">An optional path fragment to append before testing.</param>
/// <returns>True if the path (with optional appended fragment) exists, false otherwise.</returns>
public bool Exists(NPath append = null)
{
return FileExists(append) || DirectoryExists(append);
}
/// <summary>
/// Tests whether the path exists and is a directory.
/// </summary>
/// <param name="append">An optional path fragment to append before testing.</param>
/// <returns>True if the path (with optional appended fragment) exists and is a directory, false otherwise.</returns>
public bool DirectoryExists(NPath append = null) => FileSystem.Active.Directory_Exists(append != null ? Combine(append) : this);
/// <summary>
/// Tests whether the path exists and is a file.
/// </summary>
/// <param name="append">An optional path fragment to append before testing.</param>
/// <returns>True if the path (with optional appended fragment) exists and is a file, false otherwise.</returns>
public bool FileExists(NPath append = null) => FileSystem.Active.File_Exists(append != null ? Combine(append) : this);
/// <summary>
/// The extension of the file, excluding the initial "." character.
/// </summary>
public string Extension
{
get
{
if (IsRoot)
throw new ArgumentException("A root directory does not have an extension");
for (int i = _path.Length - 1; i >= 0; i--)
{
var c = _path[i];
if (c == '.' || c == '/')
return _path.Substring(i + 1);
}
return string.Empty;
}
}
/// <summary>
/// UNC server name of the path, if present. Null if not present.
/// </summary>
public string UNCServerName
{
get
{
if (!IsUNC)
return null;
var indexOfFirstSlash = _path.IndexOf('/');
if (indexOfFirstSlash < 0)
indexOfFirstSlash = _path.Length;
return _path.Substring(2, indexOfFirstSlash - 2);
}
}
bool HasSameUNCServerName(NPath other) => UNCServerName == other.UNCServerName;
/// <summary>
/// The Windows drive letter of the path, if present. Null if not present.
/// </summary>
public string DriveLetter => _path.Length >= 2 && _path[1] == ':' ? _path[0].ToString() : null;
bool HasSameDriveLetter(NPath other) => DriveLetter == other.DriveLetter;
/// <summary>
/// Provides a quoted version of the path as a string, with the requested path separator type.
/// </summary>
/// <param name="slashMode">The path separator to use. See the <see cref="SlashMode">SlashMode</see> enum for an explanation of the values. Defaults to <c>SlashMode.Forward</c>.</param>
/// <returns>The path, with the requested path separator type, in quotes.</returns>
public string InQuotes(SlashMode slashMode = SlashMode.Forward)
{
return "\"" + ToString(slashMode) + "\"";
}
/// <summary>
/// Convert this path to a string, using forward slashes as path separators.
/// </summary>
/// <returns>The string representation of this path.</returns>
public override string ToString()
{
return _path;
}
/// <summary>
/// Convert this path to a string, using the requested path separator type.
/// </summary>
/// <param name="slashMode">The path separator type to use. See <see cref="SlashMode">SlashMode</see> for possible values.</param>
/// <returns>The string representation of this path.</returns>
public string ToString(SlashMode slashMode)
{
if (slashMode == SlashMode.Forward || (slashMode == SlashMode.Native && !k_IsWindows))
return _path;
return _path.Replace("/", "\\");
}
/// <summary>
/// Checks if this NPath represents the same path as another object.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if this NPath represents the same path as the other object; false if it does not, if the other object is not an NPath, or is null.</returns>
public override bool Equals(object obj)
{
return Equals(obj as NPath);
}
/// <summary>
/// Checks if this NPath is equal to another NPath.
/// </summary>
/// <param name="p">The path to compare to.</param>
/// <returns>True if this NPath represents the same path as the other NPath; false otherwise.</returns>
/// <remarks>Note that the comparison requires that the paths are the same, not just that the targets are the same; "foo/bar" and "foo/baz/../bar" refer to the same target but will not be treated as equal by this comparison. However, this comparison will ignore case differences when the current operating system does not use case-sensitive filesystems.</remarks>
public bool Equals(NPath p)
{
return p != null && string.Equals(p._path, _path, PathStringComparison);
}
/// <summary>
/// Compare two NPaths for equality.
/// </summary>
/// <param name="a">The first NPath to compare.</param>
/// <param name="b">The second NPath to compare.</param>
/// <returns>True if the NPaths are both equal (or both null), false otherwise. See <see cref="Equals(NPath)">Equals.</see></returns>
public static bool operator==(NPath a, NPath b)
{
// If both are null, or both are same instance, return true.
if (ReferenceEquals(a, b))
return true;
// If one is null, but not both, return false.
if ((object)a == null || (object)b == null)
return false;
// Return true if the fields match:
return a.Equals(b);
}
/// <summary>
/// Get an appropriate hash value for this NPath.
/// </summary>
/// <returns>A hash value for this NPath.</returns>
public override int GetHashCode()
{
if (k_IsCaseSensitiveFileSystem)
return _path.GetHashCode();
uint hash = 27644437;
for (int i = 0, len = _path.Length; i < len; ++i)
{
uint c = _path[i];
if (c > 0x80) c = 0x80; // All non-ASCII chars may (potentially) compare Equal.
c |= 0x20; // ASCII case folding.
hash ^= (hash << 5) ^ c;
}
return unchecked((int)hash);
}
/// <summary>
/// Compare this NPath to another NPath, returning a value that can be used to sort the two objects in a stable order.
/// </summary>
/// <param name="obj">The object to compare to. Note that this object must be castable to NPath.</param>
/// <returns>A value that indicates the relative order of the two objects. The return value has these meanings:
/// <list type="table">
/// <listheader><term>Value</term><description>Meaning</description></listheader>
/// <item><term>Less than zero</term><description>This instance precedes <c>obj</c> in the sort order.</description></item>
/// <item><term>Zero</term><description>This instance occurs in the same position as <c>obj</c> in the sort order.</description></item>
/// <item><term>Greater than zero</term><description>This instance follows <c>obj</c> in the sort order.</description></item>
/// </list>
/// </returns>
public int CompareTo(object obj)
{
if (obj == null)
return -1;
return string.Compare(_path, ((NPath)obj)._path, PathStringComparison);
}
/// <summary>
/// Compare two NPaths for inequality.
/// </summary>
/// <param name="a">The first NPath to compare.</param>
/// <param name="b">The second NPath to compare.</param>
/// <returns>True if the NPaths are not equal, false otherwise.</returns>
public static bool operator!=(NPath a, NPath b)
{
return !(a == b);
}
/// <summary>
/// Tests whether this NPath has the provided extension.
/// </summary>
/// <param name="extension">The extension to test for.</param>
/// <returns>True if this NPath has has the provided extension. False otherwise.</returns>
/// <remarks>The extension "*" is special, and will return true for all paths if specified.</remarks>
public bool HasExtension(string extension)
{
if (extension == "*")
return true;
if (IsRoot)
return false;
if (extension.Length > _path.Length)
return false;
int extensionOffset = _path.Length - extension.Length;
if (extension.Length == 0 || extension[0] != '.')
{
// Supplied extension doesn't have a dot, so we must check
// that there is a dot or a slash before the extension in our path
if (extensionOffset < 1)
return false;
char extensionSeparator = _path[extensionOffset - 1];
if (extensionSeparator != '.' && extensionSeparator != '/')
return false;
}
return string.Compare(extension, 0, _path, extensionOffset, extension.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
/// <summary>
/// Tests whether this NPath has one of the provided extensions, or if no extensions are provided, whether it has any extension at all.
/// </summary>
/// <param name="extensions">The possible extensions to test for.</param>
/// <returns>True if this NPath has one of the provided extensions; or, if no extensions are provided, true if this NPath has an extension. False otherwise.</returns>
/// <remarks>The extension "*" is special, and will return true for all paths if specified.</remarks>
public bool HasExtension(params string[] extensions)
{
if (extensions.Length == 0)
return FileName.Contains(".");
foreach (var e in extensions)
{
if (HasExtension(e))
return true;
}
return false;
}
private static string WithDot(string extension)
{
return extension.StartsWith(".", StringComparison.Ordinal) ? extension : "." + extension;
}
/// <summary>
/// Whether this path is rooted or not (begins with a slash character or drive specifier).
/// </summary>
public bool IsRoot
{
get
{
if (_path == "/")
return true;
if (_path.Length == 3 && _path[1] == ':' && _path[2] == '/')
return true;
if (IsUNC && _path.Length == _path.IndexOf('/') + 1)
return true;
return false;
}
}
/// <summary>
/// Whether this path starts with an UNC path prefix "\\" or not.
/// </summary>
public bool IsUNC => IsUNCPath(_path);
#endregion inspection
#region directory enumeration
/// <summary>
/// Find all files within this path that match the given filter.
/// </summary>
/// <param name="filter">The filter to match against the names of files. Wildcards can be included.</param>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for files that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of files that were found.</returns>
public NPath[] Files(string filter, bool recurse = false) => FileSystem.Active.Directory_GetFiles(_path, filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
/// <summary>
/// Find all files within this path.
/// </summary>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for files that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of files that were found.</returns>
public NPath[] Files(bool recurse = false) => Files("*", recurse);
/// <summary>
/// Find all files within this path that have one of the provided extensions.
/// </summary>
/// <param name="extensions">The extensions to search for.</param>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for files that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of files that were found.</returns>
public NPath[] Files(string[] extensions, bool recurse = false)
{
if (!DirectoryExists() || extensions.Length == 0)
return new NPath[] {};
return FileSystem.Active.Directory_GetFiles(this, "*", recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Where(p => extensions.Contains(p.Extension)).ToArray();
}
/// <summary>
/// Find all files or directories within this path that match the given filter.
/// </summary>
/// <param name="filter">The filter to match against the names of files and directories. Wildcards can be included.</param>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for files and directories that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of files and directories that were found.</returns>
public NPath[] Contents(string filter, bool recurse = false)
{
return Files(filter, recurse).Concat(Directories(filter, recurse)).ToArray();
}
/// <summary>
/// Find all files and directories within this path.
/// </summary>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for files and directories that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of files and directories that were found.</returns>
public NPath[] Contents(bool recurse = false)
{
return Contents("*", recurse);
}
/// <summary>
/// Find all directories within this path that match the given filter.
/// </summary>
/// <param name="filter">The filter to match against the names of directories. Wildcards can be included.</param>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for directories that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of directories that were found.</returns>
public NPath[] Directories(string filter, bool recurse = false)
{
return FileSystem.Active.Directory_GetDirectories(this, filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
}
/// <summary>
/// Find all directories within this path.
/// </summary>
/// <param name="recurse">If true, search recursively inside subdirectories of this path; if false, search only for directories that are immediate children of this path. Defaults to false.</param>
/// <returns>An array of directories that were found.</returns>
public NPath[] Directories(bool recurse = false)
{
return Directories("*", recurse);
}
#endregion
#region filesystem writing operations
/// <summary>
/// Create an empty file at this path.
/// </summary>
/// <returns>This NPath, for chaining further operations.</returns>
/// <remarks>If a file already exists at this path, it will be overwritten.</remarks>
public NPath CreateFile()
{
ThrowIfRoot();
EnsureParentDirectoryExists();
FileSystem.Active.File_WriteAllBytes(this, new byte[0]);
return this;
}
/// <summary>
/// Append the given path fragment to this path, and create an empty file there.
/// </summary>
/// <param name="file">The path fragment to append.</param>
/// <returns>The path to the created file, for chaining further operations.</returns>
/// <remarks>If a file already exists at that path, it will be overwritten.</remarks>
public NPath CreateFile(NPath file)
{
if (!file.IsRelative)
throw new ArgumentException(
"You cannot call CreateFile() on an existing path with a non relative argument");
return Combine(file).CreateFile();
}
/// <summary>
/// Create this path as a directory if it does not already exist.
/// </summary>
/// <returns>This NPath, for chaining further operations.</returns>
/// <remark>This is identical to <see cref="EnsureDirectoryExists(NPath)"/>, except that EnsureDirectoryExists triggers "Stat" callbacks and this doesn't.</remark>
public NPath CreateDirectory()
{
if (IsRoot)
throw new NotSupportedException(
"CreateDirectory is not supported on a root level directory because it would be dangerous:" +
ToString());
FileSystem.Active.Directory_CreateDirectory(this);
return this;
}
/// <summary>
/// Append the given path fragment to this path, and create it as a directory if it does not already exist.
/// </summary>
/// <param name="directory">The path fragment to append.</param>
/// <returns>The path to the created directory, for chaining further operations.</returns>
public NPath CreateDirectory(NPath directory)
{
if (!directory.IsRelative)
throw new ArgumentException("Cannot call CreateDirectory with an absolute argument");
return Combine(directory).CreateDirectory();
}
/// <summary>
/// Create this path as a symbolic link to another file or directory.
/// </summary>
/// <param name="targetPath">The path that this path should be a symbolic link to. Can be relative or absolute.</param>
/// <param name="targetIsFile">Specifies whether this link is to a file or to a directory (required on Windows). Defaults to file.</param>
/// <returns>The path to the created symbolic link, for chaining further operations.</returns>
public NPath CreateSymbolicLink(NPath targetPath, bool targetIsFile = true)
{
ThrowIfRoot();
if (Exists())
throw new InvalidOperationException(
"Cannot create symbolic link at {this} because it already exists as a file or directory.");
FileSystem.Active.CreateSymbolicLink(this, targetPath, targetIsFile);
return this;
}
/// <summary>
/// Checks whether the entity referred to by this path is a symbolic link.
/// </summary>
public bool IsSymbolicLink
{
get
{
return FileSystem.Active.IsSymbolicLink(this);
}
}
/// <summary>
/// Copy this NPath to the given destination.
/// </summary>
/// <param name="dest">The path to copy to.</param>
/// <returns>The path to the copied result, for chaining further operations.</returns>
public NPath Copy(NPath dest)
{
return Copy(dest, p => true);
}
/// <summary>
/// Copy this NPath to the given destination, applying a filter function to decide which files are copied.
/// </summary>
/// <param name="dest">The path to copy to.</param>
/// <param name="fileFilter">The filter function. Each candidate file is passed to this function; if the function returns true, the file will be copied, otherwise it will not.</param>
/// <returns></returns>
public NPath Copy(NPath dest, Func<NPath, bool> fileFilter)
{
if (dest.DirectoryExists())
return CopyWithDeterminedDestination(dest.Combine(FileName), fileFilter);
return CopyWithDeterminedDestination(dest, fileFilter);