home-manager: internalize uninstall

This adds a Boolean option `uninstall`. When enabled this option will
reset side-effecting configurations to their "empty" state. The intent
is that this will cause the activation script to remove all managed
files and packages.

Doing it this way should hopefully be more robust than the previous
solution. It also allows a somewhat more convenient uninstall process
when using Flakes; put `uninstall = true` in your existing
configuration and then do a switch.

Also add simple uninstall test in CI test job.
This commit is contained in:
Robert Helgesson
2024-01-06 00:22:27 +01:00
parent 93e804e7f8
commit 7403ed4980
7 changed files with 118 additions and 77 deletions

View File

@@ -585,44 +585,14 @@ in
if config.submoduleSupport.externalPackageInstall
then
''
# We don't use `cfg.profileDirectory` here because it defaults to
# `/etc/profiles/per-user/<user>` which is constructed by NixOS or
# nix-darwin and won't require uninstalling `home-manager-path`.
if [[ -e $HOME/.nix-profile/manifest.json \
|| -e "''${XDG_STATE_HOME:-$HOME/.local/state}/nix/profile/manifest.json" ]] ; then
nix profile list \
| { grep 'home-manager-path$' || test $? = 1; } \
| cut -d ' ' -f 4 \
| xargs -rt $DRY_RUN_CMD nix profile remove $VERBOSE_ARG
else
if nix-env -q | grep '^home-manager-path$'; then
$DRY_RUN_CMD nix-env -e home-manager-path
fi
fi
nixProfileRemove home-manager-path
''
else
''
function nixProfileList() {
# We attempt to use `--json` first (added in Nix 2.17). Otherwise attempt to
# parse the legacy output format.
{
nix profile list --json 2>/dev/null \
| jq -r --arg name "$1" '.elements[].storePaths[] | select(endswith($name))'
} || {
nix profile list \
| { grep "$1\$" || test $? = 1; } \
| cut -d ' ' -f 4
}
}
function nixRemoveProfileByName() {
nixProfileList "$1" | xargs -t $DRY_RUN_CMD nix profile remove $VERBOSE_ARG
}
function nixReplaceProfile() {
local oldNix="$(command -v nix)"
nixRemoveProfileByName 'home-manager-path'
nixProfileRemove 'home-manager-path'
$DRY_RUN_CMD $oldNix profile install $1
}
@@ -644,7 +614,7 @@ in
_iError $'Oops, Nix failed to install your new Home Manager profile!\n\nPerhaps there is a conflict with a package that was installed using\n"%s"? Try running\n\n %s\n\nand if there is a conflicting package you can remove it with\n\n %s\n\nThen try activating your Home Manager configuration again.' "$INSTALL_CMD" "$LIST_CMD" "$REMOVE_CMD_SYNTAX"
exit 1
fi
unset -f nixProfileList nixRemoveProfileByName nixReplaceProfile
unset -f nixReplaceProfile
unset INSTALL_CMD INSTALL_CMD_ACTUAL LIST_CMD REMOVE_CMD_SYNTAX
''
);