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

PathKit: port to Windows #86

Closed
wants to merge 1 commit into from
Closed
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: 31 additions & 0 deletions Sources/PathKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import Glibc

let system_glob = Glibc.glob
#elseif os(Windows)
import WinSDK
#else
import Darwin

Expand Down Expand Up @@ -587,6 +589,26 @@ extension Path {

extension Path {
public static func glob(_ pattern: String) -> [Path] {
#if os(Windows)
var fdData: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
let hSearch: HANDLE = pattern.withCString(encodedAs: UTF16.self) {
FindFirstFileW($0, &fdData)
}
if (hSearch == INVALID_HANDLE_VALUE) {
return []
}
defer { FindClose(hSearch) }
Copy link
Collaborator

@djbe djbe Aug 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this defer be above that first if?

Edit: or is it because you can't close an invalid handle 🤔

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The edit is correct - it would close an invalid handle.

var paths: [Path] = []
repeat {
let path: String = withUnsafePointer(to: fdData.cFileName) {
$0.withMemoryRebound(to: UInt16.self, capacity: Int(MAX_PATH)) {
String(decodingCString: $0, as: UTF16.self)
}
}
paths.append(Path(path))
} while (FindNextFileW(hSearch, &fdData))
return paths
#else
var gt = glob_t()
guard let cPattern = strdup(pattern) else {
fatalError("strdup returned null: Likely out of memory")
Expand Down Expand Up @@ -614,13 +636,21 @@ extension Path {

// GLOB_NOMATCH
return []
#endif
}

public func glob(_ pattern: String) -> [Path] {
return Path.glob((self + pattern).description)
}

public func match(_ pattern: String) -> Bool {
#if os(Windows)
return path.withCString(encodedAs: UTF16.self) { lpwszPath in
return pattern.withCString(encodedAs: UTF16.self) { lpwszPattern in
PathMatchSpecExW(lpwszPath, lpwszPattern, DWORD(PMSF_NORMAL)) == S_OK
}
}
#else
guard let cPattern = strdup(pattern),
let cPath = strdup(path) else {
fatalError("strdup returned null: Likely out of memory")
Expand All @@ -630,6 +660,7 @@ extension Path {
free(cPath)
}
return fnmatch(cPattern, cPath, 0) == 0
#endif
}
}

Expand Down