Skip to content

Commit 9e520f3

Browse files
committed
[stdlib-candidate] set-env
1 parent 7fcbf54 commit 9e520f3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

stdlib-candidate/set-env.nu

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Gracefully set an environment variable or merge a nested option.
2+
#
3+
# Examples:
4+
# Set $env.NUPM_HOME
5+
# > set-env NUPM_HOME $'($nu.home-path)/.local/share/nupm'
6+
#
7+
# Add to $env.NU_LIB_DIRS
8+
# > set-env --append NU_LIB_DIRS $'($env.NUPM_HOME)/modules'
9+
#
10+
# Set a nested config option
11+
# > set-env config.filesize.metric true
12+
#
13+
# Add a config hook
14+
# > set-env -a config.hooks.pre_prompt 'ellie | print'
15+
export def --env main [
16+
path: cell-path # The environment variable name or nested option path
17+
value: any # The value to set or append
18+
--append (-a) # Append to the previous value or wrap in a new list
19+
]: nothing -> nothing {
20+
def 'get or' [default path] { get --ignore-errors $path | default $default }
21+
let value = if $append {
22+
$env | get or [] $path | append $value
23+
} else {
24+
$value
25+
}
26+
let path = $path | to text | split row .
27+
let value = match $path {
28+
[_] => $value
29+
[$root, ..$path] => {
30+
$env | get or {} $root | upsert ($path | into cell-path) $value
31+
}
32+
}
33+
load-env { ($path | first): $value }
34+
}

0 commit comments

Comments
 (0)