#!/usr/bin/env python3 """Нормализация имён файлов и каталогов.""" from __future__ import annotations import argparse import os import re import sys import unicodedata from pathlib import Path RESERVED = {"con", "prn", "aux", "nul"} RESERVED |= {f"com{index}" for index in range(1, 10)} RESERVED |= {f"lpt{index}" for index in range(1, 10)} INVALID = re.compile(r"[^\w.\- ]", re.UNICODE) SPACES = re.compile(r"[\s_]+") def split_name(name: str) -> tuple[str, str, int]: leading = len(name) - len(name.lstrip(".")) if leading >= len(name): return "", "", 0 core = name[leading:] suffix = Path(core).suffix stem = core[: -len(suffix)] if suffix else core return stem, suffix, leading def normalize_name(name: str) -> str: stem, suffix, leading = split_name(name) text = unicodedata.normalize("NFKC", stem).lower() text = INVALID.sub("", text) text = SPACES.sub("_", text).strip("._- ") if not text: text = "file" if text in RESERVED: text = "_" + text suffix = INVALID.sub("", unicodedata.normalize("NFKC", suffix)).lower() return "." * leading + text + suffix def unique_path(path: Path, reserved: set[Path]) -> Path: if path not in reserved and not path.exists(): return path for index in range(2, 10000): candidate = path.with_name(f"{path.stem}_{index}{path.suffix}") if candidate not in reserved and not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {path}") def collect(root: Path, recursive: bool, include_dirs: bool) -> tuple[list[Path], list[Path]]: files: list[Path] = [] directories: list[Path] = [] if recursive: for current, dirs, names in os.walk(root): current_path = Path(current) dirs[:] = [name for name in dirs if not (current_path / name).is_symlink()] for name in names: path = current_path / name if path.is_file() and not path.is_symlink(): files.append(path) if include_dirs: directories.extend(current_path / name for name in dirs) else: for path in root.iterdir(): if path.is_symlink(): continue if path.is_file(): files.append(path) elif include_dirs and path.is_dir(): directories.append(path) return files, directories def main() -> int: parser = argparse.ArgumentParser(description="Нормализовать имена файлов") parser.add_argument("--dir", type=Path, required=True, help="Папка с файлами") parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки") parser.add_argument("--dirs", action="store_true", help="Переименовывать также каталоги") parser.add_argument("--apply", action="store_true", help="Выполнить переименование") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") files, directories = collect(root, args.recursive, args.dirs) reserved: set[Path] = set() plan: list[tuple[Path, Path]] = [] for source in files: new_name = normalize_name(source.name) if new_name == source.name: continue destination = unique_path(source.with_name(new_name), reserved) reserved.add(destination) plan.append((source, destination)) dir_plan: list[tuple[Path, Path]] = [] for source in sorted(directories, key=lambda item: len(item.parts), reverse=True): new_name = normalize_name(source.name) if new_name == source.name: continue destination = unique_path(source.with_name(new_name), reserved) reserved.add(destination) dir_plan.append((source, destination)) if not plan and not dir_plan: print("Имена уже нормализованы.") return 0 for source, destination in plan + dir_plan: print(f"{source.relative_to(root)} -> {destination.name}") if not args.apply: print(f"\nПредпросмотр: {len(plan) + len(dir_plan)} переименований. Для применения добавьте --apply.") return 0 renamed = 0 failed = 0 for source, destination in plan + dir_plan: try: source.rename(destination) renamed += 1 except OSError as error: failed += 1 print(f"Ошибка {source}: {error}", file=sys.stderr) print(f"\nПереименовано: {renamed}, ошибок: {failed}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())