#!/usr/bin/env python3 """Копирование файлов из дерева в одну плоскую папку.""" from __future__ import annotations import argparse import os import shutil from pathlib import Path DEFAULT_EXCLUDES = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv"} def iter_files(root: Path, excludes: set[str]): for current, dirs, names in os.walk(root): current_path = Path(current) dirs[:] = [ name for name in dirs if name not in excludes and not (current_path / name).is_symlink() ] for name in names: path = current_path / name if path.is_file() and not path.is_symlink(): yield path def unique_path(destination: Path, name: str, reserved: set[Path]) -> Path: candidate = destination / name if candidate not in reserved and not candidate.exists(): return candidate stem = Path(name).stem suffix = Path(name).suffix for index in range(2, 10000): candidate = destination / f"{stem}_{index}{suffix}" if candidate not in reserved and not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {name}") def main() -> int: parser = argparse.ArgumentParser(description="Скопировать файлы в одну папку") parser.add_argument("--src", type=Path, required=True, help="Исходная папка") parser.add_argument("--dst", type=Path, required=True, help="Плоская папка назначения") parser.add_argument("--ext", action="append", default=[], help="Копировать только эти расширения") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--apply", action="store_true", help="Выполнить копирование") args = parser.parse_args() source = args.src.expanduser().resolve() destination = args.dst.expanduser().resolve() if not source.is_dir(): parser.error(f"Исходная папка не найдена: {source}") if destination == source or source in destination.parents: parser.error("Папка назначения не должна находиться внутри исходной") extensions = { (part.strip() if part.strip().startswith(".") else "." + part.strip()).lower() for value in args.ext for part in value.split(",") if part.strip() } excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()} files = list(iter_files(source, excludes)) if extensions: files = [path for path in files if path.suffix.lower() in extensions] if not files: print("Нет файлов для копирования.") return 0 reserved: set[Path] = set() plan = [] for path in files: target = unique_path(destination, path.name, reserved) reserved.add(target) plan.append((path, target)) for path, target in plan: print(f"{path.relative_to(source)} -> {target.name}") if not args.apply: print(f"\nПредпросмотр: {len(plan)} файлов. Для копирования добавьте --apply.") return 0 destination.mkdir(parents=True, exist_ok=True) copied = 0 failed = 0 for path, target in plan: try: shutil.copy2(path, target) copied += 1 except OSError as error: failed += 1 print(f"Ошибка {path}: {error}") print(f"\nСкопировано: {copied}, ошибок: {failed}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())