Skip to content

Commit 4d0d2af

Browse files
committed
Fix deleteLastPathComponent() for absolute paths with trailing /
Paths like /home/ would return "" instead of /
1 parent ef8c1d5 commit 4d0d2af

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

Sources/FoundationEssentials/String/String+Path.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ extension String {
6363
// This is a trailing slash. Ignore it.
6464
let beforeLastSlash = self[startIndex..<lastSlash].lastIndex { $0 == "/" }
6565
if let beforeLastSlash {
66-
return String(self[startIndex..<beforeLastSlash])
66+
if beforeLastSlash == startIndex {
67+
// Only the first slash remains, return a bare slash.
68+
return "/"
69+
} else {
70+
return String(self[startIndex..<beforeLastSlash])
71+
}
6772
} else {
6873
// No other slash. Return empty string.
6974
return ""

Tests/FoundationEssentialsTests/DataIOTests.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ class DataIOTests : XCTestCase {
255255
XCTAssertEqual("/".deletingLastPathComponent(), "/")
256256
XCTAssertEqual("q".deletingLastPathComponent(), "")
257257
XCTAssertEqual("/aaa".deletingLastPathComponent(), "/")
258+
XCTAssertEqual("/aaa/".deletingLastPathComponent(), "/")
258259
XCTAssertEqual("/a/b/c/".deletingLastPathComponent(), "/a/b")
259260
XCTAssertEqual("hello".deletingLastPathComponent(), "")
260261
XCTAssertEqual("hello/".deletingLastPathComponent(), "")

Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -458,11 +458,7 @@ final class FileManagerTests : XCTestCase {
458458
XCTAssertEqual(try $0.subpathsOfDirectory(atPath: ".").sorted(), ["dir", "dir/bar", "dir/foo", "dir2", "dir2/bar", "dir2/foo", "other_file"])
459459
XCTAssertEqual($0.contents(atPath: "dir/foo"), data)
460460
XCTAssertEqual($0.contents(atPath: "dir2/foo"), data)
461-
#if os(Windows)
462461
XCTAssertEqual($0.delegateCaptures.shouldCopy, [.init("dir", "dir2"), .init("dir/bar", "dir2/bar"), .init("dir/foo", "dir2/foo")])
463-
#else
464-
XCTAssertEqual($0.delegateCaptures.shouldCopy, [.init("dir", "dir2"), .init("dir/foo", "dir2/foo"), .init("dir/bar", "dir2/bar")])
465-
#endif
466462

467463
XCTAssertThrowsError(try $0.copyItem(atPath: "does_not_exist", toPath: "dir3")) {
468464
XCTAssertEqual(($0 as? CocoaError)?.code, .fileReadNoSuchFile)

0 commit comments

Comments
 (0)