#!/usr/bin/env python3 """Генерация Markdown-changelog из conventional commits.""" from __future__ import annotations import argparse import re import shutil import subprocess from collections import OrderedDict from datetime import date from pathlib import Path CONVENTIONAL = re.compile(r"^(?P[A-Za-z]+)(?:\((?P[^)]+)\))?!?:\s*(?P.+)$") SECTIONS = OrderedDict( [ ("feat", "Новые возможности"), ("fix", "Исправления"), ("perf", "Производительность"), ("refactor", "Рефакторинг"), ("docs", "Документация"), ("test", "Тесты"), ("build", "Сборка"), ("ci", "CI"), ("chore", "Обслуживание"), ] ) def git(repo: Path, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( ["git", "-C", str(repo), *args], capture_output=True, text=True, encoding="utf-8", errors="replace", ) def main() -> int: parser = argparse.ArgumentParser(description="Собрать changelog из git log") parser.add_argument("--repo", default=".", help="Путь к репозиторию") parser.add_argument("--from", dest="start", help="Начальный тег или коммит") parser.add_argument("--to", default="HEAD", help="Конечный коммит") parser.add_argument("--version", help="Заголовок версии") parser.add_argument("--output", type=Path, help="Файл Markdown") parser.add_argument("--apply", action="store_true", help="Записать файл") parser.add_argument("--force", action="store_true", help="Перезаписать файл") args = parser.parse_args() if not shutil.which("git"): print("Не найден git.") return 2 repo = Path(args.repo).expanduser().resolve() if not repo.is_dir(): print(f"Папка не найдена: {repo}") return 2 if git(repo, "rev-parse", "--is-inside-work-tree").returncode != 0: print(f"Это не git-репозиторий: {repo}") return 2 start = args.start if not start: tag = git(repo, "describe", "--tags", "--abbrev=0") if tag.returncode == 0: start = tag.stdout.strip() log_args = [ "log", "--no-merges", "--date=short", "--pretty=format:%H%x1f%s%x1f%an%x1f%ad", ] if start: log_args.append(f"{start}..{args.to}") else: log_args.append(args.to) result = git(repo, *log_args) if result.returncode != 0: print(result.stderr.strip()) return 1 groups: dict[str, list[str]] = {key: [] for key in SECTIONS} groups["other"] = [] total = 0 for line in result.stdout.splitlines(): parts = line.split("\x1f") if len(parts) != 4: continue commit, subject, author, _ = parts total += 1 match = CONVENTIONAL.match(subject) if match: kind = match.group("type").lower() text = match.group("text").strip() scope = match.group("scope") if scope: text = f"**{scope}:** {text}" key = kind if kind in SECTIONS else "other" else: key = "other" text = subject.strip() groups[key].append(f"- {text} ({author}, {commit[:7]})") if total == 0: print("Коммитов для changelog не найдено.") return 0 title = args.version.strip() if args.version else "Не выпущено" lines = ["# История изменений", "", f"## {title} - {date.today().isoformat()}", ""] for key, heading in SECTIONS.items(): items = groups[key] if not items: continue lines.append(f"### {heading}") lines.extend(items) lines.append("") if groups["other"]: lines.append("### Прочее") lines.extend(groups["other"]) lines.append("") content = "\n".join(lines).rstrip() + "\n" if not args.output: print(content) return 0 target = args.output.expanduser() if target.exists() and not args.force: print(f"Файл уже существует: {target}. Добавьте --force для замены.") return 2 if not args.apply: print(content) print(f"Это предпросмотр. Для записи в {target} добавьте --apply.") return 0 if target.parent and not target.parent.exists(): print(f"Папка не найдена: {target.parent}") return 2 target.write_text(content, encoding="utf-8") print(f"Changelog записан: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())