nix-direnv/direnvrc
Jörg Thalheim ee17ef31d0 use_flake: make shellHook usable again; use _nix_import_env
Now that use_nix allows shellHook, we can do the same for use_flake.
2021-11-19 09:38:08 +01:00

280 lines
7.8 KiB
Text

# shellcheck shell=bash
# Usage: nix_direnv_version <version_at_least>
#
# Checks that the nix-direnv version is at least as old as <version_at_least>.
nix_direnv_version() {
declare major='1' minor='5' patch='0' # UPDATE(nix-direnv version)
[[ $1 =~ ^([^+-.]*)(\.?)([^+-.]*)(\.?)([^+-]*)(-?)([^+]*)(\+?)(.*)$ ]]
declare -a ver; ver=("${BASH_REMATCH[@]:1}")
if [[ ( ${ver[0]} != +([0-9]) ) \
|| ( ${ver[1]} == '.' && ${ver[2]} != +([0-9]) ) \
|| ( ${ver[3]} == '.' && ${ver[4]} != +([0-9]) ) \
|| ( ${ver[5]} == '-' && ${ver[6]} != +([0-9A-Za-z-])*(.+([0-9A-Za-z-])) ) \
|| ( ${ver[7]} == '+' && ${ver[8]} != +([0-9A-Za-z-])*(.+([0-9A-Za-z-])) ) \
|| ( ( -n ${ver[5]} || -n ${ver[7]} ) && ( -z ${ver[2]} || -z ${ver[4]} ) ) \
]]; then
printf '%s\n' "nix-direnv: error v$1 is not a valid semver version" >&2
return 1
fi
if [[ ( ${ver[0]} -gt $major ) \
|| ( ${ver[2]:=0} -gt $minor ) \
|| ( ${ver[4]:=0} -gt $patch ) \
]]; then
printf '%s\n' "nix-direnv: error current version v$major.$minor.$patch is older than the desired version v$1" >&2
return 1
fi
}
if [[ -z ${NIX_BIN_PREFIX:-} ]]; then
NIX_BIN_PREFIX=$(command -v nix-shell)
NIX_BIN_PREFIX="${NIX_BIN_PREFIX%/*}/"
fi
_nix_export_or_unset() {
local key=$1 value=$2
if [[ "$value" == __UNSET__ ]]; then
unset "$key"
else
export "$key=$value"
fi
}
_nix_import_env() {
local profile_rc=$1
local old_nix_build_top=${NIX_BUILD_TOP:-__UNSET__}
local old_tmp=${TMP:-__UNSET__}
local old_tmpdir=${TMPDIR:-__UNSET__}
local old_temp=${TEMP:-__UNSET__}
local old_tempdir=${TEMPDIR:-__UNSET__}
local old_xdg_data_dirs=${XDG_DATA_DIRS:-}
eval "$(< "$profile_rc")"
# nix print-env-dev will create a temporary directory and use it a TMPDIR,
# we cannot rely on this directory beeing not deleted at some point,
# hence we are just removing it right away.
if [[ "$NIX_BUILD_TOP" == */nix-shell.* && -d "$NIX_BUILD_TOP" ]]; then
rmdir "$NIX_BUILD_TOP"
fi
_nix_export_or_unset NIX_BUILD_TOP "$old_nix_build_top"
_nix_export_or_unset TMP "$old_tmp"
_nix_export_or_unset TMPDIR "$old_tmpdir"
_nix_export_or_unset TEMP "$old_temp"
_nix_export_or_unset TEMPDIR "$old_tempdir"
export XDG_DATA_DIRS=$XDG_DATA_DIRS${old_xdg_data_dirs:+":"}$old_xdg_data_dirs
}
_nix_add_gcroot() {
local storepath=$1
local symlink=$2
local stripped_pwd=${2/\//}
local escaped_pwd=${stripped_pwd//-/--}
local escaped_pwd=${escaped_pwd//\//-}
ln -fsn "$storepath" "$symlink"
ln -fsn "$symlink" "/nix/var/nix/gcroots/per-user/$USER/$escaped_pwd"
}
_nix_argsum_suffix() {
local out checksum
if [ -n "$1" ]; then
if has sha1sum; then
out=$(sha1sum <<< "$1")
elif has shasum; then
out=$(shasum <<< "$1")
else
# degrate gracefully both tools are not present
return
fi
read -r checksum _ <<< "$out"
echo "-$checksum"
fi
}
use_flake() {
flake_expr="${1:-.}"
flake_dir="${flake_expr%#*}"
watch_file "$flake_dir/"flake.nix
watch_file "$flake_dir/"flake.lock
local layout_dir profile
layout_dir=$(direnv_layout_dir)
profile="${layout_dir}/flake-profile$(_nix_argsum_suffix "$flake_expr")"
local flake_inputs="${layout_dir}/flake-inputs/"
local profile_rc="${profile}.rc"
if [[ ! -e "$profile"
|| ! -e "$profile_rc"
|| "$HOME/.direnvrc" -nt "$profile_rc"
|| .envrc -nt "$profile_rc"
|| "$flake_dir/"flake.nix -nt "$profile_rc"
|| "$flake_dir/"flake.lock -nt "$profile_rc"
]];
then
local tmp_profile="${layout_dir}/flake-profile.$$"
[[ -d "$layout_dir" ]] || mkdir -p "$layout_dir"
local tmp_profile_rc
tmp_profile_rc=$("${NIX_BIN_PREFIX}nix" print-dev-env \
--extra-experimental-features "nix-command flakes" \
--profile "$tmp_profile" "$flake_expr")
drv=$(ls -dl "$tmp_profile")
drv=${drv#*-> }
echo "$tmp_profile_rc" > "$profile_rc"
rm -f "$tmp_profile" "$tmp_profile"*
_nix_add_gcroot "$drv" "$profile"
# also add garbage collection root for source
local flake_input_paths
rm -rf "$flake_inputs"
mkdir "$flake_inputs"
flake_input_paths=$("${NIX_BIN_PREFIX}nix" flake archive --json \
--extra-experimental-features "nix-command flakes" \
"$flake_dir" | grep -E -o '/nix/store/[^"]+')
for path in $flake_input_paths; do
_nix_add_gcroot "$path" "${flake_inputs}/${path##*/}"
done
log_status renewed cache
else
log_status using cached dev shell
fi
_nix_import_env "$profile_rc"
}
use_nix() {
local path layout_dir
path=$("${NIX_BIN_PREFIX}nix-instantiate" --find-file nixpkgs)
layout_dir=$(direnv_layout_dir)
if ! "${NIX_BIN_PREFIX}nix-shell" --extra-experimental-features '' --version 2>/dev/null >&2; then
log_status "Your nix is too old for nix-direnv. At least nix 2.4 is required"
return
fi
if [[ "${direnv:-}" == "" ]]; then
log_status "\$direnv environment variable was not defined. Was this script run inside direnv?"
fi
local version
if [[ -f "${path}/.version-suffix" ]]; then
version=$(< "${path}/.version-suffix")
elif [[ -f "${path}/.git/HEAD" ]]; then
local head
read -r head < "${path}/.git/HEAD"
local regex="ref: (.*)"
if [[ "$head" =~ $regex ]]; then
read -r version < "${path}/.git/${BASH_REMATCH[1]}"
else
version="$head"
fi
elif [[ -f "${path}/.version" && "${path}" == "/nix/store/"* ]]; then
# borrow some bits from the store path
local version_prefix
read -r version_prefix < "${path}/.version"
version="${version_prefix}-${path:11:16}"
fi
local profile
profile="${layout_dir}/nix-profile-${version:-unknown}$(_nix_argsum_suffix "$*")"
local profile_rc="${profile}.rc"
local in_packages=0
local attribute=
local packages=""
local extra_args=()
local file=
while [ "$#" -gt 0 ]; do
i="$1"; shift
case $i in
-p|--packages)
in_packages=1
;;
# ignore unsupported arguments
--command|--run|--exclude)
shift
;;
# ignore unsupported arguments
--pure|-i|--keep)
;;
-I)
extra_args+=("$i" "$1")
shift
;;
--attr|-A)
attribute=$1
shift
;;
--option|-o|--arg|--argstr)
extra_args+=("$i" "$1" "$2")
shift
shift
;;
-*)
echo "unknown argument $i"
return
;;
*)
if [[ $in_packages == 1 ]]; then
packages+=" $i"
else
file=$i
fi
;;
esac
done
if [[ ! -e "$profile"
|| ! -e "$profile_rc"
|| "$HOME/.direnvrc" -nt "$profile_rc"
|| .envrc -nt "$profile_rc"
|| default.nix -nt "$profile_rc"
|| shell.nix -nt "$profile_rc"
]];
then
local tmp_profile="${layout_dir}/flake-profile.$$"
[[ -d "$layout_dir" ]] || mkdir -p "$layout_dir"
local tmp_profile_rc
local extra_args=()
if [[ $packages != "" ]]; then
extra_args+=("--expr" "with import <nixpkgs> {}; mkShell { buildInputs = [ $packages ]; }")
else
if [[ $file == "" ]]; then
if [[ -e "shell.nix" ]]; then
file=./shell.nix
elif [[ -e "default.nix" ]]; then
file=./default.nix
fi
fi
if [[ $attribute == "" ]]; then
extra_args+=(--file "$file")
else
extra_args+=(--expr "(import $file).${attribute}")
fi
fi
tmp_profile_rc=$("${NIX_BIN_PREFIX}nix" print-dev-env \
--extra-experimental-features "nix-command flakes" \
--profile "$tmp_profile" --impure "${extra_args[@]}")
drv=$(ls -dl "$tmp_profile")
drv=${drv#*-> }
echo "$tmp_profile_rc" > "$profile_rc"
rm -f "$tmp_profile" "$tmp_profile"*
_nix_add_gcroot "$drv" "$profile"
log_status renewed cache
else
log_status using cached derivation
fi
_nix_import_env "$profile_rc"
if [[ "$#" == 0 ]]; then
watch_file default.nix
watch_file shell.nix
fi
}