Skip to main content

max / alloy

1.9 KB · 44 lines History Blame Raw
1 # direnv, wired into nushell by hand.
2 #
3 # The other integrations in this directory are generated at image build time
4 # from each tool's own init output (see the Containerfile). direnv has no
5 # such output to generate: as of 2.35.0 its `hook` and `export` targets are
6 # bash, zsh, fish, elvish, tcsh, murex, pwsh, vim, systemd, gha, json and
7 # gzenv, with no nu among them. `json` is the seam this file is built on,
8 # and it is a supported target rather than a workaround: `direnv export
9 # json` prints the pending environment diff as a JSON object, which is the
10 # shape nushell wants anyway.
11 #
12 # In that object a value is the variable's new value and a null means unset.
13 # direnv's own status lines ("direnv: loading .envrc") go to stderr, so they
14 # reach the terminal untouched while stdout stays parseable.
15 #
16 # This file lands in the vendor autoload directory, which nushell reads
17 # after config.nu. That ordering is what makes the hook below stick:
18 # config.nu assigns $env.config wholesale, hooks included, so anything
19 # registered before it would be discarded.
20
21 # Apply direnv's pending environment diff to this shell. Called from the
22 # pre_prompt hook below, and useful by hand after editing an .envrc.
23 def --env direnv-reload [] {
24 if (which direnv | is-empty) { return }
25
26 let diff = (direnv export json | str trim)
27 if ($diff | is-empty) { return }
28 let diff = ($diff | from json)
29
30 # PATH is handled apart from the rest. nushell keeps it as a list and
31 # direnv reports it the way the rest of the world writes it, as one
32 # colon-joined string, so loading it verbatim would leave the shell with
33 # a PATH it cannot search.
34 $diff | reject --optional PATH | load-env
35 if "PATH" in ($diff | columns) {
36 let raw = ($diff | get PATH)
37 $env.PATH = (if $raw == null { [] } else { $raw | split row (char esep) })
38 }
39 }
40
41 $env.config.hooks.pre_prompt = (
42 $env.config.hooks.pre_prompt | default [] | append {|| direnv-reload }
43 )
44