Skip to content

Commit a515c42

Browse files
authored
add capture-foreign-env module (#1099)
This is a modified version of [capture-foreign-env command from nushell wiki](https://www.nushell.sh/cookbook/foreign_shell_scripts.html#detailed-explanation-of-capture-foreign-env). Unlike the wiki version It relies on `null_byte` instead of `newline` as a delimiter for environment variables dumped by the `env` command which allows it to support multi-line foreign environment variables.
1 parent 488b9b0 commit a515c42

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# capture-foreign-env
2+
3+
This is a modified version of the [capture-foreign-env command from the nushell wiki](https://www.nushell.sh/cookbook/foreign_shell_scripts.html#detailed-explanation-of-capture-foreign-env).
4+
5+
Unlike the wiki version It relies on `null_byte` instead of `newline` as a delimiter for environment variables dumped by the `env` command which allows it to support multi-line foreign environment variables.

modules/capture-foreign-env/mod.nu

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Returns a record of changed env variables after running a non-nushell script's contents (passed via stdin), e.g. a bash script you want to "source"
2+
export def main [
3+
--shell (-s): string = /bin/sh
4+
# The shell to run the script in
5+
# (has to support '-c' argument and POSIX 'env', 'echo', 'eval' commands)
6+
--arguments (-a): list<string> = []
7+
# Additional command line arguments to pass to the foreign shell
8+
] {
9+
let script_contents = $in;
10+
let env_out = with-env { SCRIPT_TO_SOURCE: $script_contents } {
11+
^$shell ...$arguments -c `
12+
env -0
13+
echo -n '<ENV_CAPTURE_EVAL_FENCE>'
14+
eval "$SCRIPT_TO_SOURCE"
15+
echo -n '<ENV_CAPTURE_EVAL_FENCE>'
16+
env -0 -u _ -u _AST_FEATURES -u SHLVL`
17+
}
18+
| split row '<ENV_CAPTURE_EVAL_FENCE>'
19+
| {
20+
before: ($in | first | str trim --char (char nul) | split row (char nul))
21+
after: ($in | last | str trim --char (char nul) | split row (char nul))
22+
}
23+
24+
$env_out.after
25+
| where { |line| $line not-in $env_out.before }
26+
| parse "{key}={value}"
27+
| transpose --header-row --as-record
28+
}

0 commit comments

Comments
 (0)