Skip to content

Commit 9d9a537

Browse files
authored
Fix deleteLastPathComponent() for absolute paths with trailing / (#897)
Paths like /home/ would return "" instead of / Co-authored-by: Ryan Mansfield <ryan_mansfield@apple.com>
1 parent ef8c1d5 commit 9d9a537

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
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(), "")

0 commit comments

Comments
 (0)