#!/usr/bin/env python3 """Удаление выбранных файлов из zip через сборку новой копии.""" from __future__ import annotations import argparse import fnmatch import shutil import zipfile from pathlib import Path def matches(name: str, patterns: list[str]) -> bool: base = Path(name).name return any(fnmatch.fnmatch(name, pattern) or fnmatch.fnmatch(base, pattern) for pattern in patterns) def main() -> int: parser = argparse.ArgumentParser(description="Удалить файлы из zip") parser.add_argument("archive", type=Path, help="Исходный zip") parser.add_argument("patterns", nargs="+", help="Шаблоны имён") parser.add_argument("--output", type=Path, 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}.cleaned.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: removed = [info for info in source.infolist() if matches(info.filename, args.patterns)] kept = [info for info in source.infolist() if not matches(info.filename, args.patterns)] print(f"Исключить: {len(removed)}, оставить: {len(kept)}") for info in removed[:30]: print(f" - {info.filename}") if len(removed) > 30: print(f" и ещё {len(removed) - 30}") if not removed: print("Под шаблоны ничего не подошло.") 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 kept: 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())