Add nix_direnv_watch_file command

Used to watch files that, when changed, trigger an update of the
cached nix environment.
This commit is contained in:
polygon 2022-02-23 23:36:01 +01:00
parent 60a6964eae
commit 1241f1115e
2 changed files with 60 additions and 18 deletions

View file

@ -232,17 +232,30 @@ direnv_layout_dir() {
During direnv setup `direnv_layout_dir` can be called multiple times and with different values of `$PWD`
(when other `.envrc` files are included). Therefore cache its results in dictionary `direnv_layout_dirs`.
## Manually re-triggering evaluation
## Watching additional files
In some case nix-direnv does not detect if imported file has changed and still
provides the old cached values. An evaluation can be triggered by updating your
`default.nix`, `shell.nix` or `flake.nix`, depending on what is used:
To minimize the number of evaluations, nix-direnv maintains a list of files to check
for changes when deciding if an update of the cached environment is required. By default, `use_flake` watches
```console
# choose one
$ touch default.nix
$ touch shell.nix
$ touch flake.nix
```
flake.nix
flake.lock
devshell.toml
```
`use_nix` watches
```
default.nix
shell.nix
```
To trigger an evaluation when other nix files change, register them by calling `nix_direnv_watch_file PATH [PATH...]` from `.envrc`.
```bash
nix_direnv_watch_file module.nix
nix_direnv_watch_file mod1.nix mod2.nix
use flake
```
## Shell integration

View file

@ -111,6 +111,11 @@ _nix_argsum_suffix() {
fi
}
nix_direnv_watch_file() {
watch_file "$@"
nix_watches+=("$@")
}
use_flake() {
flake_expr="${1:-.}"
flake_dir="${flake_expr%#*}"
@ -123,13 +128,25 @@ use_flake() {
local flake_inputs="${layout_dir}/flake-inputs/"
local profile_rc="${profile}.rc"
nix_watches+=(
"$HOME/".direnvrc
.envrc
"$flake_dir/"devshell.toml
"$flake_dir/"flake.nix
"$flake_dir/"flake.lock
)
need_update=0
for file in "${nix_watches[@]}"; do
if [[ "$file" -nt "$profile_rc" ]]; then
need_update=1
break
fi
done
if [[ ! -e "$profile"
|| ! -e "$profile_rc"
|| "$HOME/.direnvrc" -nt "$profile_rc"
|| .envrc -nt "$profile_rc"
|| "$flake_dir/"devshell.toml -nt "$profile_rc"
|| "$flake_dir/"flake.nix -nt "$profile_rc"
|| "$flake_dir/"flake.lock -nt "$profile_rc"
|| "$need_update" -eq "1"
]];
then
local tmp_profile="${layout_dir}/flake-profile.$$"
@ -239,12 +256,24 @@ use_nix() {
local cache
cache="${layout_dir}/cache-${version:-unknown}$(_nix_argsum_suffix "$*")"
nix_watches+=(
"$HOME/".direnvrc
.envrc
default.nix
shell.nix
)
need_update=0
for file in "${nix_watches[@]}"; do
if [[ "$file" -nt "$cache" ]]; then
need_update=1
break
fi
done
local update_drv=0
if [[ ! -e "$cache"
|| "$HOME/.direnvrc" -nt "$cache"
|| .envrc -nt "$cache"
|| default.nix -nt "$cache"
|| shell.nix -nt "$cache"
|| "$need_update" -eq "1"
]];
then
[[ -d "$layout_dir" ]] || mkdir -p "$layout_dir"