From 1019cca0609921a5fab91f794c8545628a1057e4 Mon Sep 17 00:00:00 2001 From: Antoine Stevan <44101798+amtoine@users.noreply.github.com> Date: Wed, 4 Oct 2023 19:33:11 +0200 Subject: [PATCH] update the `direnv` hook (#628) i wanted to install and run `direnv` with Nushell, came accross this hook and thought i could update it a bit :yum: ## changelog - make `config.nu` possible to `source` => it will add the hook to the list of hooks, without overwriting - will run the hook on environment change thank to `$env.config.hooks.env_change.PWD` instead of `$env.config.hooks.pre_prompt` => i think this is the most controversial change, we can discuss that of course - checks if `direnv` is in the `PATH` before running the rest of the hook - uses a oneliner with `default` to load the environment - uses directly a closure instead of string - the comments were out of date, so i removed them i tested this before and after and i think this works just as before :relieved: --- hooks/direnv/config.nu | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/hooks/direnv/config.nu b/hooks/direnv/config.nu index 0ca6120..a7c20d5 100644 --- a/hooks/direnv/config.nu +++ b/hooks/direnv/config.nu @@ -1,14 +1,26 @@ -## To enable direnv in nushell we must run code in the context of the current shell - i.e it cannot be within a block and it needs to run as a "code" string as per https://github.com/nushell/nushell/pull/5982 (so you must run nushell 0.66 or later). That way it works as if you'd typed in and run the code directly in your shell. -## Direnv knows what to do otherwise and will export the env to load (or unload) based on what is in your current environment so this is all that is needed with some checks for empty strings, defaulting then to an empty table so that load-env is always happy. +# you can use the following closure in your config in a few different ways, e.g. +# +# ```nushell +# $env.config.hooks.env_change.PWD = ( +# $env.config.hooks.env_change.PWD | append (source hooks/direnv/config.nu) +# ) +# ``` +# +# or +# +# ```nushell +# $env.config.hooks.pre_prompt = ( +# $env.config.hooks.pre_prompt | append (source hooks/direnv/config.nu) +# ) +# ``` +# +# > :bulb: **Note** +# > the former will update direnv when you enter and leave a directory whereas the later will update +# > on every new prompt, i.e. much more often. +{ || + if (which direnv | is-empty) { + return + } -$env.config = { - hooks: { - pre_prompt: [{ - code: " - let direnv = (direnv export json | from json) - let direnv = if not ($direnv | is-empty) { $direnv } else { {} } - $direnv | load-env - " - }] - } + direnv export json | from json | default {} | load-env }