#!/usr/bin/env python3 """Сортировка и очистка снимков экрана macOS.""" from __future__ import annotations import argparse import json import shutil import subprocess import sys from datetime import datetime, timedelta from pathlib import Path def find_screenshots(source: Path) -> list[Path]: found: set[Path] = set() mdfind = shutil.which("mdfind") if mdfind: result = subprocess.run( [mdfind, "-onlyin", str(source), "kMDItemIsScreenCapture == 1"], capture_output=True, text=True, check=False, ) for line in result.stdout.splitlines(): path = Path(line) try: if path.is_file() and path.resolve().is_relative_to(source.resolve()): found.add(path) except OSError: continue if not found: patterns = ( "Screenshot*.png", "Screenshot*.jpg", "Screen Shot*.png", "Снимок экрана*.png", ) for pattern in patterns: found.update(path for path in source.glob(pattern) if path.is_file()) return sorted(found) def unique_target(target: Path) -> Path: if not target.exists(): return target for number in range(1, 1000): candidate = target.with_name(f"{target.stem}-{number}{target.suffix}") if not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {target}") def main() -> int: parser = argparse.ArgumentParser(description="Разложить снимки экрана по месяцам") parser.add_argument("--source", type=Path, default=Path.home() / "Desktop") parser.add_argument("--dest", type=Path, default=Path.home() / "Pictures" / "Screenshots") parser.add_argument("--older-than", type=int, default=0, metavar="ДНЕЙ") parser.add_argument("--trash", action="store_true", help="Отправить старые снимки в Корзину") parser.add_argument("--apply", action="store_true", help="Выполнить план") parser.add_argument("--yes", action="store_true", help="Не задавать вопросов") parser.add_argument("--json", type=Path, help="Сохранить план в JSON") args = parser.parse_args() source = args.source.expanduser().resolve() dest = args.dest.expanduser().resolve() if not source.is_dir(): parser.error(f"Папка не найдена: {source}") files = find_screenshots(source) cutoff = datetime.now() - timedelta(days=args.older_than) if args.older_than > 0 else None old_files: list[Path] = [] for path in files: try: changed = datetime.fromtimestamp(path.stat().st_mtime) except OSError: continue if cutoff and changed < cutoff: old_files.append(path) plan: list[dict[str, str]] = [] for path in files: if path in old_files and args.trash: plan.append({"action": "trash", "source": str(path), "target": ""}) continue try: stamp = datetime.fromtimestamp(path.stat().st_mtime) except OSError: continue target_dir = dest / f"{stamp.year:04d}" / f"{stamp.month:02d}" plan.append({"action": "move", "source": str(path), "target": str(target_dir / path.name)}) if args.json: args.json.write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") if not plan: print("Снимки экрана не найдены.") return 0 moves = sum(1 for item in plan if item["action"] == "move") trashes = sum(1 for item in plan if item["action"] == "trash") print(f"Найдено снимков: {len(files)}. Переместить: {moves}. В Корзину: {trashes}.") if not args.apply: for item in plan[:10]: target = item["target"] or "Корзина" print(f" {item['action']}: {item['source']} -> {target}") if len(plan) > 10: print(f" и ещё {len(plan) - 10}") print("Это предпросмотр. Добавьте --apply для выполнения.") return 0 if not args.yes: answer = input("Выполнить план? [y/N]: ").strip().lower() if answer not in {"y", "yes", "д", "да"}: print("Отменено.") return 1 trash = shutil.which("trash") if trashes and not trash: print("Для --trash установите утилиту trash: brew install trash", file=sys.stderr) return 2 errors = 0 for item in plan: source_path = Path(item["source"]) try: if item["action"] == "trash": result = subprocess.run([trash, str(source_path)], capture_output=True, text=True, check=False) if result.returncode: errors += 1 print(f"Не удалось отправить в Корзину {source_path}: {result.stderr.strip()}") else: target_path = unique_target(Path(item["target"])) target_path.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(source_path), str(target_path)) print(f"Перемещено: {source_path} -> {target_path}") except OSError as error: errors += 1 print(f"Ошибка для {source_path}: {error}") print(f"Готово. Ошибок: {errors}.") return 0 if errors == 0 else 1 if __name__ == "__main__": raise SystemExit(main())