"""Bash: a backup retention pruner (keep-daily/weekly/monthly/within) split across prune.sh and lib/{calendar,dates,backups,policy}.sh. calendar.sh's is_leap prints 1 or 0 for arithmetic, but dates.sh's day_number tests it as `[ "$(is_leap "$y")" ]`, which is true for "0" too, so every year gets a February 29th: March-December dates of common years land one day late. Only a keep-within window that crosses the end of February in a common year shows it (a 7-day-old archive is dropped); leap-year windows, same-month windows and the Jan/Feb weekly fixtures come out right. The tempting patches (a looser age bound in policy.sh, is_leap printing nothing for common years, dropping the leap-day adjustment) each fix that test but break the boundary, helper or leap-year tests. Runs on macOS /bin/bash 3.2 and Linux bash 5.""" import re ITEM_ID = "sh-backup-retention" LANG = "sh" TOOL = "bash" PROJECT = { "prune.sh": r'''#!/bin/bash # prune.sh: thin out one job's NAME-YYYY-MM-DD[_HHMM].tar.gz archives in a backup directory. # # prune.sh [-n] [-d DAILY] [-w WEEKLY] [-m MONTHLY] [-k DAYS] DIR NAME # # -n dry run: print the plan, delete nothing # -d -w -m keep the newest archive of each of the N most recent days / ISO weeks / # calendar months that have archives # -k DAYS keep every archive dated at most DAYS days before the newest one # # Prints the plan ("keep FILE RULES" / "drop FILE", newest first), then deletes the dropped # archives unless -n is given. Runs on bash 3.2 (macOS) and later. here=$(cd "$(dirname "$0")" && pwd) . "$here/lib/calendar.sh" . "$here/lib/dates.sh" . "$here/lib/backups.sh" . "$here/lib/policy.sh" usage() { echo "usage: prune.sh [-n] [-d DAILY] [-w WEEKLY] [-m MONTHLY] [-k DAYS] DIR NAME" >&2 exit 2 } dry_run=0 daily=0 weekly=0 monthly=0 within=-1 while getopts nd:w:m:k: opt; do case $opt in n) dry_run=1 ;; d) daily=$OPTARG ;; w) weekly=$OPTARG ;; m) monthly=$OPTARG ;; k) within=$OPTARG ;; *) usage ;; esac done shift $((OPTIND - 1)) [ "$#" -eq 2 ] || usage dir=$1 name=$2 [ -d "$dir" ] || { echo "prune: no such directory: $dir" >&2; exit 2; } for n in "$daily" "$weekly" "$monthly"; do case $n in "" | *[!0-9]*) echo "prune: -d/-w/-m take a whole number" >&2; exit 2 ;; esac done case $within in -1) ;; "" | *[!0-9]*) echo "prune: -k takes a whole number of days" >&2; exit 2 ;; esac if [ "$daily" -eq 0 ] && [ "$weekly" -eq 0 ] && [ "$monthly" -eq 0 ] && [ "$within" -lt 0 ]; then echo "prune: no retention rule given; refusing to drop every archive" >&2 exit 2 fi plan=$(list_backups "$dir" "$name" | plan_retention "$daily" "$weekly" "$monthly" "$within") [ -n "$plan" ] || exit 0 echo "$plan" [ "$dry_run" -eq 0 ] || exit 0 echo "$plan" | while read -r verdict file rules; do if [ "$verdict" = drop ]; then rm -f -- "$dir/$file" fi done ''', "lib/calendar.sh": r'''# calendar.sh: Gregorian calendar facts. Years, months and days are plain decimal numbers. # is_leap Y: prints 1 when Y is a leap year and 0 when it is not, for use in arithmetic # such as $((365 + $(is_leap 2024))). It always succeeds. is_leap() { if [ $(($1 % 4)) -eq 0 ] && { [ $(($1 % 100)) -ne 0 ] || [ $(($1 % 400)) -eq 0 ]; }; then echo 1 else echo 0 fi } # days_in_month Y M: prints the number of days in month M (1-12) of year Y. days_in_month() { case $2 in 2) echo $((28 + $(is_leap "$1"))) ;; 4 | 6 | 9 | 11) echo 30 ;; *) echo 31 ;; esac } # valid_date Y M D: succeeds when Y-M-D exists on the calendar. valid_date() { [ "$#" -eq 3 ] || return 1 [ "$2" -ge 1 ] && [ "$2" -le 12 ] || return 1 [ "$3" -ge 1 ] && [ "$3" -le "$(days_in_month "$1" "$2")" ] } ''', "lib/dates.sh": r'''# dates.sh: date arithmetic without GNU or BSD date(1), so it behaves the same everywhere. # Needs calendar.sh. # split_date YYYY-MM-DD: prints "Y M D" as plain decimals (zero padding removed). split_date() { local y=${1%%-*} rest=${1#*-} local m=${rest%%-*} d=${rest#*-} echo "$((10#$y)) $((10#$m)) $((10#$d))" } # day_number Y M D: prints the number of days from 1970-01-01 (day 0) to Y-M-D. day_number() { local y=$1 m=$2 d=$3 p=$(($1 - 1)) n # whole years since 1970, plus the leap days in years 1970..Y-1 # (477 = leap years from year 1 through 1969) n=$(((y - 1970) * 365 + p / 4 - p / 100 + p / 400 - 477)) # days in the months before M, in a common year set -- 0 31 59 90 120 151 181 212 243 273 304 334 shift $((m - 1)) n=$((n + $1 + d - 1)) # Y's own February 29th, once it is behind us if [ "$m" -gt 2 ] && [ "$(is_leap "$y")" ]; then n=$((n + 1)) fi echo "$n" } # weekday Y M D: prints 1 (Monday) .. 7 (Sunday). 1970-01-01 was a Thursday. weekday() { echo $((($(day_number "$1" "$2" "$3") + 3) % 7 + 1)) } # iso_week Y M D: prints the ISO 8601 week, e.g. 2026-W07. Weeks start on Monday and belong # to the year that holds their Thursday, so early January can fall in the previous year's # last week and late December in week 01 of the next year. iso_week() { local y=$1 n thu n=$(day_number "$1" "$2" "$3") thu=$((n - $(weekday "$1" "$2" "$3") + 4)) if [ "$thu" -lt "$(day_number "$y" 1 1)" ]; then y=$((y - 1)) elif [ "$thu" -ge "$(day_number $((y + 1)) 1 1)" ]; then y=$((y + 1)) fi printf '%04d-W%02d\n' "$y" $(((thu - $(day_number "$y" 1 1)) / 7 + 1)) } ''', "lib/backups.sh": r'''# backups.sh: find the backup archives of one job. Needs calendar.sh and dates.sh. # list_backups DIR NAME: prints "STAMP FILE" for each NAME-YYYY-MM-DD.tar.gz or # NAME-YYYY-MM-DD_HHMM.tar.gz in DIR, newest first. STAMP is the part between "NAME-" and # ".tar.gz"; an archive without a time sorts before every timed one of the same day. # Archives named after a date that does not exist are skipped with a warning on stderr; # anything else in DIR is ignored. list_backups() { local dir=$1 name=$2 path file stamp for path in "$dir/$name"-*.tar.gz; do [ -f "$path" ] || continue file=${path##*/} stamp=${file#"$name"-} stamp=${stamp%.tar.gz} case $stamp in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;; [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9][0-9][0-9]) ;; *) continue ;; esac if ! valid_date $(split_date "${stamp%%_*}"); then echo "prune: skipping $file: no such date" >&2 continue fi echo "$stamp $file" done | LC_ALL=C sort -r } ''', "lib/policy.sh": r'''# policy.sh: decide which backups a retention policy keeps. Needs dates.sh. # plan_retention DAILY WEEKLY MONTHLY WITHIN # stdin: "STAMP FILE" lines, newest first, as list_backups prints them # stdout: "keep FILE RULES" or "drop FILE" for each input line, in the same order # # A backup is kept by rule "daily" when it is the newest backup of one of the DAILY most # recent days that have backups; "weekly" and "monthly" do the same for ISO weeks and # calendar months. Rule "within" keeps every backup whose date is at most WITHIN days # before the newest backup's date (ages are whole calendar days; WITHIN=0 keeps all of the # newest day). A count of 0 turns its rule off, and so does a negative WITHIN. RULES lists # every rule that kept the file, comma-separated. plan_retention() { local daily=$1 weekly=$2 monthly=$3 within=$4 local stamp file date y m d why key age newest="" local last_day="" last_week="" last_month="" days=0 weeks=0 months=0 while read -r stamp file; do [ -n "$file" ] || continue date=${stamp%%_*} set -- $(split_date "$date") y=$1 m=$2 d=$3 why="" if [ "$date" != "$last_day" ]; then last_day=$date if [ "$days" -lt "$daily" ]; then days=$((days + 1)); why="$why,daily"; fi fi key=$(iso_week "$y" "$m" "$d") if [ "$key" != "$last_week" ]; then last_week=$key if [ "$weeks" -lt "$weekly" ]; then weeks=$((weeks + 1)); why="$why,weekly"; fi fi key=${date%-*} if [ "$key" != "$last_month" ]; then last_month=$key if [ "$months" -lt "$monthly" ]; then months=$((months + 1)); why="$why,monthly"; fi fi key=$(day_number "$y" "$m" "$d") [ -n "$newest" ] || newest=$key age=$((newest - key)) if [ "$within" -ge 0 ] && [ "$age" -le "$within" ]; then why="$why,within"; fi if [ -n "$why" ]; then echo "keep $file ${why#,}" else echo "drop $file" fi done } ''', "tests/run.sh": r'''#!/bin/bash # tests/run.sh: runs every test_* function below in its own mktemp -d work dir. Prints # "PASS name" or "FAIL name" (a failure is followed by a diff of expected vs. actual) and # exits 1 if any test failed. root=$(cd "$(dirname "$0")/.." && pwd) . "$root/lib/calendar.sh" . "$root/lib/dates.sh" failed=0 prune() { "$BASH" "$root/prune.sh" "$@"; } # mk FILE...: empty archives in the work dir mk() { local f for f in "$@"; do : >"$work/$f"; done } # check EXPECTED ACTUAL check() { if [ "$1" = "$2" ]; then echo "PASS $current" else echo "FAIL $current" printf '%s\n' "$1" >"$work/.expected" printf '%s\n' "$2" >"$work/.actual" diff "$work/.expected" "$work/.actual" | sed 's/^/ /' failed=1 fi } test_calendar_helpers() { check "1 0 0 1 / 29 28 30 / yes no" \ "$(is_leap 2024) $(is_leap 2026) $(is_leap 1900) $(is_leap 2000) / $(days_in_month 2024 2) $(days_in_month 2026 2) $(days_in_month 2026 4) / $(valid_date 2024 2 29 && echo yes || echo no) $(valid_date 2026 2 29 && echo yes || echo no)" } test_day_numbers() { check "0 11017 19782 18630" \ "$(day_number 1970 1 1) $(day_number 2000 3 1) $(day_number 2024 2 29) $(day_number 2021 1 3)" } test_iso_weeks() { check "2026-W01 2020-W53 2024-W52 2025-W01 2026-W07" \ "$(iso_week 2026 1 1) $(iso_week 2021 1 3) $(iso_week 2024 12 29) $(iso_week 2024 12 30) $(iso_week 2026 2 15)" } test_daily_newest_per_day() { mk db-2026-10-12_0300.tar.gz db-2026-10-12_1500.tar.gz db-2026-10-11_0300.tar.gz \ db-2026-10-10.tar.gz db-2026-10-09_0300.tar.gz check "keep db-2026-10-12_1500.tar.gz daily drop db-2026-10-12_0300.tar.gz keep db-2026-10-11_0300.tar.gz daily keep db-2026-10-10.tar.gz daily drop db-2026-10-09_0300.tar.gz" "$(prune -n -d 3 "$work" db)" } test_weekly_iso_weeks() { mk web-2026-02-15.tar.gz web-2026-02-10.tar.gz web-2026-02-09.tar.gz \ web-2026-02-08.tar.gz web-2026-02-02.tar.gz web-2026-02-01.tar.gz check "keep web-2026-02-15.tar.gz weekly drop web-2026-02-10.tar.gz drop web-2026-02-09.tar.gz keep web-2026-02-08.tar.gz weekly drop web-2026-02-02.tar.gz drop web-2026-02-01.tar.gz" "$(prune -n -w 2 "$work" web)" } test_monthly_and_daily() { mk db-2026-10-01.tar.gz db-2026-09-30_2300.tar.gz db-2026-09-30_0100.tar.gz \ db-2026-09-15.tar.gz db-2026-08-31.tar.gz db-2026-07-04.tar.gz check "keep db-2026-10-01.tar.gz daily,monthly keep db-2026-09-30_2300.tar.gz monthly drop db-2026-09-30_0100.tar.gz drop db-2026-09-15.tar.gz keep db-2026-08-31.tar.gz monthly drop db-2026-07-04.tar.gz" "$(prune -n -d 1 -m 3 "$work" db)" } test_within_edge_inclusive() { mk app-2026-10-12.tar.gz app-2026-10-08.tar.gz app-2026-10-05.tar.gz \ app-2026-10-04.tar.gz app-2026-09-28.tar.gz check "keep app-2026-10-12.tar.gz within keep app-2026-10-08.tar.gz within keep app-2026-10-05.tar.gz within drop app-2026-10-04.tar.gz drop app-2026-09-28.tar.gz" "$(prune -n -k 7 "$work" app)" } test_within_db_nightlies() { mk db-2024-03-02.tar.gz db-2024-03-01.tar.gz db-2024-02-29.tar.gz \ db-2024-02-28.tar.gz db-2024-02-27.tar.gz check "keep db-2024-03-02.tar.gz daily,within keep db-2024-03-01.tar.gz within keep db-2024-02-29.tar.gz within keep db-2024-02-28.tar.gz within drop db-2024-02-27.tar.gz" "$(prune -n -d 1 -k 3 "$work" db)" } test_within_web_nightlies() { mk web-2026-03-03.tar.gz web-2026-03-01.tar.gz web-2026-02-26.tar.gz \ web-2026-02-24.tar.gz web-2026-02-23.tar.gz check "keep web-2026-03-03.tar.gz daily,within keep web-2026-03-01.tar.gz within keep web-2026-02-26.tar.gz within keep web-2026-02-24.tar.gz within drop web-2026-02-23.tar.gz" "$(prune -n -d 1 -k 7 "$work" web)" } test_skips_impossible_dates() { mk db-2026-03-01_0300.tar.gz db-2024-02-29.tar.gz db-2026-02-29.tar.gz \ db-2026-13-01.tar.gz db-latest.tar.gz notes.txt check "keep db-2026-03-01_0300.tar.gz daily keep db-2024-02-29.tar.gz daily skipped 2" "$(prune -n -d 5 "$work" db 2>"$work/.stderr") skipped $(grep -c 'no such date' "$work/.stderr")" } test_prune_deletes_dropped() { mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz db-2026-10-10.tar.gz db-2026-10-09.tar.gz \ other-2026-10-01.tar.gz prune -d 2 "$work" db >/dev/null check "db-2026-10-11.tar.gz db-2026-10-12.tar.gz other-2026-10-01.tar.gz" \ "$(cd "$work" && LC_ALL=C ls | tr '\n' ' ' | sed 's/ $//')" } test_dry_run_deletes_nothing() { mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz db-2026-10-10.tar.gz prune -n -d 1 "$work" db >/dev/null check "3" "$(cd "$work" && ls | wc -l | tr -d ' ')" } test_refuses_without_rules() { mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz prune "$work" db 2>/dev/null local rc=$? check "status 2, 2 left" "status $rc, $(cd "$work" && ls | wc -l | tr -d ' ') left" } for t in $(declare -F | sed -n 's/^declare -f test_//p'); do current=$t work=$(mktemp -d "${TMPDIR:-/tmp}/prune-test.XXXXXX") || exit 2 "test_$t" rm -f "$work"/* "$work"/.[!.]* rmdir "$work" done exit "$failed" ''', } def _patched(path, *pairs): """{path: PROJECT[path] with each (old, new) pair replaced once}; fails loudly if an `old` is not there exactly once.""" src = PROJECT[path] for old, new in pairs: assert src.count(old) == 1, (path, old) src = src.replace(old, new) return {path: src} HIDDEN = ("tests/run.sh",) FIX = _patched("lib/dates.sh", ('[ "$(is_leap "$y")" ]', '[ "$(is_leap "$y")" -eq 1 ]')) TEST_CMD = ["bash", "tests/run.sh"] PASS_RE = r"^PASS (\S+)$" TESTS = tuple(re.findall(r"^test_(\w+)\(\) \{", PROJECT["tests/run.sh"], re.M)) WRONG = [ # one more day of slack at the symptom site _patched("lib/policy.sh", ('[ "$age" -le "$within" ]', '[ "$age" -le $((within + 1)) ]')), # is_leap prints nothing for common years, so dates.sh's [ "$(is_leap ...)" ] reads it right _patched("lib/calendar.sh", (" echo 1\n else\n echo 0\n fi\n", " echo 1\n fi\n"), (' 2) echo $((28 + $(is_leap "$1"))) ;;\n', ' 2) if [ "$(is_leap "$1")" ]; then echo 29; else echo 28; fi ;;\n')), # no leap-day adjustment in day_number at all _patched("lib/dates.sh", (' # Y\'s own February 29th, once it is behind us\n' ' if [ "$m" -gt 2 ] && [ "$(is_leap "$y")" ]; then\n' ' n=$((n + 1))\n' ' fi\n', "")), ]