move garbage collect logic to nix module

This commit is contained in:
2025-06-30 23:05:43 +02:00
parent 581a63a196
commit eda9b91af4
2 changed files with 10 additions and 24 deletions

View File

@ -164,12 +164,20 @@
nix = {
settings.experimental-features = ["nix-command" "flakes"]; # Enable modern Nix features (flakes and new CLI)
# Optimise the Nix store automatically to recover space
optimise = {
# Optimise the Nix store automatically to recover space
automatic = true;
dates = ["03:45"]; # Optional; allows customizing optimisation schedule
dates = ["03:45"];
persistent = true; # Run missed optimisations
};
# Garbage collect the Nix store automatically to recover space
gc = {
automatic = true;
dates = "weekly";
options = "--delete-older-than 60d";
persistent = true; # Run missed GC
};
};
# ================================

View File

@ -2,13 +2,6 @@
set -e
# Days of nix generations to keep
KEEP_DAYS=60
# extra buffer before we trigger a GC
BUFFER_DAYS=30
# minimum number of generations to keep
KEEP_MIN=5
# Check for force flag
FORCE_REBUILD=false
if [[ "$1" == "-f" || "$1" == "--force" ]]; then
@ -67,18 +60,3 @@ current=$(nixos-rebuild list-generations | grep current)
# Commit all changes witih the generation metadata
git commit -am "$NIXOS_HOST: $current"
# Clean up old generations if conditions are met
gens=$(nixos-rebuild list-generations | tail -n +2)
# If there are less than KEEP_MIN generations, exit
(( $(wc -l <<<"$gens") <= KEEP_MIN )) && exit 0
# Get the oldest generation
old=$(awk 'END{print $2" "$3}' <<<"$gens")
# Calculate the age of the oldest generation in days
age=$(( ( $(date +%s) - $(date -d "$old" +%s) )/86400 ))
# If the age is greater than KEEP_DAYS+BUFFER_DAYS, delete the oldest generation
(( age > KEEP_DAYS+BUFFER_DAYS )) || exit 0
sudo nix-collect-garbage --delete-older-than ${KEEP_DAYS}d &>logs/nixos-gc.log || (cat logs/nixos-gc.log | grep --color error && exit 1)