From 762a7fde2a35825c7c2706466a5a2492935a3300 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 19 Nov 2021 17:32:01 +0200 Subject: [PATCH] os: add os.getenv_opt/1 --- vlib/os/environment.c.v | 18 +++++++++++++++--- vlib/os/environment_test.v | 5 +++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/vlib/os/environment.c.v b/vlib/os/environment.c.v index 1b65a2792..c390ce813 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 532437124..0c454bd14 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() { -- 2.30.2