#!/usr/bin/env python3 """Удаление дубликатов внутри zip.""" from __future__ import annotations import argparse import hashlib import shutil import zipfile from pathlib import Path def digest(archive: zipfile.ZipFile, info: zipfile.ZipInfo) -> str: value = hashlib.sha256() with archive.open(info) as handle: while chunk := handle.read(1024 * 1024): value.update(chunk) return value.hexdigest() def main() -> int: parser = argparse.ArgumentParser(description="Убрать дубликаты из архива") parser.add_argument("archive", type=Path, help="Исходный zip") parser.add_argument("--output", type=Path, help="Новый архив") parser.add_argument("--keep", choices=["first", "last"], default="first", help="Какое вхождение оставить") parser.add_argument("--min-size", type=int, default=1, help="Минимальный размер файла") parser.add_argument("--apply", action="store_true", help="Создать новый архив") parser.add_argument("--force", action="store_true", help="Перезаписать новый архив") args = parser.parse_args() source_path = args.archive.expanduser().resolve() if not source_path.is_file(): parser.error(f"Архив не найден: {source_path}") output = (args.output or source_path.with_name(f"{source_path.stem}.dedup.zip")).expanduser().resolve() if output == source_path: parser.error("Новый архив должен отличаться от исходного") if output.exists() and not args.force: parser.error(f"Файл уже существует: {output}. Используйте --force") with zipfile.ZipFile(source_path) as source: infos = source.infolist() groups: dict[tuple[int, str], list[zipfile.ZipInfo]] = {} failed = [] for info in infos: if info.is_dir() or info.file_size < args.min_size: continue if info.flag_bits & 0x1: failed.append(info.filename) continue try: key = (info.file_size, digest(source, info)) except (RuntimeError, zipfile.BadZipFile) as error: failed.append(f"{info.filename}: {error}") continue groups.setdefault(key, []).append(info) drop_names = set() duplicate_groups = 0 saved = 0 for (size, value), items in groups.items(): if len(items) < 2: continue duplicate_groups += 1 keep = items[0] if args.keep == "first" else items[-1] for info in items: if info is not keep: drop_names.add(info.filename) saved += size print(f"Дубликаты по {size} байт:") for info in items: mark = "оставить" if info is keep else "убрать" print(f" {mark}: {info.filename}") print(f"Групп дубликатов: {duplicate_groups}, файлов к удалению: {len(drop_names)}, экономия: {saved} байт") for name in failed: print(f"Пропуск: {name}") if not drop_names: return 0 if not args.apply: print("Режим проверки: добавьте --apply для создания новой копии.") return 0 with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as target: for info in infos: if info.filename in drop_names: continue new_info = zipfile.ZipInfo(info.filename, info.date_time) new_info.compress_type = info.compress_type new_info.external_attr = info.external_attr new_info.comment = info.comment if info.is_dir(): target.writestr(new_info, b"") continue with source.open(info) as src, target.open(new_info, "w") as dst: shutil.copyfileobj(src, dst) print(f"Готово: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())