-
-
Save lionello/4ba29a03c128fefdf3ed52d5e7d5ac4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same as https://gist.github.com/lionello/3cb29d9eea83938622eec9ff3bfb3b69