#!/usr/bin/env python3 """Копирование домашней папки в отдельный каталог с отчётом.""" from __future__ import annotations import argparse import hashlib import os import shutil import sys import time from pathlib import Path DEFAULT_EXCLUDES = { ".cache", ".npm", ".cargo/registry", ".local/share/Trash", "node_modules", ".venv", "venv", "__pycache__", } def is_inside(child: Path, parent: Path) -> bool: try: child.relative_to(parent) return True except ValueError: return False def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(chunk_size): digest.update(block) return digest.hexdigest() def main() -> int: parser = argparse.ArgumentParser(description="Копия домашней папки") parser.add_argument("--source", type=Path, default=Path.home(), help="Исходная папка") parser.add_argument("--dest", type=Path, required=True, help="Корень для бэкапов") parser.add_argument("--exclude", action="append", default=[], help="Дополнительное имя для пропуска") parser.add_argument("--apply", action="store_true", help="Выполнить копирование") parser.add_argument("--hash", action="store_true", help="Записать manifest SHA-256") args = parser.parse_args() source = args.source.expanduser().resolve() dest = args.dest.expanduser().resolve() if not source.is_dir(): parser.error(f"Источник не найден: {source}") if source == dest: parser.error("Источник и назначение совпадают") if is_inside(dest, source) or is_inside(source, dest): parser.error("Источник и назначение не должны вкладываться друг в друга") timestamp = time.strftime("%Y%m%d-%H%M%S") target = dest / f"home-{timestamp}" if target.exists(): parser.error(f"Каталог уже существует: {target}") excludes = DEFAULT_EXCLUDES | set(args.exclude) planned = 0 copied = 0 skipped = 0 errors = 0 total_bytes = 0 manifest_lines: list[str] = [] for current, dirnames, filenames in os.walk(source): current_path = Path(current) relative_dir = current_path.relative_to(source) dirnames[:] = sorted( name for name in dirnames if name not in excludes and (relative_dir / name).as_posix() not in excludes ) for name in sorted(filenames): path = current_path / name relative = path.relative_to(source) if path.is_symlink() or not path.is_file(): skipped += 1 continue try: total_bytes += path.stat().st_size except OSError: skipped += 1 continue planned += 1 if not args.apply: if planned <= 20: print(f"Будет скопировано: {relative}") continue try: target_path = target / relative target_path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target_path) copied += 1 if args.hash: manifest_lines.append(f"{file_digest(target_path)} {relative.as_posix()}") except OSError as error: errors += 1 print(f"Ошибка {relative}: {error}") if not args.apply: print(f"Файлов к копированию: {planned}, пропущено: {skipped}, размер: {total_bytes} байт") print("Предпросмотр. Для копирования добавьте --apply.") return 0 target.mkdir(parents=True, exist_ok=True) if args.hash: manifest_path = target / "manifest.sha256" manifest_path.write_text("\n".join(manifest_lines) + "\n", encoding="utf-8") print(f"Manifest: {manifest_path}") print(f"Скопировано: {copied}, пропущено: {skipped}, ошибок: {errors}") print(f"Каталог: {target}") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())