fix(FilePath.ComponentView): prevent trailing separator when replacing suffix

This commit is contained in:
Ugur Toprakdeviren authored and Guillaume Lessard committed 2026-11-04 15:21:12 -08:00
1 parent 402eb4b586
commit 77882a1fc8
2 files changed
+36 -1

No files matched your search

@@ -143,7 +143,9 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
str.append(platformSeparator)
}
str.appendComponents(components: newElements)
if !atEnd {
// If we're replacing through the end, we must not leave a trailing
// separator.
if subrange.upperBound != endIndex {
str.append(platformSeparator)
}
_path._storage.replaceSubrange(range, with: str)
@@ -210,6 +210,39 @@ final class FilePathComponentsTest: XCTestCase {
expect("/usr/newMiddle/newMiddle2/newMiddle3/newMiddle4/bin")
}
// Replacing a suffix with non-empty elements must not leave a trailing
// separator
restoreAfter {
let last = path.components.indices.last!
path.components.replaceSubrange(last..., with: ["sbin"])
expect("/usr/local/sbin")
XCTAssertEqual(path.lastComponent, "sbin")
XCTAssertEqual(path.components.last, "sbin")
let c = path.components
XCTAssertNotEqual(c.index(before: c.endIndex), c.endIndex)
path.components.replaceSubrange(
path.components.index(after: path.components.startIndex)...,
with: ["a", "b", "c"])
expect("/usr/a/b/c")
path.components.append("d")
expect("/usr/a/b/c/d")
XCTAssertEqual(path.components.count, 5)
path.components.replaceSubrange(
path.components.startIndex..., with: ["x", "y"])
expect("/x/y")
}
restoreAfter {
path = "a/b"
path.components.replaceSubrange(
path.components.indices.last!..., with: ["x"])
expect("a/x")
XCTAssertEqual(path.lastComponent, "x")
}
restoreAfter {
path.components.removeLast(3)
expect("/")