1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

os: add os.getenv_opt/1

This commit is contained in:
Delyan Angelov 2021-11-19 17:32:01 +02:00
parent c2eb909c9b
commit 762a7fde2a
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 20 additions and 3 deletions

View File

@ -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)

View File

@ -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() {