diff --git a/modules/capture-foreign-env/README.md b/modules/capture-foreign-env/README.md new file mode 100644 index 0000000..bd04fcc --- /dev/null +++ b/modules/capture-foreign-env/README.md @@ -0,0 +1,5 @@ +# capture-foreign-env + +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). + +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. diff --git a/modules/capture-foreign-env/mod.nu b/modules/capture-foreign-env/mod.nu new file mode 100644 index 0000000..827bb42 --- /dev/null +++ b/modules/capture-foreign-env/mod.nu @@ -0,0 +1,28 @@ +# 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" +export def main [ + --shell (-s): string = /bin/sh + # The shell to run the script in + # (has to support '-c' argument and POSIX 'env', 'echo', 'eval' commands) + --arguments (-a): list = [] + # Additional command line arguments to pass to the foreign shell +] { + let script_contents = $in; + let env_out = with-env { SCRIPT_TO_SOURCE: $script_contents } { + ^$shell ...$arguments -c ` + env -0 + echo -n '' + eval "$SCRIPT_TO_SOURCE" + echo -n '' + env -0 -u _ -u _AST_FEATURES -u SHLVL` + } + | split row '' + | { + before: ($in | first | str trim --char (char nul) | split row (char nul)) + after: ($in | last | str trim --char (char nul) | split row (char nul)) + } + + $env_out.after + | where { |line| $line not-in $env_out.before } + | parse "{key}={value}" + | transpose --header-row --as-record +}