#!/usr/bin/env python3 """Нормализация имён внутри zip.""" from __future__ import annotations import argparse import shutil import unicodedata import zipfile from pathlib import Path, PurePosixPath PAIRS = [ ("а", "a"), ("б", "b"), ("в", "v"), ("г", "g"), ("д", "d"), ("е", "e"), ("ё", "e"), ("ж", "zh"), ("з", "z"), ("и", "i"), ("й", "y"), ("к", "k"), ("л", "l"), ("м", "m"), ("н", "n"), ("о", "o"), ("п", "p"), ("р", "r"), ("с", "s"), ("т", "t"), ("у", "u"), ("ф", "f"), ("х", "kh"), ("ц", "ts"), ("ч", "ch"), ("ш", "sh"), ("щ", "shch"), ("ъ", ""), ("ы", "y"), ("ь", ""), ("э", "e"), ("ю", "yu"), ("я", "ya"), ] TRANSLIT = {} for lower, latin in PAIRS: TRANSLIT[lower] = latin TRANSLIT[lower.upper()] = latin.capitalize() TRANSLIT["№"] = "N" TRANSLIT_TABLE = str.maketrans(TRANSLIT) INVALID = set('<>:"|?*') def normalize_segment(segment: str, ascii_only: bool, lower: bool) -> str: segment = unicodedata.normalize("NFC", segment) if ascii_only: segment = segment.translate(TRANSLIT_TABLE) cleaned = [] for char in segment: if char in INVALID or ord(char) < 32: cleaned.append("_") else: cleaned.append(char) result = "".join(cleaned).rstrip(" .") if not result: result = "_" if lower: result = result.lower() return result def normalize_name(name: str, ascii_only: bool, lower: bool) -> str: normalized = name.replace("\\", "/") path = PurePosixPath(normalized) parts = [part for part in path.parts if part not in ("", ".")] if any(part == ".." for part in parts): raise ValueError(f"небезопасный путь: {name}") result = "/".join(normalize_segment(part, ascii_only, lower) for part in parts) if name.endswith("/") and result: result += "/" return result def with_suffix(name: str, number: int) -> str: path = PurePosixPath(name) suffix = "".join(path.suffixes) stem = path.name[: -len(suffix)] if suffix else path.name new_name = f"{stem}-{number}{suffix}" return new_name if str(path.parent) == "." else f"{path.parent}/{new_name}" def main() -> int: parser = argparse.ArgumentParser(description="Нормализовать имена в zip") parser.add_argument("archive", type=Path, help="Исходный zip") parser.add_argument("--output", type=Path, help="Новый архив") parser.add_argument("--ascii", action="store_true", help="Транслитерировать кириллицу") parser.add_argument("--lower", action="store_true", 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}.normalized.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() mapping: dict[str, str] = {} used: set[str] = set() for info in infos: try: candidate = normalize_name(info.filename, args.ascii, args.lower) except ValueError as error: print(f"Пропуск: {error}") continue if not candidate: continue key = candidate.lower() counter = 2 unique = candidate while key in used: unique = with_suffix(candidate, counter) key = unique.lower() counter += 1 used.add(key) mapping[info.filename] = unique changed = [(old, new) for old, new in mapping.items() if old != new] print(f"Элементов: {len(infos)}, изменятся имена: {len(changed)}") for old, new in changed[:100]: print(f" {old} -> {new}") if len(changed) > 100: print(f" и ещё {len(changed) - 100}") if not changed: 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: new_name = mapping.get(info.filename) if new_name is None: continue new_info = zipfile.ZipInfo(new_name, info.date_time) new_info.compress_type = info.compress_type new_info.external_attr = info.external_attr 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())