URL.path vs path(percentEncoded:) for File URLs

There's a deprecation warning in Xcode for URL.path that reads:

WARNING: 'path' will be deprecated in a future version of macOS: Use path(percentEncoded:) instead

The problem is something like this:

Bundle.main.url(forAuxiliaryExecutable: "tool")!.path

... which returns the expected file path (ex: "/Applications/MyApp.app/Contents/tool")

would be quickly rewritten as suggested to:

Bundle.main.url(forAuxiliaryExecutable: "tool")!.path(percentEncoded: false)

... which simply returns "tool", because the URL returned is relative to a base URL.

Widespread adoption of path(percentEncoded: false) in place of path on file URLs will lead to bugs if this undocumented difference is not known.

--

This can be demonstrated as such:

let a = URL(fileURLWithPath: "/System/Library")
let b = URL(string: "Library", relativeTo: URL(fileURLWithPath: "/System"))!

print(a) // file:///System/Library/
print(b) // Library -- file:///System/

// WARNING: 'path' will be deprecated in a future version of macOS: Use path(percentEncoded:) instead
print(a.path) //  /System/Library
print(b.path) //  /System/Library

print(a.path(percentEncoded: false)) //  /System/Library 
print(b.path(percentEncoded: false)) //  Library

print(a.standardizedFileURL.path(percentEncoded: false)) //  /System/Library 
print(b.standardizedFileURL.path(percentEncoded: false)) //  /System/Library

I've always found it not-completely-obvious to newcomers how to get a standard file path string from a file URL and this only makes it more confusing.

For the sake of sanity where having to go from a URL to a file path string is still very common, I'd expect something along the lines of:

url.standardizedFilePath -> String

... which makes it very clear and obvious to anyone looking at URL and asking "how do I get a file path string from this?"

Or, since the FilePath type now exists, I'd even accept:

url.standardizedFilePath -> FilePath

I can't seem to find any discussion on

  • A) This .path vs .path(percentEncoded: false) difference so I'm not even sure if it's intentional or not
  • B) Making it more obvious how to get a correct file path from a URL. (Which surely has come up in the past!)

Am I missing something?

7 Likes

Reported as a bug: URL.path(percentEncoded: false) is NOT Equivalent to URL.path property for File URLs · Issue #77213 · swiftlang/swift · GitHub