Skip to content

Instantly share code, notes, and snippets.

@lionello
Forked from sveitser/.direnvrc
Last active Aug 6, 2019
Embed
What would you like to do?
#!/bin/bash
#
# Cache nix-shell environment
#
# - watches shell.nix (or default.nix), ~/.direnvrc and .envrc
# - based on https://github.com/direnv/direnv/wiki/Nix
#
use_nix() {
local shell_file=$(test -f shell.nix && echo shell.nix || echo default.nix)
if [[ ! -f "$shell_file" ]]; then return; fi
local cache_key=$(nix-instantiate "$shell_file" 2> /dev/null | shasum -a 1 | cut -d ' ' -f 1)
# Use ram as virtualenv storage
local tmpdir
case $(uname -s) in
Linux*) tmpdir=$XDG_RUNTIME_DIR;;
Darwin*) tmpdir_SDK=$TMPDIR;;
*) tmpdir=/tmp
esac
if test "$tmpdir" = ""; then
tmpdir="/tmp"
fi
local cachedir="${tmpdir}/direnv-nix"
mkdir -p $cachedir
local cache="$cachedir/$cache_key"
if [[ ! -e "$cache" ]] || \
[[ "~/.direnvrc" -nt "$cache" ]] || \
[[ ".envrc" -ot "$cache" ]] || \
[[ ".envrc" -nt "$cache" ]];
then
local tmp="$(mktemp "${cache_key}.tmp-XXXXXXXX")"
trap "rm -r '$tmp' || true" EXIT
nix-instantiate "$shell_file" --indirect --add-root ~/.direnv-gcroots/"$cache_key"
nix-shell --show-trace "$@" --run 'direnv dump' > "$tmp" || exit $?
# Copy the filetime but use POSIX precision for both
touch -r ".envrc" "$tmp"
mv "$tmp" "$cache"
echo "Created cache at $cache"
else
echo "Using cache at $cache"
fi
direnv_load cat "$cache"
if [[ $# -eq 0 ]]; then
watch_file "$shell_file"
watch_file shell.nix
fi
}
# GistId: 3cb29d9eea83938622eec9ff3bfb3b69
@lionello
Copy link
Author

lionello commented Sep 7, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment