|
12 | 12 |
|
13 | 13 | import Foundation |
14 | 14 |
|
| 15 | +#if os(Windows) |
| 16 | +import WinSDK |
| 17 | +#endif |
| 18 | + |
15 | 19 | extension URL { |
| 20 | + /// Returns a `Bool` to indicate if the given `URL` leads to the root of a filesystem. |
| 21 | + /// A non-filesystem type `URL` will always return false. |
16 | 22 | @_spi(Testing) public var isRoot: Bool { |
| 23 | + guard isFileURL else { return false } |
| 24 | + |
| 25 | + #if compiler(>=6.1) |
| 26 | + #if os(Windows) |
| 27 | + let filePath = self.withUnsafeFileSystemRepresentation { pointer in |
| 28 | + guard let pointer else { |
| 29 | + return "" |
| 30 | + } |
| 31 | + return String(cString: pointer) |
| 32 | + } |
| 33 | + return filePath.withCString(encodedAs: UTF16.self, PathCchIsRoot) |
| 34 | + #else // os(Windows) |
| 35 | + return self.path == "/" |
| 36 | + #endif // os(Windows) |
| 37 | + #else // compiler(>=6.1) |
| 38 | + |
17 | 39 | #if os(Windows) |
18 | | - // FIXME: We should call into Windows' native check to check if this path is a root once https://github.com/swiftlang/swift-foundation/issues/976 is fixed. |
| 40 | + // This is needed as the fixes from #844 aren't in the Swift 6.0 toolchain. |
19 | 41 | // https://github.com/swiftlang/swift-format/issues/844 |
20 | 42 | var pathComponents = self.pathComponents |
21 | 43 | if pathComponents.first == "/" { |
22 | 44 | // Canonicalize `/C:/` to `C:/`. |
23 | 45 | pathComponents = Array(pathComponents.dropFirst()) |
24 | 46 | } |
25 | 47 | return pathComponents.count <= 1 |
26 | | - #else |
| 48 | + #else // os(Windows) |
27 | 49 | // On Linux, we may end up with an string for the path due to https://github.com/swiftlang/swift-foundation/issues/980 |
28 | | - // TODO: Remove the check for "" once https://github.com/swiftlang/swift-foundation/issues/980 is fixed. |
| 50 | + // This is needed as the fixes from #980 aren't in the Swift 6.0 toolchain. |
29 | 51 | return self.path == "/" || self.path == "" |
30 | | - #endif |
| 52 | + #endif // os(Windows) |
| 53 | + #endif // compiler(>=6.1) |
31 | 54 | } |
32 | 55 | } |
0 commit comments