diff --git a/vlib/os/environment.c.v b/vlib/os/environment.c.v index 1b65a27920..c390ce813a 100644 --- a/vlib/os/environment.c.v +++ b/vlib/os/environment.c.v @@ -11,18 +11,30 @@ fn C.GetEnvironmentStringsW() &u16 fn C.FreeEnvironmentStringsW(&u16) int // `getenv` returns the value of the environment variable named by the key. +// If there is not one found, it returns an empty string ''. pub fn getenv(key string) string { + return getenv_opt(key) or { '' } +} + +// `getenv_opt` returns the value of the environment variable named by the key +// If there is not one found, it returns `none`. +[manualfree] +pub fn getenv_opt(key string) ?string { unsafe { $if windows { - s := C._wgetenv(key.to_wide()) + kw := key.to_wide() + defer { + free(voidptr(kw)) + } + s := C._wgetenv(kw) if s == 0 { - return '' + return none } return string_from_wide(s) } $else { s := C.getenv(&char(key.str)) if s == voidptr(0) { - return '' + return none } // NB: C.getenv *requires* that the result be copied. return cstring_to_vstring(s) diff --git a/vlib/os/environment_test.v b/vlib/os/environment_test.v index 532437124f..0c454bd14e 100644 --- a/vlib/os/environment_test.v +++ b/vlib/os/environment_test.v @@ -7,6 +7,10 @@ fn test_getenv() { assert os.getenv('PATH').len > 0 } +fn test_getenv_opt() { + assert os.getenv_opt('VEXE') or { '' }.len > 0 +} + fn test_setenv() { os.setenv('foo', 'bar', true) assert os.getenv('foo') == 'bar' @@ -16,6 +20,7 @@ fn test_setenv() { // `setenv` should overwrite if `overwrite` is true os.setenv('foo', 'bar2', true) assert os.getenv('foo') == 'bar2' + assert os.getenv_opt('foo') or { '' } == 'bar2' } fn test_unsetenv() {