Skip to content

Instantly share code, notes, and snippets.

@danbst
Last active January 15, 2024 22:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save danbst/f07d9760ed15dd844e141177cf7dd478 to your computer and use it in GitHub Desktop.
Save danbst/f07d9760ed15dd844e141177cf7dd478 to your computer and use it in GitHub Desktop.
Imperative nix-env rewrite (so it becomes declarative)
#!/usr/bin/env bash
statefile=~/.config/nixpkgs/declarative
action="$1"
package="$2"
mkdir -p $(dirname "$statefile")
touch "$statefile"
function update {
envExpr=~/.config/nixpkgs/declarative-env.nix
truncate -s 0 "$envExpr"
for ch in $(ls /nix/var/nix/profiles/per-user/root/channels | grep -v -e manifest -e binary-caches) ; do
echo "let $ch = import <$ch> { }; in" >> "$envExpr"
done
echo "let _pkgs = import <nixpkgs> { }; in" >> "$envExpr"
echo "rec { _paths = [" >> "$envExpr"
cat "$statefile" | sort -u >> "$envExpr"
echo " ]; " >> "$envExpr"
echo " env = _pkgs.buildEnv {" >> "$envExpr"
echo " name = ''declarative-collection''; " >> "$envExpr"
echo " paths = _paths;" >> "$envExpr"
echo "}; }" >> "$envExpr"
\nix-env -Q -if "$envExpr" -A env && echo "# Updated successfully!" >> "$envExpr"
}
case "$action" in
install|add)
if (grep -Eq "^$package\$" "$statefile"); then
echo "already installed, updating"
else
echo "scheduled install'n'update"
echo "$package" >> "$statefile"
fi
# TODO: trap
update && echo Success || sed -i "/^$package$/d" $statefile
;;
uninstall|remove|delete)
if (grep -Eq "^$package\$" "$statefile"); then
sed -i "/^$package\$/d" $statefile
update && echo "Success"
else
echo Not installed
fi
;;
list)
cat "$statefile"
;;
*)
echo Command not specified. Try $(basename "$0") install nixpkgs.htop
echo Command list: install, uninstall, list
;;
esac
@CamoCatX
Copy link

Reminder to whoever uses this script: alias nix-env=/path/to/script

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