Skip to content

Commit d0447c0

Browse files
Merge pull request #422 from ktsu-dev/fix/388-empty-relative-combine
Keep a path relative when its left operand is empty [patch]
2 parents 63f9920 + 4eee5fb commit d0447c0

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

‎Semantics.Paths/Utilities/PooledStringBuilder.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,12 @@ public static string CombinePaths(params string[] components)
6767
sb.Append(components[0]);
6868
for (int i = 1; i < components.Length; i++)
6969
{
70-
70+
// An empty leading component contributes nothing, so a separator after it would root the
71+
// result: "" combined with "x.txt" must be "x.txt", not "/x.txt".
7172
#if NETSTANDARD2_0
72-
if (!SpanPathUtilities.EndsWithDirectorySeparator(sb.ToString()))
73+
if (sb.Length > 0 && !SpanPathUtilities.EndsWithDirectorySeparator(sb.ToString()))
7374
#else
74-
if (!SpanPathUtilities.EndsWithDirectorySeparator(sb.ToString().AsSpan()))
75+
if (sb.Length > 0 && !SpanPathUtilities.EndsWithDirectorySeparator(sb.ToString().AsSpan()))
7576
#endif
7677
{
7778
sb.Append(Path.DirectorySeparatorChar);

‎Semantics.Test/Paths/PathOperatorTests.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,4 +216,23 @@ public void DirectoryNameOperator_WithSpecialCharacters_HandlesCorrectly()
216216
Assert.IsTrue(result.IsValid());
217217
Assert.Contains("my-app_v2 (beta)", result.WeakString);
218218
}
219+
220+
[TestMethod]
221+
public void RelativeDirectoryOperators_EmptyLeftOperand_StayRelative()
222+
{
223+
// Parent of a single-segment path is the empty path, the usual source of an empty left operand.
224+
RelativeDirectoryPath empty = RelativeDirectoryPath.Create<RelativeDirectoryPath>("a").Parent;
225+
Assert.AreEqual(string.Empty, empty.WeakString);
226+
227+
RelativeFilePath file = empty / FileName.Create<FileName>("x.txt");
228+
Assert.AreEqual("x.txt", file.WeakString);
229+
230+
RelativeDirectoryPath directory = empty / RelativeDirectoryPath.Create<RelativeDirectoryPath>("b");
231+
Assert.AreEqual("b", directory.WeakString);
232+
233+
string nested = TestPaths.Relative("c", "d.txt");
234+
RelativeFilePath nestedFile = empty / RelativeFilePath.Create<RelativeFilePath>(nested);
235+
Assert.AreEqual(nested, nestedFile.WeakString);
236+
Assert.IsFalse(Path.IsPathRooted(nestedFile.WeakString));
237+
}
219238
}

0 commit comments

Comments
 (0)