#!/usr/bin/env python3 """Упаковка папки в zip с исключениями.""" from __future__ import annotations import argparse import fnmatch import zipfile from pathlib import Path def is_excluded(relative: str, patterns: list[str]) -> bool: name = Path(relative).name return any( fnmatch.fnmatch(relative, pattern) or fnmatch.fnmatch(name, pattern) for pattern in patterns ) def main() -> int: parser = argparse.ArgumentParser(description="Упаковать папку в zip") parser.add_argument("source", type=Path, help="Папка-источник") parser.add_argument("output", type=Path, help="Имя zip-файла") parser.add_argument("--exclude", action="append", default=[], help="Шаблон исключения, можно повторить") parser.add_argument("--level", type=int, choices=range(0, 10), default=6, help="Уровень сжатия 0-9") parser.add_argument("--force", action="store_true", help="Перезаписать существующий архив") parser.add_argument("--dry-run", action="store_true", help="Только показать файлы") args = parser.parse_args() source = args.source.expanduser().resolve() output = args.output.expanduser().resolve() if not source.is_dir(): parser.error(f"Папка не найдена: {source}") if output.exists() and not args.force: parser.error(f"Файл уже существует: {output}. Используйте --force") if source == output: parser.error("Архив не может совпадать с папкой") files: list[tuple[Path, str]] = [] for path in sorted(source.rglob("*")): if not path.is_file() or path.is_symlink(): continue relative = path.relative_to(source).as_posix() if is_excluded(relative, args.exclude): continue if path.resolve() == output: continue files.append((path, relative)) if not files: print("Нечего упаковывать: подходящих файлов нет.") return 1 total = sum(path.stat().st_size for path, _ in files) print(f"Файлов: {len(files)}, исходный размер: {total / 1024 / 1024:.1f} МБ") if args.dry_run: for _, relative in files: print(f" {relative}") print("Режим проверки: архив не создан.") return 0 output.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=args.level) as archive: for path, relative in files: archive.write(path, arcname=relative) print(f"Готово: {output} ({output.stat().st_size / 1024 / 1024:.1f} МБ)") return 0 if __name__ == "__main__": raise SystemExit(main())