#!/usr/bin/env python3 """Поиск файлов по регулярному выражению в имени или пути.""" from __future__ import annotations import argparse import json import os import re from pathlib import Path DEFAULT_EXCLUDES = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv"} def human_size(size: int) -> str: value = float(size) for unit in ("B", "KB", "MB", "GB", "TB"): if value < 1024 or unit == "TB": return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}" value /= 1024 return f"{size} B" 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("--pattern", required=True, help="Регулярное выражение для имени или пути") parser.add_argument("--ignore-case", action="store_true", help="Не учитывать регистр") parser.add_argument("--full-path", action="store_true", help="Искать по относительному пути, а не только по имени") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--json", type=Path, help="Сохранить результат в JSON") args = parser.parse_args() try: regex = re.compile(args.pattern, re.IGNORECASE if args.ignore_case else 0) except re.error as error: parser.error(f"Ошибка в регулярном выражении: {error}") 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()} matches = [] for path in iter_files(root, excludes): relative = path.relative_to(root) subject = str(relative) if args.full_path else path.name if not regex.search(subject): continue try: stat = path.stat() except OSError as error: print(f"Пропуск {path}: {error}") continue matches.append( { "path": str(relative), "size": stat.st_size, "modified": stat.st_mtime, } ) print(f"{human_size(stat.st_size):>10} {relative}") if not matches: print("Совпадений не найдено.") return 0 print(f"\nНайдено файлов: {len(matches)}") if args.json: output = args.json.expanduser() output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps({"root": str(root), "pattern": args.pattern, "files": matches}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Отчёт сохранён: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())