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:
parent
c2eb909c9b
commit
762a7fde2a
@ -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)
|
||||
|
@ -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() {
|
||||
|
Loading…
Reference in New Issue
Block a user