-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAbsoluteDirectoryPath.cs
More file actions
280 lines (246 loc) · 11.3 KB
/
AbsoluteDirectoryPath.cs
File metadata and controls
280 lines (246 loc) · 11.3 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
// Copyright (c) ktsu.dev
// All rights reserved.
// Licensed under the MIT license.
namespace ktsu.Semantics.Paths;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Represents an absolute directory path
/// </summary>
[IsPath, IsAbsolutePath, IsAbsoluteDirectoryPath]
public sealed record AbsoluteDirectoryPath : SemanticDirectoryPath<AbsoluteDirectoryPath>, IAbsoluteDirectoryPath
{
// Cache for expensive parent directory computation
private AbsoluteDirectoryPath? _cachedParent;
/// <summary>
/// Gets the parent directory of this absolute directory path.
/// </summary>
/// <value>An <see cref="AbsoluteDirectoryPath"/> representing the parent directory, or an empty path if this is a root directory.</value>
public AbsoluteDirectoryPath Parent
{
get
{
return _cachedParent ??= Create<AbsoluteDirectoryPath>(
InternedPathStrings.InternIfCommon(Path.GetDirectoryName(WeakString) ?? InternedPathStrings.Empty));
}
}
// Cache for directory name
private FileName? _cachedName;
/// <summary>
/// Gets the name of this directory (the last component of the path).
/// </summary>
/// <value>A <see cref="FileName"/> representing just the directory name.</value>
public FileName Name => _cachedName ??= FileName.Create<FileName>(Path.GetFileName(WeakString) ?? "");
// Cache for depth calculation
private int? _cachedDepth;
/// <summary>
/// Gets the depth of this directory path (number of directory separators).
/// For example, "a/b/c" has depth 2, "a" has depth 0.
/// </summary>
/// <value>The number of directory separators in the path.</value>
public int Depth => _cachedDepth ??= CalculateDepth(WeakString);
/// <summary>
/// Calculates directory depth using span semantics for optimal performance.
/// </summary>
/// <param name="path">The path to analyze.</param>
/// <returns>The directory depth.</returns>
private static int CalculateDepth(string path)
{
if (string.IsNullOrEmpty(path))
{
return 0;
}
ReadOnlySpan<char> span = path.AsSpan();
int depth = 0;
for (int i = 0; i < span.Length; i++)
{
if (span[i] == Path.DirectorySeparatorChar || span[i] == Path.AltDirectorySeparatorChar)
{
depth++;
}
}
return depth;
}
// Cache for root check
private bool? _cachedIsRoot;
/// <summary>
/// Determines whether this directory is a root directory.
/// </summary>
/// <value><c>true</c> if this is a root directory; otherwise, <c>false</c>.</value>
public bool IsRoot => _cachedIsRoot ??= Path.GetPathRoot(WeakString) == WeakString;
/// <summary>
/// Creates an absolute file path for files in this directory.
/// </summary>
/// <param name="filePath">The file path to wrap.</param>
/// <returns>An <see cref="AbsoluteFilePath"/> object.</returns>
protected override IFilePath CreateFilePath(string filePath) =>
AbsoluteFilePath.Create<AbsoluteFilePath>(filePath);
/// <summary>
/// Creates an absolute directory path for subdirectories in this directory.
/// </summary>
/// <param name="directoryPath">The directory path to wrap.</param>
/// <returns>An <see cref="AbsoluteDirectoryPath"/> object.</returns>
protected override IDirectoryPath CreateDirectoryPath(string directoryPath) =>
Create<AbsoluteDirectoryPath>(directoryPath);
/// <summary>
/// Combines an absolute directory path with a relative directory path using the '/' operator.
/// </summary>
/// <param name="left">The base absolute directory path.</param>
/// <param name="right">The relative directory path to append.</param>
/// <returns>A new <see cref="AbsoluteDirectoryPath"/> representing the combined path.</returns>
[SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "Path combination is the semantic meaning, not mathematical division")]
public static AbsoluteDirectoryPath operator /(AbsoluteDirectoryPath left, RelativeDirectoryPath right)
{
Guard.NotNull(left);
Guard.NotNull(right);
string combinedPath = PooledStringBuilder.CombinePaths(left.WeakString, right.WeakString);
return Create<AbsoluteDirectoryPath>(combinedPath);
}
/// <summary>
/// Combines an absolute directory path with a relative file path using the '/' operator.
/// </summary>
/// <param name="left">The base absolute directory path.</param>
/// <param name="right">The relative file path to append.</param>
/// <returns>A new <see cref="AbsoluteFilePath"/> representing the combined path.</returns>
[SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "Path combination is the semantic meaning, not mathematical division")]
public static AbsoluteFilePath operator /(AbsoluteDirectoryPath left, RelativeFilePath right)
{
Guard.NotNull(left);
Guard.NotNull(right);
string combinedPath = PooledStringBuilder.CombinePaths(left.WeakString, right.WeakString);
return AbsoluteFilePath.Create<AbsoluteFilePath>(combinedPath);
}
/// <summary>
/// Combines an absolute directory path with a directory name using the '/' operator.
/// </summary>
/// <param name="left">The base absolute directory path.</param>
/// <param name="right">The directory name to append.</param>
/// <returns>A new <see cref="AbsoluteDirectoryPath"/> representing the combined path.</returns>
[SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "Path combination is the semantic meaning, not mathematical division")]
public static AbsoluteDirectoryPath operator /(AbsoluteDirectoryPath left, DirectoryName right)
{
Guard.NotNull(left);
Guard.NotNull(right);
string combinedPath = PooledStringBuilder.CombinePaths(left.WeakString, right.WeakString);
return Create<AbsoluteDirectoryPath>(combinedPath);
}
/// <summary>
/// Combines an absolute directory path with a file name using the '/' operator.
/// </summary>
/// <param name="left">The base absolute directory path.</param>
/// <param name="right">The file name to append.</param>
/// <returns>A new <see cref="AbsoluteFilePath"/> representing the combined path.</returns>
[SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "Path combination is the semantic meaning, not mathematical division")]
public static AbsoluteFilePath operator /(AbsoluteDirectoryPath left, FileName right)
{
Guard.NotNull(left);
Guard.NotNull(right);
string combinedPath = PooledStringBuilder.CombinePaths(left.WeakString, right.WeakString);
return AbsoluteFilePath.Create<AbsoluteFilePath>(combinedPath);
}
/// <summary>
/// Determines whether this directory is a child of the specified parent path using efficient span comparison.
/// </summary>
/// <param name="parentPath">The potential parent path to check against.</param>
/// <returns><see langword="true"/> if this path is a child of the parent path; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// This method uses span-based comparison for better performance than string concatenation.
/// It normalizes both paths before comparison to handle different separator styles.
/// </remarks>
public bool IsChildOf(AbsoluteDirectoryPath parentPath)
{
Guard.NotNull(parentPath);
// Get normalized paths using span semantics for comparison
ReadOnlySpan<char> thisPathSpan = Path.GetFullPath(WeakString).AsSpan();
ReadOnlySpan<char> parentPathSpan = Path.GetFullPath(parentPath.WeakString).AsSpan();
// A path cannot be a child of itself
if (thisPathSpan.SequenceEqual(parentPathSpan))
{
return false;
}
// Check if this path starts with the parent path followed by a separator
if (!thisPathSpan.StartsWith(parentPathSpan, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Ensure there's a separator after the parent path (not just a prefix match)
int nextIndex = parentPathSpan.Length;
return nextIndex < thisPathSpan.Length &&
(thisPathSpan[nextIndex] == Path.DirectorySeparatorChar ||
thisPathSpan[nextIndex] == Path.AltDirectorySeparatorChar);
}
/// <summary>
/// Determines whether this directory is a parent of the specified child path using efficient span comparison.
/// </summary>
/// <param name="childPath">The potential child path to check against.</param>
/// <returns><see langword="true"/> if this path is a parent of the child path; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// This method uses span-based comparison for better performance than string concatenation.
/// It normalizes both paths before comparison to handle different separator styles.
/// </remarks>
public bool IsParentOf(AbsoluteDirectoryPath childPath)
{
Guard.NotNull(childPath);
return childPath.IsChildOf(this);
}
/// <summary>
/// Gets all parent directories from this directory up to the root.
/// </summary>
/// <returns>An enumerable of <see cref="AbsoluteDirectoryPath"/> representing all parent directories.</returns>
public IEnumerable<AbsoluteDirectoryPath> GetAncestors()
{
AbsoluteDirectoryPath current = Parent;
while (!string.IsNullOrEmpty(current.WeakString) && current != this)
{
yield return current;
AbsoluteDirectoryPath next = current.Parent;
if (next == current)
{
break; // Prevent infinite loop at root
}
current = next;
}
}
/// <summary>
/// Creates a relative directory path from this directory to another absolute directory.
/// </summary>
/// <param name="targetDirectory">The target directory.</param>
/// <returns>A <see cref="RelativeDirectoryPath"/> from this directory to the target.</returns>
public RelativeDirectoryPath GetRelativePathTo(AbsoluteDirectoryPath targetDirectory)
{
Guard.NotNull(targetDirectory);
// Use Path.GetRelativePath to compute the relative path
#if NETSTANDARD2_0
string relativePath = PathPolyfill.GetRelativePath(WeakString, targetDirectory.WeakString);
#else
string relativePath = Path.GetRelativePath(WeakString, targetDirectory.WeakString);
#endif
return RelativeDirectoryPath.Create<RelativeDirectoryPath>(relativePath);
}
/// <summary>
/// Converts this directory path to an absolute directory path representation.
/// Since this is already an absolute path, returns itself.
/// </summary>
/// <returns>An <see cref="AbsoluteDirectoryPath"/> representing the absolute path to this directory.</returns>
public AbsoluteDirectoryPath AsAbsolute() => this;
/// <summary>
/// Explicitly implements IAbsolutePath.AsAbsolute() to return the base AbsolutePath type.
/// </summary>
/// <returns>An <see cref="AbsolutePath"/> representing this absolute path.</returns>
AbsolutePath IAbsolutePath.AsAbsolute() => AbsolutePath.Create<AbsolutePath>(WeakString);
/// <summary>
/// Converts this absolute directory path to a relative directory path using the specified base directory.
/// </summary>
/// <param name="baseDirectory">The base directory to make this path relative to.</param>
/// <returns>A <see cref="RelativeDirectoryPath"/> representing the relative path from the base directory.</returns>
/// <exception cref="ArgumentNullException"><paramref name="baseDirectory"/> is <see langword="null"/>.</exception>
public RelativeDirectoryPath AsRelative(AbsoluteDirectoryPath baseDirectory)
{
Guard.NotNull(baseDirectory);
#if NETSTANDARD2_0
string relativePath = PathPolyfill.GetRelativePath(baseDirectory.WeakString, WeakString);
#else
string relativePath = Path.GetRelativePath(baseDirectory.WeakString, WeakString);
#endif
return RelativeDirectoryPath.Create<RelativeDirectoryPath>(relativePath);
}
}