#!/usr/bin/env python3 """Состояние Time Machine и локальных снимков APFS.""" from __future__ import annotations import argparse import json import re import subprocess import sys from pathlib import Path STATUS_RE = re.compile(r"^\s*([A-Za-z0-9_]+)\s*=\s*(.+?);\s*$") def run(command: list[str]) -> tuple[int, str]: result = subprocess.run(command, capture_output=True, text=True, check=False) return result.returncode, (result.stdout or result.stderr).strip() def status_values() -> dict: _, output = run(["tmutil", "status"]) values = {} for line in output.splitlines(): match = STATUS_RE.match(line) if match: values[match.group(1)] = match.group(2) return values def main() -> int: parser = argparse.ArgumentParser(description="Time Machine и локальные снимки") parser.add_argument("--json", type=Path) parser.add_argument("--delete-date", help="Дата снимка в формате 2026-01-15-120000") parser.add_argument("--yes", action="store_true") args = parser.parse_args() code, destination = run(["tmutil", "destinationinfo"]) _, latest = run(["tmutil", "latestbackup"]) _, backups = run(["tmutil", "listbackups"]) _, snapshot_dates = run(["tmutil", "listlocalsnapshotdates", "/"]) snapshot_list = [line.strip() for line in snapshot_dates.splitlines() if line.strip()] report = { "status": status_values(), "destination": destination if code == 0 else "", "latest_backup": latest if latest and "No backups" not in latest else "", "backups": [line.strip() for line in backups.splitlines() if line.strip()], "local_snapshot_dates": snapshot_list, } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("Time Machine status:") if report["status"]: for key, value in report["status"].items(): print(f" {key}: {value}") else: print(" данные недоступны") print("\nНазначение:") print(f" {report['destination'] or 'не настроено'}") print(f"\nПоследняя копия: {report['latest_backup'] or 'нет'}") print(f"Копий в списке: {len(report['backups'])}") print(f"Локальных снимков: {len(snapshot_list)}") for date in snapshot_list: print(f" {date}") if not args.delete_date: return 0 if args.delete_date not in snapshot_list: print(f"Снимок не найден в списке: {args.delete_date}", file=sys.stderr) return 2 if not re.fullmatch(r"\d{4}-\d{2}-\d{2}-\d{6}", args.delete_date): print("Неверный формат даты.", file=sys.stderr) return 2 if not args.yes: answer = input(f"Удалить локальный снимок {args.delete_date}? [y/N]: ").strip().lower() if answer not in {"y", "yes", "д", "да"}: print("Отменено.") return 1 code, output = run(["tmutil", "deletelocalsnapshots", args.delete_date]) if code == 0: print(f"Снимок удалён: {args.delete_date}") return 0 print(f"Не удалось удалить снимок: {output}", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())