Skip to content

Commit

Permalink
os: use _wputenv instead of _putenv to stay in sync with _wgetenv (fi…
Browse files Browse the repository at this point in the history
…x changing env variables with non ASCII content on windows) (vlang#22920)
  • Loading branch information
Ekopalypse authored Nov 20, 2024
1 parent b995e64 commit ca67273
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
1 change: 1 addition & 0 deletions vlib/builtin/cfns.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ fn C._wsystem(command &u16) int
fn C._wgetenv(varname &u16) voidptr

fn C._putenv(envstring &char) int
fn C._wputenv(envstring &u16) int

fn C._waccess(path &u16, mode int) int

Expand Down
16 changes: 11 additions & 5 deletions vlib/os/environment.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,18 @@ pub fn getenv_opt(key string) ?string {
// os.setenv sets the value of an environment variable with `name` to `value`.
pub fn setenv(name string, value string, overwrite bool) int {
$if windows {
format := '${name}=${value}'
format := '${name}=${value}'.to_wide()
defer {
unsafe { free(voidptr(format)) }
}
if overwrite {
unsafe {
return C._putenv(&char(format.str))
return C._wputenv(format)
}
} else {
if getenv(name).len == 0 {
unsafe {
return C._putenv(&char(format.str))
return C._wputenv(format)
}
}
}
Expand All @@ -68,8 +71,11 @@ pub fn setenv(name string, value string, overwrite bool) int {
// os.unsetenv clears an environment variable with `name`.
pub fn unsetenv(name string) int {
$if windows {
format := '${name}='
return C._putenv(&char(format.str))
format := '${name}='.to_wide()
defer {
unsafe { free(voidptr(format)) }
}
return C._wputenv(format)
} $else {
return C.unsetenv(&char(name.str))
}
Expand Down
16 changes: 16 additions & 0 deletions vlib/os/environment_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,19 @@ fn test_getenv_empty_var() {
os.setenv('empty${key}', '""', false)
assert os.getenv('empty${key}') == '""'
}

fn test_environ_non_ascii() {
os.setenv('Büro', 'gebäude', false)
assert os.getenv('Büro') == 'gebäude'
os.setenv('Büro', 'gebäudehaus', true)
assert os.getenv('Büro') == 'gebäudehaus'
os.setenv('Büro', 'gebäudehaus in der Straße', true)
assert os.getenv('Büro') == 'gebäudehaus in der Straße'
os.unsetenv('Büro')
assert os.getenv('Büro') == ''

os.setenv('한국어', '초보자를 위한', false)
assert os.getenv('한국어') == '초보자를 위한'
os.unsetenv('한국어')
assert os.getenv('한국어') == ''
}

0 comments on commit ca67273

Please sign in to comment.