Files
nix/hosts/common/configs/user/console/nix-direnv/default.nix
Nikolaos Karaolidis 184aa4da8f Update
Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
2025-07-13 23:33:27 +01:00

119 lines
3.4 KiB
Nix

{ user, home }:
{
lib,
pkgs,
inputs,
system,
...
}:
{
home-manager.users.${user}.programs = {
direnv = {
enable = true;
silent = true;
nix-direnv.enable = true;
enableZshIntegration = true;
config = {
global.warn_timeout = 0;
};
# https://github.com/direnv/direnv/wiki/Customizing-cache-location
stdlib = ''
declare -A direnv_layout_dirs
direnv_layout_dir() {
local hash path
echo "''${direnv_layout_dirs[$PWD]:=$(
hash="$(sha1sum - <<< "$PWD" | head -c40)"
path="''${PWD//[^a-zA-Z0-9]/-}"
echo "${home}/.cache/direnv/layouts/''${hash}''${path}"
)}"
}
'';
};
zsh = {
shellAliases.nde = "nix-direnv";
initContent =
let
devShells = lib.strings.concatStringsSep " " (
lib.attrsets.mapAttrsToList (key: _: key) inputs.self.devShells.${system}
);
in
''
nix-direnv() {
local devshell=""
local hide=false
while getopts "s:h" opt; do
case $opt in
s)
devshell="$OPTARG"
;;
h)
hide=true
;;
*)
echo "Usage: nix-direnv [-s <devshell>] [-h]"
return 1
;;
esac
done
if [[ -z "$devshell" ]]; then
if "$hide"; then
echo "use flake path:." > .envrc;
else
echo "use flake" > .envrc;
fi
if [ ! -f flake.nix ]; then
cp "${../nix-develop/template.nix}" flake.nix
chmod 755 flake.nix
fi
if [ ! -f treefmt.nix ]; then
cp "${../nix-develop/treefmt.nix}" treefmt.nix
chmod 755 treefmt.nix
fi
else
echo "use flake self#$devshell" > .envrc
fi
if "$hide" && git rev-parse --is-inside-work-tree &>/dev/null; then
local top
top="$(git rev-parse --show-toplevel)"
if ! grep -q "^\.envrc$" "$top/.gitignore" "$top/.git/info/exclude"; then echo "$(realpath --relative-to="$top" .envrc)" >> "$top/.git/info/exclude"; fi
if [ -z "$devshell" ]; then
if ! grep -q "^flake.nix$" "$top/.gitignore" "$top/.git/info/exclude"; then echo "flake.nix" >> "$top/.git/info/exclude"; fi
if ! grep -q "^flake.lock$" "$top/.gitignore" "$top/.git/info/exclude"; then echo "flake.lock" >> "$top/.git/info/exclude"; fi
if ! grep -q "^treefmt.nix$" "$top/.gitignore" "$top/.git/info/exclude"; then echo "treefmt.nix" >> "$top/.git/info/exclude"; fi
fi
fi
direnv allow
}
_nix-direnv_completion() {
local options=(
'-s[Dev shell from root flake]:shell:(${devShells})'
'-h[Hide .envrc and flake.nix in git]'
)
_arguments -s $options
}
compdef _nix-direnv_completion nix-direnv
'';
p10k.extraRightPromptElements = [ "direnv" ];
};
};
environment.persistence = {
"/persist/state"."${home}/.local/share/direnv/allow" = { };
"/persist/cache"."${home}/.cache/direnv" = { };
};
}