Files
filwordspl-frontend/scripts/code_summary.py
T

270 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""
Code Summary — сводка по коду проекта Filwords PL.
Проходит по всем .py (backend) или .ts/.tsx (frontend) файлам,
вытаскивает docstring, функции, классы, импорты.
Формирует .md файл для быстрого ознакомления.
(22.09.2026) Первая версия. Без AI — только парсинг.
"""
from __future__ import annotations
import argparse
import ast
import re
import sys
from datetime import datetime
from pathlib import Path
# ============ Настройки ============
IGNORE_DIRS = {
"venv", ".venv", "__pycache__", ".git", ".gitea",
"node_modules", "dist", "build", ".vite", "coverage",
"archive", "uploads", "tts_cache", ".cache", "public",
}
# Большие файлы контента (не код) — пропускаем
IGNORE_FILES = {
"level_a1.py", "level_a2.py", "level_b1.py", "level_b2.py",
"level_c1.py", "level_c2.py",
}
# Максимальный размер файла для парсинга
MAX_FILE_SIZE = 100_000
# ============ Парсер Python ============
def parse_python(path: Path, repo_root: Path) -> dict | None:
"""Парсит один .py файл. Возвращает dict со сводкой или None."""
try:
content = path.read_text(encoding="utf-8")
except Exception as e:
print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr)
return None
if len(content) > MAX_FILE_SIZE:
return None
try:
tree = ast.parse(content)
except SyntaxError as e:
print(f"⚠️ Синтаксис {path}: {e}", file=sys.stderr)
return None
# Docstring модуля
module_doc = ast.get_docstring(tree) or ""
first_line = module_doc.strip().split("\n")[0] if module_doc else ""
# Функции и классы
functions: list[str] = []
classes: list[str] = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
args = [a.arg for a in node.args.args]
functions.append(f"{node.name}({', '.join(args)})")
elif isinstance(node, ast.ClassDef):
classes.append(node.name)
# Импорты
imports: list[str] = []
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name.split(".")[0])
elif isinstance(node, ast.ImportFrom):
if node.module:
imports.append(node.module.split(".")[0])
# Топ-3 импорта
imports = list(dict.fromkeys(imports))[:5]
rel = str(path.relative_to(repo_root)).replace("\\", "/")
return {
"path": rel,
"lang": "python",
"doc": first_line,
"functions": functions,
"classes": classes,
"imports": imports,
"lines": len(content.split("\n")),
}
# ============ Парсер TypeScript ============
def parse_typescript(path: Path, repo_root: Path) -> dict | None:
"""Парсит один .ts/.tsx файл. Возвращает dict со сводкой или None."""
try:
content = path.read_text(encoding="utf-8")
except Exception as e:
print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr)
return None
if len(content) > MAX_FILE_SIZE:
return None
# Docstring — первая многострочная /** ... */ или // в начале
doc_match = re.match(r'^(?:/\*\*(.*?)\*/|//\s*(.+?)$)', content, re.DOTALL | re.MULTILINE)
doc = ""
if doc_match:
doc = (doc_match.group(1) or doc_match.group(2) or "").strip()
doc = doc.split("\n")[0].strip().lstrip("*").strip()
# Функции (function name, const name = () =>)
funcs = re.findall(r'(?:export\s+)?(?:async\s+)?function\s+(\w+)', content)
funcs += re.findall(r'(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s+)?\(', content)
funcs = list(dict.fromkeys(funcs))[:15] # максимум 15
# Компоненты (const Name: React.FC)
components = re.findall(r'const\s+(\w+):\s*React\.FC', content)
components = list(dict.fromkeys(components))[:15]
# Импорты — топ-5
imports_raw = re.findall(r"from\s+['\"]([^'\"]+)['\"]", content)
imports_raw = [i for i in imports_raw if not i.startswith(".")][:5]
rel = str(path.relative_to(repo_root)).replace("\\", "/")
return {
"path": rel,
"lang": "typescript",
"doc": doc,
"functions": funcs,
"classes": components, # переиспользуем поле под компоненты
"imports": imports_raw,
"lines": len(content.split("\n")),
}
# ============ Обход файлов ============
def collect_files(repo_root: Path, mode: str) -> list[Path]:
"""Собирает файлы для парсинга."""
if mode == "backend":
extensions = {".py"}
else:
extensions = {".ts", ".tsx", ".js", ".jsx"}
files: list[Path] = []
for path in sorted(repo_root.rglob("*")):
if not path.is_file():
continue
if path.suffix not in extensions:
continue
if any(part in IGNORE_DIRS for part in path.relative_to(repo_root).parts):
continue
if path.name in IGNORE_FILES:
continue
files.append(path)
return files
# ============ Формирование сводки ============
def format_summary(items: list[dict], mode: str, repo_name: str) -> str:
"""Формирует markdown-сводку."""
lines: list[str] = []
date_str = datetime.now().strftime("%Y-%m-%d %H:%M")
lines.append(f"# 📋 Code Summary — {repo_name}")
lines.append("")
lines.append(f"**Дата:** {date_str}")
lines.append(f"**Режим:** {mode}")
lines.append(f"**Файлов:** {len(items)}")
lines.append("")
lines.append("---")
lines.append("")
for item in items:
lines.append(f"## `{item['path']}`")
lines.append("")
if item["doc"]:
lines.append(f"- **Назначение:** {item['doc']}")
else:
lines.append(f"- **Назначение:** _(docstring отсутствует)_")
if item["functions"]:
lines.append(f"- **Функции:** {', '.join(item['functions'][:20])}")
if len(item["functions"]) > 20:
lines.append(f" _(+{len(item['functions']) - 20} ещё)_")
if item["classes"]:
label = "Компоненты" if mode == "frontend" else "Классы"
lines.append(f"- **{label}:** {', '.join(item['classes'][:20])}")
if item["imports"]:
lines.append(f"- **Импорты:** {', '.join(item['imports'])}")
lines.append(f"- **Строк:** {item['lines']}")
lines.append("")
return "\n".join(lines)
# ============ Main ============
def main() -> None:
parser = argparse.ArgumentParser(description="Code Summary для Filwords PL")
parser.add_argument("mode", choices=["backend", "frontend"], help="Режим")
parser.add_argument(
"--path",
type=str,
default=None,
help="Путь к репозиторию (по умолчанию — текущая папка)",
)
parser.add_argument(
"--output",
type=str,
default=None,
help="Путь к выходному .md (по умолчанию — ~/Desktop/CODE_SUMMARY_*.md)",
)
args = parser.parse_args()
repo_root = Path(args.path).resolve() if args.path else Path(".").resolve()
if not repo_root.exists():
print(f"❌ Папка не найдена: {repo_root}", file=sys.stderr)
sys.exit(1)
print(f"📁 Репозиторий: {repo_root}")
print(f"🎯 Режим: {args.mode}")
files = collect_files(repo_root, args.mode)
print(f"📂 Найдено файлов: {len(files)}")
items: list[dict] = []
for f in files:
if args.mode == "backend":
result = parse_python(f, repo_root)
else:
result = parse_typescript(f, repo_root)
if result:
items.append(result)
print(f"✅ Обработано: {len(items)}")
repo_name = repo_root.name
summary = format_summary(items, args.mode, repo_name)
if args.output:
output_path = Path(args.output)
else:
date_str = datetime.now().strftime("%Y%m%d_%H%M")
output_path = Path.home() / "Desktop" / f"CODE_SUMMARY_{args.mode.upper()}_{date_str}.md"
output_path.write_text(summary, encoding="utf-8")
print(f"💾 Сохранено: {output_path}")
print(f"📊 Размер: {len(summary):,} символов")
if __name__ == "__main__":
main()