Skip to content

Instantly share code, notes, and snippets.

@nothingmuch
Created March 15, 2023 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nothingmuch/716afcc93bf3ab0a11ced6b27c06e4da to your computer and use it in GitHub Desktop.
Save nothingmuch/716afcc93bf3ab0a11ced6b27c06e4da to your computer and use it in GitHub Desktop.
# This script lives in my home manager home.packages. I also have:
#
# programs.direnv.enable = true;
# programs.direnv.nix-direnv.enable = true;
#
# To enable a language, I use e.g.:
#
# nix registry add rust-direnv ~/code/dev-templates/rust
#
# where the directory is my local fork of https://github.com/the-nix-way/dev-templates
(writeShellScriptBin "mkenvrc" ''
set -e
# construct a regex that matches languages supported in the nix registry
# which is any user flake that named "<language>-direnv".
known_langs_re="$(
${pkgs.nix}/bin/nix registry list |
${pkgs.perl}/bin/perl -nE 'push @l,$1 if /^user\s+flake:([\w-]+)-direnv/; END { say join("|", map quotemeta, @l) }' )";
# construct a string of use flake directives to append to .envrc based on
# the languages tokei found under the current directory all tokei language
# names are normalized to lowercase with \W+ runs replaced with dashes
# TODO sort by .code? tokei outputs an object, not a list, kinda annoying
# to sort
append="$(
(for lang in $(
${pkgs.tokei}/bin/tokei -o json |
${pkgs.jq}/bin/jq --raw-output 'to_entries | sort_by(-.value.code) | .[] | .key | ascii_downcase' |
${pkgs.gnused}/bin/sed 's/\W+/-/'
); do
if echo "$lang" | ${pkgs.gnugrep}/bin/egrep "$known_langs_re" >/dev/null; then
[ -e .envrc ] && ${pkgs.gnugrep}/bin/grep "$lang" .envrc >/dev/null || echo "use flake $lang-direnv"
# else
# TODO echo "$lang in project but direnv support not in nix registry...";
fi
done)|
${pkgs.skim}/bin/sk --no-sort --multi --query "$*"
)";
# if we made it this far something was selected, we can append and enable,
# interrupting sk or selecting nothing in sk will leave .envrc unmodified
# due to the set -e above
echo "$append" >> .envrc
direnv allow
'')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment