From 77882a1fc872c49a18fd034d019f3e7a336b0392 Mon Sep 17 00:00:00 2001 From: Ugur Toprakdeviren Date: Wed, 4 Nov 2026 23:04:07 +0300 Subject: [PATCH] fix(FilePath.ComponentView): prevent trailing separator when replacing suffix --- .../FilePath/FilePathComponentView.swift | 4 ++- .../FilePathComponentsTest.swift | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Sources/System/FilePath/FilePathComponentView.swift b/Sources/System/FilePath/FilePathComponentView.swift index be17630..9433dfd 100644 --- a/Sources/System/FilePath/FilePathComponentView.swift +++ b/Sources/System/FilePath/FilePathComponentView.swift @@ -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) diff --git a/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift b/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift index 675b533..50ec7d6 100644 --- a/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift @@ -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("/")