#!/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"} SIZE_RE = re.compile(r"^\s*(\d+(?:[.,]\d+)?)\s*([kmgt]?i?b?)?\s*$", re.IGNORECASE) UNITS = { "": 1, "b": 1, "k": 1024, "kb": 1024, "kib": 1024, "m": 1024 ** 2, "mb": 1024 ** 2, "mib": 1024 ** 2, "g": 1024 ** 3, "gb": 1024 ** 3, "gib": 1024 ** 3, "t": 1024 ** 4, "tb": 1024 ** 4, "tib": 1024 ** 4, } def parse_size(text: str) -> int: match = SIZE_RE.match(text) if not match: raise argparse.ArgumentTypeError(f"Неверный размер: {text}") number = float(match.group(1).replace(",", ".")) unit = (match.group(2) or "").lower() return int(number * UNITS[unit]) 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("--min", type=parse_size, default=0, help="Минимальный размер, например 10MB") parser.add_argument("--max", type=parse_size, default=None, help="Максимальный размер, например 2GB") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--json", type=Path, help="Сохранить результат в JSON") args = parser.parse_args() if args.max is not None and args.min > args.max: parser.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): try: size = path.stat().st_size except OSError as error: print(f"Пропуск {path}: {error}") continue if size < args.min: continue if args.max is not None and size > args.max: continue matches.append({"path": str(path.relative_to(root)), "size": size}) if not matches: print("Файлы с таким размером не найдены.") return 0 matches.sort(key=lambda item: item["size"], reverse=True) for item in matches: print(f"{human_size(item['size']):>10} {item['path']}") total = sum(item["size"] for item in matches) print(f"\nНайдено файлов: {len(matches)}, суммарный размер: {human_size(total)}") if args.json: output = args.json.expanduser() output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps({"root": str(root), "files": matches}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Отчёт сохранён: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())