Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PathCchIsRoot Updated isRoot extension. #892

Merged
merged 1 commit into from
Dec 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions Sources/SwiftFormat/Utilities/URL+isRoot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,44 @@

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 == "/" {
// Canonicalize `/C:/` to `C:/`.
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)
}
}
Loading