os: add os.getenv_opt/1
parent
c2eb909c9b
commit
762a7fde2a
|
@ -11,18 +11,30 @@ fn C.GetEnvironmentStringsW() &u16
|
||||||
fn C.FreeEnvironmentStringsW(&u16) int
|
fn C.FreeEnvironmentStringsW(&u16) int
|
||||||
|
|
||||||
// `getenv` returns the value of the environment variable named by the key.
|
// `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 {
|
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 {
|
unsafe {
|
||||||
$if windows {
|
$if windows {
|
||||||
s := C._wgetenv(key.to_wide())
|
kw := key.to_wide()
|
||||||
|
defer {
|
||||||
|
free(voidptr(kw))
|
||||||
|
}
|
||||||
|
s := C._wgetenv(kw)
|
||||||
if s == 0 {
|
if s == 0 {
|
||||||
return ''
|
return none
|
||||||
}
|
}
|
||||||
return string_from_wide(s)
|
return string_from_wide(s)
|
||||||
} $else {
|
} $else {
|
||||||
s := C.getenv(&char(key.str))
|
s := C.getenv(&char(key.str))
|
||||||
if s == voidptr(0) {
|
if s == voidptr(0) {
|
||||||
return ''
|
return none
|
||||||
}
|
}
|
||||||
// NB: C.getenv *requires* that the result be copied.
|
// NB: C.getenv *requires* that the result be copied.
|
||||||
return cstring_to_vstring(s)
|
return cstring_to_vstring(s)
|
||||||
|
|
|
@ -7,6 +7,10 @@ fn test_getenv() {
|
||||||
assert os.getenv('PATH').len > 0
|
assert os.getenv('PATH').len > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn test_getenv_opt() {
|
||||||
|
assert os.getenv_opt('VEXE') or { '' }.len > 0
|
||||||
|
}
|
||||||
|
|
||||||
fn test_setenv() {
|
fn test_setenv() {
|
||||||
os.setenv('foo', 'bar', true)
|
os.setenv('foo', 'bar', true)
|
||||||
assert os.getenv('foo') == 'bar'
|
assert os.getenv('foo') == 'bar'
|
||||||
|
@ -16,6 +20,7 @@ fn test_setenv() {
|
||||||
// `setenv` should overwrite if `overwrite` is true
|
// `setenv` should overwrite if `overwrite` is true
|
||||||
os.setenv('foo', 'bar2', true)
|
os.setenv('foo', 'bar2', true)
|
||||||
assert os.getenv('foo') == 'bar2'
|
assert os.getenv('foo') == 'bar2'
|
||||||
|
assert os.getenv_opt('foo') or { '' } == 'bar2'
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_unsetenv() {
|
fn test_unsetenv() {
|
||||||
|
|
Loading…
Reference in New Issue