#!/usr/bin/env python3 """Копирование музыкальной библиотеки с контролем версий файлов.""" from __future__ import annotations import argparse import hashlib import json import os import shutil import sys import time from pathlib import Path AUDIO_EXTENSIONS = { ".mp3", ".flac", ".wav", ".m4a", ".aac", ".ogg", ".opus", ".wma", ".aiff", ".alac", } 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 unique_path(path: Path) -> Path: if not path.exists(): return path for index in range(1, 10000): candidate = path.with_name(f"{path.stem}-{index}{path.suffix}") if not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {path}") def main() -> int: parser = argparse.ArgumentParser(description="Копия музыкальной библиотеки") parser.add_argument("--source", type=Path, required=True) parser.add_argument("--dest", type=Path, required=True) parser.add_argument("--apply", action="store_true", help="Выполнить копирование") 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("Источник и назначение не должны вкладываться друг в друга") planned = 0 copied = 0 skipped = 0 errors = 0 entries = [] for current, dirs, files in os.walk(source): dirs[:] = sorted(name for name in dirs if not Path(current, name).is_symlink()) for name in sorted(files): path = Path(current, name) if path.suffix.lower() not in AUDIO_EXTENSIONS: continue if path.is_symlink() or not path.is_file(): continue planned += 1 relative = path.relative_to(source) target = dest / relative try: if target.is_file(): if target.stat().st_size == path.stat().st_size: if file_digest(target) == file_digest(path): skipped += 1 continue target = unique_path(target) if not args.apply: print(f"Будет скопировано: {relative}") continue target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) copied += 1 entries.append( { "source": relative.as_posix(), "target": str(target), "size": target.stat().st_size, "sha256": file_digest(target), } ) except OSError as error: errors += 1 print(f"Ошибка {relative}: {error}") if args.apply: dest.mkdir(parents=True, exist_ok=True) timestamp = time.strftime("%Y%m%d-%H%M%S") manifest_path = unique_path(dest / f"music-manifest-{timestamp}.json") manifest_path.write_text( json.dumps({"files": entries}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Manifest: {manifest_path}") else: print("Предпросмотр. Для копирования добавьте --apply.") print(f"Аудиофайлов: {planned}, скопировано: {copied}, без изменений: {skipped}, ошибок: {errors}") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())