diff --git a/Sources/SwiftFormat/Utilities/URL+isRoot.swift b/Sources/SwiftFormat/Utilities/URL+isRoot.swift index 1ad521c7f..6a8522889 100644 --- a/Sources/SwiftFormat/Utilities/URL+isRoot.swift +++ b/Sources/SwiftFormat/Utilities/URL+isRoot.swift @@ -12,10 +12,32 @@ import Foundation +#if os(Windows) +import WinSDK +#endif + extension URL { + /// Returns a `Bool` to indicate if the given `URL` leads to the root of a filesystem. + /// A non-filesystem type `URL` will always return false. @_spi(Testing) public var isRoot: Bool { + guard isFileURL else { return false } + + #if compiler(>=6.1) + #if os(Windows) + let filePath = self.withUnsafeFileSystemRepresentation { pointer in + guard let pointer else { + return "" + } + return String(cString: pointer) + } + return filePath.withCString(encodedAs: UTF16.self, PathCchIsRoot) + #else // os(Windows) + return self.path == "/" + #endif // os(Windows) + #else // compiler(>=6.1) + #if os(Windows) - // 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. + // This is needed as the fixes from #844 aren't in the Swift 6.0 toolchain. // https://github.com/swiftlang/swift-format/issues/844 var pathComponents = self.pathComponents if pathComponents.first == "/" { @@ -23,10 +45,11 @@ extension URL { pathComponents = Array(pathComponents.dropFirst()) } return pathComponents.count <= 1 - #else + #else // os(Windows) // On Linux, we may end up with an string for the path due to https://github.com/swiftlang/swift-foundation/issues/980 - // TODO: Remove the check for "" once https://github.com/swiftlang/swift-foundation/issues/980 is fixed. + // This is needed as the fixes from #980 aren't in the Swift 6.0 toolchain. return self.path == "/" || self.path == "" - #endif + #endif // os(Windows) + #endif // compiler(>=6.1) } }