Skip to content

Commit f343291

Browse files
committed
TSCBasic: avoid using C library functions for environment
Prefer to use the Win32 APIs for environment management. Note that this is going to break any user of libc on Windows. Setting environment variables through this function will not be reflected in the C library only the Win32 APIs. Furthermore, we use the unicode variants always as the unicode and ANSI environment may diverge as not all unicode (UTF-16) is translatable to ANSI, which is documented at [1]. [1] https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getenv-wgetenv?view=msvc-170&viewFallbackFrom=vs-2019.
1 parent d9d2b41 commit f343291

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

Sources/TSCBasic/Process/ProcessEnv.swift

+10-6
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,12 @@ public enum ProcessEnv {
2626
/// Set the given key and value in the process's environment.
2727
public static func setVar(_ key: String, value: String) throws {
2828
#if os(Windows)
29-
guard TSCLibc._putenv("\(key)=\(value)") == 0 else {
30-
throw SystemError.setenv(Int32(GetLastError()), key)
29+
try key.withCString(encodedAs: UTF16.self) { pwszKey in
30+
try value.withCString(encodedAs: UTF16.self) { pwszValue in
31+
guard SetEnvironmentVariableW(pwszKey, pwszValue) else {
32+
throw SystemError.setenv(Int32(GetLastError()), key)
33+
}
34+
}
3135
}
3236
#else
3337
guard TSCLibc.setenv(key, value, 1) == 0 else {
@@ -40,7 +44,9 @@ public enum ProcessEnv {
4044
/// Unset the give key in the process's environment.
4145
public static func unsetVar(_ key: String) throws {
4246
#if os(Windows)
43-
guard TSCLibc._putenv("\(key)=") == 0 else {
47+
guard key.withCString(encodedAs: UTF16.self, {
48+
SetEnvironmentVariableW($0, nil)
49+
}) else {
4450
throw SystemError.unsetenv(Int32(GetLastError()), key)
4551
}
4652
#else
@@ -70,9 +76,7 @@ public enum ProcessEnv {
7076
public static func chdir(_ path: AbsolutePath) throws {
7177
let path = path.pathString
7278
#if os(Windows)
73-
guard path.withCString(encodedAs: UTF16.self, {
74-
SetCurrentDirectoryW($0)
75-
}) else {
79+
guard path.withCString(encodedAs: UTF16.self, SetCurrentDirectoryW) else {
7680
throw SystemError.chdir(Int32(GetLastError()), path)
7781
}
7882
#else

0 commit comments

Comments
 (0)