#!/usr/bin/env python3 """Статическая проверка requirements-файлов Python.""" from __future__ import annotations import argparse import json import re import subprocess import sys from collections import defaultdict from pathlib import Path NAME_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]+\])?\s*(.*)$") def normalize(name: str) -> str: return re.sub(r"[-_.]+", "-", name).lower() def parse_file(path: Path) -> list[dict[str, str]]: result = [] try: lines = path.read_text(encoding="utf-8", errors="replace").splitlines() except OSError: return result for raw in lines: line = raw.split("#", 1)[0].strip() if not line or line.startswith("-"): continue marker = "" if ";" in line: line, marker = line.split(";", 1) marker = marker.strip() line = line.strip() if "@" in line: name = line.split("@", 1)[0].strip() spec = "@ " + line.split("@", 1)[1].strip() else: match = NAME_RE.match(line) if not match: continue name = match.group(1) spec = (match.group(3) or "").strip() result.append( { "name": name, "normalized": normalize(name), "spec": spec, "marker": marker, "file": str(path), } ) return result def main() -> int: parser = argparse.ArgumentParser(description="Проверить зависимости Python") parser.add_argument("--path", type=Path, default=Path("."), help="Папка проекта") parser.add_argument("--online", action="store_true", help="Запросить pip list --outdated") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.is_dir(): print(f"Папка не найдена: {root}") return 2 files = sorted(root.glob("requirements*.txt")) + sorted(root.glob("constraints*.txt")) if not files: print("Requirements-файлы не найдены.") return 0 packages = [] for path in files: packages.extend(parse_file(path)) by_name: dict[str, list[dict[str, str]]] = defaultdict(list) for item in packages: by_name[item["normalized"]].append(item) duplicates = { name: items for name, items in by_name.items() if len(items) > 1 } unpinned = [ item for item in packages if "==" not in item["spec"] and "@" not in item["spec"] ] wildcards = [item for item in packages if "==" in item["spec"] and "*" in item["spec"]] print(f"Файлов: {len(files)}, строк с пакетами: {len(packages)}, уникальных: {len(by_name)}") print() if duplicates: print("Дубликаты пакетов:") for name, items in sorted(duplicates.items()): print(f" {name}:") for item in items: print(f" {item['file']}: {item['spec'] or 'без версии'}") print() if unpinned: print(f"Без точной версии: {len(unpinned)}") for item in unpinned[:30]: print(f" {item['name']} {item['spec'] or '(нет)'} {item['file']}") print() if wildcards: print(f"Версии с шаблоном: {len(wildcards)}") for item in wildcards[:20]: print(f" {item['name']} {item['spec']}") print() online = [] if args.online: result = subprocess.run( [sys.executable, "-m", "pip", "list", "--outdated", "--format=json"], capture_output=True, text=True, encoding="utf-8", errors="replace", ) if result.returncode == 0: try: data = json.loads(result.stdout or "[]") except json.JSONDecodeError: data = [] wanted = set(by_name) online = [ item for item in data if normalize(str(item.get("name", ""))) in wanted ] print(f"Устаревших пакетов из requirements: {len(online)}") for item in online[:30]: print(f" {item.get('name')}: {item.get('version')} -> {item.get('latest_version')}") else: print("Не удалось получить pip list --outdated.") print() if args.json: payload = { "root": str(root), "packages": packages, "duplicates": duplicates, "unpinned": unpinned, "wildcards": wildcards, "outdated": online, } args.json.write_text( json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) if not duplicates and not unpinned and not wildcards: print("Явных проблем в requirements не найдено.") return 0 if __name__ == "__main__": raise SystemExit(main())