#!/usr/bin/env python3 """Отчёт о пользовательских каталогах, которые можно очистить.""" from __future__ import annotations import argparse import json import os import tempfile import time from pathlib import Path def candidate_locations() -> list[tuple[str, Path]]: home = Path.home() locations: list[tuple[str, Path]] = [("Временные файлы", Path(tempfile.gettempdir()))] if os.name == "nt": local = os.environ.get("LOCALAPPDATA") if local: locations.append(("Кэш интернета", Path(local) / "Microsoft" / "Windows" / "INetCache")) locations.append(("Загрузки", home / "Downloads")) else: locations.append(("Кэш пользователя", home / ".cache")) locations.append(("Загрузки", home / "Downloads")) if os.uname().sysname == "Darwin": locations.append(("Кэш macOS", home / "Library" / "Caches")) locations.append(("Корзина", home / ".Trash")) locations.append( ("Xcode DerivedData", home / "Library" / "Developer" / "Xcode" / "DerivedData") ) else: locations.append(("Корзина", home / ".local" / "share" / "Trash")) return locations def measure(root: Path, cutoff: float) -> tuple[int, int, int]: total = 0 stale = 0 files = 0 for current, dirnames, filenames in os.walk(root, followlinks=False): dirnames[:] = [ name for name in dirnames if not os.path.islink(os.path.join(current, name)) ] for name in filenames: path = Path(current) / name if path.is_symlink(): continue try: stat = path.stat() except OSError: continue total += stat.st_size files += 1 if stat.st_mtime <= cutoff: stale += stat.st_size return total, stale, files def main() -> int: parser = argparse.ArgumentParser(description="Отчёт о кандидатах на очистку") parser.add_argument("--days", type=int, default=90, help="Порог давности для старых данных") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() if args.days < 0: parser.error("--days не может быть отрицательным") cutoff = time.time() - args.days * 86400 rows = [] seen: set[Path] = set() for label, path in candidate_locations(): try: resolved = path.expanduser().resolve() except OSError: continue if resolved in seen or not resolved.is_dir(): continue seen.add(resolved) total, stale, files = measure(resolved, cutoff) rows.append( { "label": label, "path": str(resolved), "total_bytes": total, "stale_bytes": stale, "files": files, } ) rows.sort(key=lambda item: item["stale_bytes"], reverse=True) print(f"Кандидаты на очистку, старые данные старше {args.days} дней:") print(f"{'Категория':24} {'Всего':>10} {'Старое':>10} {'Файлов':>8}") for row in rows: print( f"{row['label']:24} {row['total_bytes'] / 1048576:10.1f} " f"{row['stale_bytes'] / 1048576:10.1f} {row['files']:8d}" ) print(f" {row['path']}") total_stale = sum(row["stale_bytes"] for row in rows) print(f"Потенциально освободится: {total_stale / 1048576:.1f} MB") print("Это только отчёт. Выбирайте очистку вручную и запускайте отдельные скрипты.") if args.json: payload = {"days": args.days, "locations": rows, "stale_bytes": total_stale} args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())