Skip to content

Commit bbf0133

Browse files
authored
Support: fix Environment.variable(named:) on Windows (#114)
The return value being `0` may or may not indicate. We need to additionally check `GetLastError` to see if `ERROR_ENVVAR_NOT_FOUND` is set to indicate the missing variable. Otherwise, the variable is just an empty string. This repairs the 2 failing tests on Windows. Thanks to @grynspan for the fix!
1 parent 668a20e commit bbf0133

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

Sources/Testing/Support/Environment.swift

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,19 @@ enum Environment {
4141
name.withCString(encodedAs: UTF16.self) { name in
4242
func getVariable(maxCount: Int) -> String? {
4343
withUnsafeTemporaryAllocation(of: wchar_t.self, capacity: maxCount) { buffer in
44+
SetLastError(DWORD(ERROR_SUCCESS))
4445
let count = GetEnvironmentVariableW(name, buffer.baseAddress!, DWORD(buffer.count))
45-
if count <= 0 {
46-
// Failed to get the environment variable. Presumably it is not set.
47-
return nil
46+
if count == 0 {
47+
return switch GetLastError() {
48+
case DWORD(ERROR_SUCCESS):
49+
// Empty String
50+
""
51+
case DWORD(ERROR_ENVVAR_NOT_FOUND):
52+
// The environment variable wasn't set.
53+
nil
54+
case let errorCode:
55+
fatalError("unexpected error code: \(errorCode) when getting environment variable '\(name)'")
56+
}
4857
} else if count > buffer.count {
4958
// Try again with the larger count.
5059
return getVariable(maxCount: Int(count))

0 commit comments

Comments
 (0)