From 2262e91b5aeb699310a3a0c08dfddc37f41c437f Mon Sep 17 00:00:00 2001 From: Tomas Rivera Date: Mon, 18 May 2026 18:56:01 +0200 Subject: [PATCH] nix: add script to clean up my system --- hostsModules/laptop/scripts/cleanNix.nix | 68 ++++++++++++++++++++++++ modules/nixos/nixUtils.nix | 3 ++ 2 files changed, 71 insertions(+) create mode 100644 hostsModules/laptop/scripts/cleanNix.nix diff --git a/hostsModules/laptop/scripts/cleanNix.nix b/hostsModules/laptop/scripts/cleanNix.nix new file mode 100644 index 0000000..d493c0f --- /dev/null +++ b/hostsModules/laptop/scripts/cleanNix.nix @@ -0,0 +1,68 @@ +{ + pkgs, + ... +}: +pkgs.writeShellApplication { + name = "custom-cleanNix"; + + runtimeInputs = with pkgs; [ + git + nixos-rebuild + matrix-commander-rs + libnotify + alejandra + deadnix + ]; + + text = '' + set -e + + FLAKE_DIR="/home/tomasr/nixos" + FLAKE="$FLAKE_DIR#laptop" + TIME=$(date -u +"%Y-%m-%dT%H-%M-%SZ") + + ERROR_FILE=$(mktemp) + + # snapshot current state + git -C "$FLAKE_DIR" add -A + git -C "$FLAKE_DIR" commit --allow-empty -m "snapshot pre-cleanup-$TIME" + git -C "$FLAKE_DIR" tag "pre-cleanup-$TIME" HEAD + + # removes dead code + deadnix --edit "$FLAKE_DIR" # removes unused code + statix fix "$FLAKE_DIR" # check other linting issues + alejandra "$FLAKE_DIR" # formats the config + + if sudo /run/current-system/sw/bin/nixos-rebuild switch --flake "$FLAKE" 2> "$ERROR_FILE"; then # use /run/.../bin/ uses the sudoless rule + + if ! git -C "$FLAKE_DIR" diff --quiet HEAD; then + git -C "$FLAKE_DIR" add -A + git -C "$FLAKE_DIR" commit -m "Auto: cleanup-$TIME" + git -C "$FLAKE_DIR" push + + notify-send "Nix auto cleanup" "Everything OK" + + matrix-commander-rs --verbose -m "Nix auto cleanup. Everything OK.
@notificationbot_0000" \ + --html \ + -r "\!7j-78_02dHROeLj4Ns8F12eo4IiZGv4zNsQ_1-WlyIU" + else + notify-send "Nix auto cleanup" "No changes" + git -C "$FLAKE_DIR" push + fi + + else + ERROR_MSG=$(cat "$ERROR_FILE") + + notify-send -u critical "Nix auto cleanup" "FAILED" + + matrix-commander-rs --verbose -m "Nix auto cleanup failed.
Error:
$ERROR_MSG

@notificationbot_0000" \ + --html \ + -r "\!7j-78_02dHROeLj4Ns8F12eo4IiZGv4zNsQ_1-WlyIU" + + git -C "$FLAKE_DIR" reset --hard "pre-cleanup-$TIME" + fi + git -C "$FLAKE_DIR" tag -d "pre-cleanup-$TIME" # removes the tag + + rm -f "$ERROR_FILE" + ''; +} diff --git a/modules/nixos/nixUtils.nix b/modules/nixos/nixUtils.nix index b0f61c2..bfb2cfa 100644 --- a/modules/nixos/nixUtils.nix +++ b/modules/nixos/nixUtils.nix @@ -1,5 +1,6 @@ # some options are in ../../hostsModules/laptop/nixos/nixUtils.nix { + pkgs, pkgs-unstable, inputs, ... @@ -29,5 +30,7 @@ alejandra vimPluginsUpdater # used for building plugins nix-index + statix + (pkgs.callPackage ../../hostsModules/laptop/scripts/cleanNix.nix {}) ]; }