#!/usr/bin/env python3 """Извлечение одного файла из zip или tar.""" from __future__ import annotations import argparse import fnmatch import shutil import tarfile import zipfile from pathlib import Path, PurePosixPath, PureWindowsPath def safe_parts(name: str) -> tuple[str, ...]: normalized = name.replace("\\", "/") path = PurePosixPath(normalized) if path.is_absolute() or PureWindowsPath(normalized).drive: raise ValueError(f"абсолютный путь: {name}") parts = tuple(part for part in path.parts if part not in ("", ".")) if not parts or any(part == ".." for part in parts): raise ValueError(f"небезопасный путь: {name}") return parts def matches(name: str, pattern: str, use_glob: bool) -> bool: if not use_glob: return name == pattern return fnmatch.fnmatch(name, pattern) or fnmatch.fnmatch(Path(name).name, pattern) def target_for(name: str, destination: Path, flatten: bool) -> Path: if flatten: parts = (Path(name.replace("\\", "/")).name,) else: parts = safe_parts(name) target = destination.joinpath(*parts) if not target.resolve().is_relative_to(destination.resolve()): raise ValueError(f"путь вне папки: {name}") return target def main() -> int: parser = argparse.ArgumentParser(description="Извлечь один файл из архива") parser.add_argument("archive", type=Path, help="Zip или tar архив") parser.add_argument("member", help="Точное имя или маска") parser.add_argument("--dest", type=Path, default=Path("."), help="Папка назначения") parser.add_argument("--glob", action="store_true", help="Считать member маской") parser.add_argument("--all", action="store_true", help="Извлечь все совпадения") parser.add_argument("--flatten", action="store_true", help="Сохранить только имена файлов") parser.add_argument("--force", action="store_true", help="Перезаписать существующие файлы") parser.add_argument("--dry-run", action="store_true", help="Только показать совпадения") args = parser.parse_args() archive_path = args.archive.expanduser().resolve() destination = args.dest.expanduser().resolve() if not archive_path.is_file(): parser.error(f"Архив не найден: {archive_path}") names: list[str] = [] if zipfile.is_zipfile(archive_path): with zipfile.ZipFile(archive_path) as archive: names = [info.filename for info in archive.infolist() if not info.is_dir()] elif tarfile.is_tarfile(archive_path): with tarfile.open(archive_path, mode="r:*") as archive: names = [member.name for member in archive.getmembers() if member.isfile()] else: print("Формат не распознан. Поддерживаются zip и tar.") return 2 found = [name for name in names if matches(name, args.member, args.glob)] if not found: print("Совпадений нет. Проверьте имя через список содержимого архива.") return 1 if len(found) > 1 and not args.all: print(f"Найдено совпадений: {len(found)}. Уточните имя или добавьте --all:") for name in found[:20]: print(f" {name}") return 1 plan: list[tuple[str, Path]] = [] for name in found: try: plan.append((name, target_for(name, destination, args.flatten))) except ValueError as error: print(f"Ошибка: {error}") return 2 existing = [str(target) for _, target in plan if target.exists() and not args.force] if existing: print("Файлы уже существуют, добавьте --force:") for name in existing: print(f" {name}") return 1 if args.dry_run: for name, target in plan: print(f"{name} -> {target}") print("Режим проверки: ничего не записано.") return 0 destination.mkdir(parents=True, exist_ok=True) if zipfile.is_zipfile(archive_path): with zipfile.ZipFile(archive_path) as archive: for name, target in plan: target.parent.mkdir(parents=True, exist_ok=True) with archive.open(name) as source, target.open("wb") as handle: shutil.copyfileobj(source, handle) else: with tarfile.open(archive_path, mode="r:*") as archive: for name, target in plan: source = archive.extractfile(name) if source is None: print(f"Не удалось прочитать: {name}") continue target.parent.mkdir(parents=True, exist_ok=True) with source, target.open("wb") as handle: shutil.copyfileobj(source, handle) print(f"Извлечено файлов: {len(plan)} в {destination}") return 0 if __name__ == "__main__": raise SystemExit(main())