Skip to content

Commit

Permalink
PathCchIsRoot PathCchIsRoot Updated isRoot extension.
Browse files Browse the repository at this point in the history
Now that swiftlang/swift-foundation#976 and swiftlang/swift-foundation#980 are fixed we can clean this code up a bit by removing the empty path check on Linux and by using the native `PathCchIsRoot` on Windows.

Existing code is retained for toolchains <6.1
  • Loading branch information
macshome committed Dec 9, 2024
1 parent 3b27ab5 commit 39bd050
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions Sources/SwiftFormat/Utilities/URL+isRoot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,43 @@

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 os(macOS)
return self.path == NSOpenStepRootDirectory()
#endif

#if 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.
return self.path.withCString(encodedAs: UTF16.self, PathCchIsRoot)
#elseif os(Linux)
return self.path == "/"
#endif
#else

#if os(Windows)
// 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
#elseif os(Linux)
// 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
}
}

0 comments on commit 39bd050

Please sign in to comment.