diff --git a/Sources/FoundationEssentials/URL/URL_Swift.swift b/Sources/FoundationEssentials/URL/URL_Swift.swift index e5643bc71..e694e7c0a 100644 --- a/Sources/FoundationEssentials/URL/URL_Swift.swift +++ b/Sources/FoundationEssentials/URL/URL_Swift.swift @@ -682,6 +682,9 @@ internal final class _SwiftURL: Sendable, Hashable, Equatable { } internal func appending(path: S, directoryHint: URL.DirectoryHint, encodingSlashes: Bool, compatibility: Bool = false) -> URL? { + guard !path.isEmpty || !_parseInfo.path.isEmpty || _parseInfo.netLocationRange?.isEmpty == false else { + return nil + } #if os(Windows) var pathToAppend = path.replacing(._backslash, with: ._slash) #else diff --git a/Tests/FoundationEssentialsTests/URLTests.swift b/Tests/FoundationEssentialsTests/URLTests.swift index 20e2d9fb5..c8eb77fb7 100644 --- a/Tests/FoundationEssentialsTests/URLTests.swift +++ b/Tests/FoundationEssentialsTests/URLTests.swift @@ -966,8 +966,21 @@ final class URLTests : XCTestCase { XCTAssertEqual(example.path(), "/foo") XCTAssertEqual(example.absoluteString, "https://example.com/foo") + // Maintain old behavior, where appending an empty path + // to an empty host does not add a slash, but appending + // an empty path to a non-empty host does + example = try XCTUnwrap(URL(string: "https://example.com")) + example.append(path: "") + XCTAssertEqual(example.host(), "example.com") + XCTAssertEqual(example.path(), "/") + XCTAssertEqual(example.absoluteString, "https://example.com/") + var emptyHost = try XCTUnwrap(URL(string: "scheme://")) - XCTAssertTrue(emptyHost.host()?.isEmpty ?? true) + XCTAssertNil(emptyHost.host()) + XCTAssertTrue(emptyHost.path().isEmpty) + + emptyHost.append(path: "") + XCTAssertNil(emptyHost.host()) XCTAssertTrue(emptyHost.path().isEmpty) emptyHost.append(path: "foo")