#!/usr/bin/env python3 """Поиск файлов с одинаковыми именами в разных каталогах.""" from __future__ import annotations import argparse import json import os from collections import defaultdict 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, files 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 files: path = current_path / name if path.is_symlink() or not path.is_file(): continue yield path def main() -> int: parser = argparse.ArgumentParser(description="Найти файлы с одинаковыми именами") parser.add_argument("--dir", type=Path, default=Path("."), help="Папка для поиска") parser.add_argument("--min-count", type=int, default=2, help="Минимальное число файлов в группе") parser.add_argument("--case-sensitive", action="store_true", help="Учитывать регистр имени") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--json", type=Path, help="Сохранить результат в JSON") args = parser.parse_args() if args.min_count < 2: parser.error("--min-count должен быть не меньше 2") root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()} groups: dict[str, list[Path]] = defaultdict(list) for path in iter_files(root, excludes): key = path.name if args.case_sensitive else path.name.lower() groups[key].append(path) found = [] for key, paths in groups.items(): if len(paths) < args.min_count: continue found.append( { "name": paths[0].name, "key": key, "count": len(paths), "files": [str(path.relative_to(root)) for path in sorted(paths)], } ) if not found: print("Одинаковые имена не найдены.") return 0 found.sort(key=lambda item: (-item["count"], item["key"])) for group in found: print(f"\n{group['name']} - {group['count']} файлов") for relative in group["files"]: print(f" {relative}") print(f"\nГрупп: {len(found)}") if args.json: output = args.json.expanduser() output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps({"root": str(root), "groups": found}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Отчёт сохранён: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())