Enhance backup scripts with error handling and directory checks

This commit is contained in:
2026-03-04 14:55:43 -05:00
parent c93dcb5daf
commit cbcb6f02a5
5 changed files with 113 additions and 19 deletions

View File

@@ -62,15 +62,41 @@ for path, _, _, age_days, preserve_latest in files:
to_delete.add(path)
deleted = 0
failed = 0
considered = 0
for path in sorted(to_delete):
considered += 1
try:
os.remove(path)
print(path)
deleted += 1
except OSError:
pass
except OSError as exc:
print(f"ERROR deleting {path}: {exc}", file=sys.stderr)
failed += 1
print(f"Retention complete for {base} (deleted {deleted} files)")
# Remove now-empty directories except anything under a latest/ subtree.
removed_dirs = 0
for root, dirs, _ in os.walk(base, topdown=False):
parts = set(os.path.normpath(root).split(os.sep))
if "latest" in parts:
continue
if os.path.normpath(root) == os.path.normpath(base):
continue
for d in list(dirs):
dir_path = os.path.join(root, d)
if "latest" in set(os.path.normpath(dir_path).split(os.sep)):
continue
try:
if not os.listdir(dir_path):
os.rmdir(dir_path)
removed_dirs += 1
except OSError:
pass
print(f"Retention complete for {base} (considered {considered}, deleted {deleted}, removed_empty_dirs {removed_dirs})")
if failed:
print(f"Retention encountered {failed} delete errors", file=sys.stderr)
sys.exit(1)
PY
echo "Policy: daily <= ${KEEP_DAILY_DAYS}d, weekly <= ${KEEP_WEEKLY_DAYS}d"