|
| 1 | +"""Changelog generation from conventional commits and git diffs.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import re |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +from rich.console import Console |
| 11 | + |
| 12 | +from gitmate import config as config_mod |
| 13 | +from gitmate.config import GitmateConfig, SecretStore |
| 14 | +from gitmate.diff_extractor import DiffExtractor, GitCommandError, GitRunner, SubprocessGitRunner |
| 15 | +from gitmate.fallback import generate_fallback_changelog |
| 16 | +from gitmate.orchestrator import GenerationResult, check_budget_cap, run_generation_pipeline |
| 17 | +from gitmate.providers.base import LLMProvider |
| 18 | +from gitmate.token_budget import TokenCounter |
| 19 | + |
| 20 | +logger = logging.getLogger("gitmate.changelog") |
| 21 | + |
| 22 | +CONVENTIONAL_PATTERN = re.compile( |
| 23 | + r"^(?P<type>[a-zA-Z]+)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?:\s*(?P<desc>.*)$" |
| 24 | +) |
| 25 | + |
| 26 | +CATEGORIES: list[str] = [ |
| 27 | + "Features", |
| 28 | + "Bug Fixes", |
| 29 | + "Performance & Refactoring", |
| 30 | + "Documentation", |
| 31 | + "Maintenance & Tooling", |
| 32 | + "Other Changes", |
| 33 | +] |
| 34 | + |
| 35 | +TYPE_TO_CATEGORY: dict[str, str] = { |
| 36 | + "feat": "Features", |
| 37 | + "fix": "Bug Fixes", |
| 38 | + "perf": "Performance & Refactoring", |
| 39 | + "refactor": "Performance & Refactoring", |
| 40 | + "docs": "Documentation", |
| 41 | + "chore": "Maintenance & Tooling", |
| 42 | + "build": "Maintenance & Tooling", |
| 43 | + "ci": "Maintenance & Tooling", |
| 44 | + "test": "Maintenance & Tooling", |
| 45 | + "style": "Maintenance & Tooling", |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | +@dataclass(frozen=True) |
| 50 | +class CommitLogEntry: |
| 51 | + """Parsed commit record with conventional commit metadata.""" |
| 52 | + |
| 53 | + commit_hash: str |
| 54 | + subject: str |
| 55 | + body: str |
| 56 | + author: str |
| 57 | + date: str |
| 58 | + commit_type: str | None = None |
| 59 | + scope: str | None = None |
| 60 | + description: str | None = None |
| 61 | + is_breaking: bool = False |
| 62 | + |
| 63 | + |
| 64 | +def parse_commit_message( |
| 65 | + commit_hash: str, |
| 66 | + subject: str, |
| 67 | + body: str = "", |
| 68 | + author: str = "", |
| 69 | + date: str = "", |
| 70 | +) -> CommitLogEntry: |
| 71 | + """Parse a single commit subject into conventional commit type, scope, and description.""" |
| 72 | + match = CONVENTIONAL_PATTERN.match(subject.strip()) |
| 73 | + if match: |
| 74 | + c_type = match.group("type").lower() |
| 75 | + scope = match.group("scope") |
| 76 | + desc = match.group("desc").strip() |
| 77 | + is_breaking = bool(match.group("breaking")) or ( |
| 78 | + "BREAKING CHANGE:" in body or "BREAKING-CHANGE:" in body |
| 79 | + ) |
| 80 | + return CommitLogEntry( |
| 81 | + commit_hash=commit_hash, |
| 82 | + subject=subject.strip(), |
| 83 | + body=body.strip(), |
| 84 | + author=author.strip(), |
| 85 | + date=date.strip(), |
| 86 | + commit_type=c_type, |
| 87 | + scope=scope, |
| 88 | + description=desc, |
| 89 | + is_breaking=is_breaking, |
| 90 | + ) |
| 91 | + |
| 92 | + is_breaking = "BREAKING CHANGE:" in body or "BREAKING-CHANGE:" in body |
| 93 | + return CommitLogEntry( |
| 94 | + commit_hash=commit_hash, |
| 95 | + subject=subject.strip(), |
| 96 | + body=body.strip(), |
| 97 | + author=author.strip(), |
| 98 | + date=date.strip(), |
| 99 | + commit_type=None, |
| 100 | + scope=None, |
| 101 | + description=subject.strip(), |
| 102 | + is_breaking=is_breaking, |
| 103 | + ) |
| 104 | + |
| 105 | + |
| 106 | +def extract_commits_between( |
| 107 | + from_ref: str, |
| 108 | + to_ref: str = "HEAD", |
| 109 | + runner: GitRunner | None = None, |
| 110 | + repo: Path | None = None, |
| 111 | +) -> list[CommitLogEntry]: |
| 112 | + """Retrieve and parse git commits in the revision range from_ref..to_ref.""" |
| 113 | + git_runner = runner if runner is not None else SubprocessGitRunner() |
| 114 | + repo_dir = repo if repo is not None else Path.cwd() |
| 115 | + |
| 116 | + # Use ASCII record separator \x1e between commits and \x00 between fields |
| 117 | + output = git_runner.run( |
| 118 | + ["log", f"{from_ref}..{to_ref}", "--format=%H%x00%s%x00%b%x00%an%x00%ad%x1e"], |
| 119 | + repo_dir, |
| 120 | + ) |
| 121 | + |
| 122 | + commits: list[CommitLogEntry] = [] |
| 123 | + records = output.split("\x1e") |
| 124 | + for rec in records: |
| 125 | + rec = rec.strip() |
| 126 | + if not rec: |
| 127 | + continue |
| 128 | + parts = rec.split("\x00") |
| 129 | + if len(parts) >= 5: |
| 130 | + commit_hash, subject, body, author, date = ( |
| 131 | + parts[0], |
| 132 | + parts[1], |
| 133 | + parts[2], |
| 134 | + parts[3], |
| 135 | + parts[4], |
| 136 | + ) |
| 137 | + commits.append( |
| 138 | + parse_commit_message( |
| 139 | + commit_hash=commit_hash, |
| 140 | + subject=subject, |
| 141 | + body=body, |
| 142 | + author=author, |
| 143 | + date=date, |
| 144 | + ) |
| 145 | + ) |
| 146 | + elif len(parts) >= 2: |
| 147 | + commits.append( |
| 148 | + parse_commit_message( |
| 149 | + commit_hash=parts[0], |
| 150 | + subject=parts[1], |
| 151 | + ) |
| 152 | + ) |
| 153 | + |
| 154 | + return commits |
| 155 | + |
| 156 | + |
| 157 | +def group_commits(commits: list[CommitLogEntry]) -> dict[str, list[CommitLogEntry]]: |
| 158 | + """Group commits into conventional categories with an explicit 'Other Changes' bucket.""" |
| 159 | + grouped: dict[str, list[CommitLogEntry]] = {cat: [] for cat in CATEGORIES} |
| 160 | + |
| 161 | + for c in commits: |
| 162 | + if c.commit_type and c.commit_type in TYPE_TO_CATEGORY: |
| 163 | + category = TYPE_TO_CATEGORY[c.commit_type] |
| 164 | + else: |
| 165 | + category = "Other Changes" |
| 166 | + grouped[category].append(c) |
| 167 | + |
| 168 | + return grouped |
| 169 | + |
| 170 | + |
| 171 | +def format_commits_for_prompt(grouped: dict[str, list[CommitLogEntry]]) -> str: |
| 172 | + """Format grouped commits into markdown sections for prompt template substitution.""" |
| 173 | + sections: list[str] = [] |
| 174 | + for category, items in grouped.items(): |
| 175 | + if not items: |
| 176 | + continue |
| 177 | + sections.append(f"### {category}") |
| 178 | + for item in items: |
| 179 | + scope_prefix = f"({item.scope}): " if item.scope else ": " |
| 180 | + t = item.commit_type or "other" |
| 181 | + breaking_marker = "!" if item.is_breaking else "" |
| 182 | + desc = item.description or item.subject |
| 183 | + sections.append(f"- [{item.commit_hash[:7]}] {t}{breaking_marker}{scope_prefix}{desc}") |
| 184 | + sections.append("") |
| 185 | + |
| 186 | + return "\n".join(sections).strip() |
| 187 | + |
| 188 | + |
| 189 | +def generate_changelog( |
| 190 | + from_ref: str, |
| 191 | + to_ref: str = "HEAD", |
| 192 | + include_diff: bool = False, |
| 193 | + output_file: Path | None = None, |
| 194 | + cfg: GitmateConfig | None = None, |
| 195 | + diff_extractor: DiffExtractor | None = None, |
| 196 | + git_runner: GitRunner | None = None, |
| 197 | + provider: LLMProvider | None = None, |
| 198 | + counter: TokenCounter | None = None, |
| 199 | + console: Console | None = None, |
| 200 | + secret_store: SecretStore | None = None, |
| 201 | + bypass_cache: bool = False, |
| 202 | + repo_dir: Path | None = None, |
| 203 | +) -> GenerationResult: |
| 204 | + """Generate structured release notes between two git references.""" |
| 205 | + con = console if console is not None else Console() |
| 206 | + active_cfg = cfg if cfg is not None else config_mod.load_config() |
| 207 | + |
| 208 | + check_budget_cap(active_cfg, console=con) |
| 209 | + |
| 210 | + repo_path = repo_dir if repo_dir is not None else Path.cwd() |
| 211 | + runner = git_runner if git_runner is not None else SubprocessGitRunner() |
| 212 | + |
| 213 | + commits = extract_commits_between(from_ref, to_ref, runner=runner, repo=repo_path) |
| 214 | + if not commits: |
| 215 | + return GenerationResult( |
| 216 | + text=f"No commits found between '{from_ref}' and '{to_ref}'.", |
| 217 | + is_fallback=False, |
| 218 | + model=active_cfg.model, |
| 219 | + ) |
| 220 | + |
| 221 | + extractor = ( |
| 222 | + diff_extractor |
| 223 | + if diff_extractor is not None |
| 224 | + else DiffExtractor(repo=repo_path, runner=runner) |
| 225 | + ) |
| 226 | + diffs = [] |
| 227 | + if include_diff: |
| 228 | + try: |
| 229 | + diffs = extractor.rev_range(from_ref, to_ref) |
| 230 | + except GitCommandError as exc: |
| 231 | + con.print( |
| 232 | + f"[yellow]warning: Could not extract diffs ({exc}), proceeding with commits only.[/yellow]" |
| 233 | + ) |
| 234 | + |
| 235 | + grouped = group_commits(commits) |
| 236 | + formatted_commits = format_commits_for_prompt(grouped) |
| 237 | + |
| 238 | + gen_result = run_generation_pipeline( |
| 239 | + diffs=diffs, |
| 240 | + cfg=active_cfg, |
| 241 | + template_name="changelog", |
| 242 | + fallback_generator=lambda: generate_fallback_changelog( |
| 243 | + commits, from_ref=from_ref, to_ref=to_ref |
| 244 | + ), |
| 245 | + template_vars={ |
| 246 | + "commits": formatted_commits, |
| 247 | + "from_ref": from_ref, |
| 248 | + "to_ref": to_ref, |
| 249 | + }, |
| 250 | + command="changelog", |
| 251 | + provider=provider, |
| 252 | + counter=counter, |
| 253 | + console=con, |
| 254 | + secret_store=secret_store, |
| 255 | + bypass_cache=bypass_cache, |
| 256 | + ) |
| 257 | + |
| 258 | + if output_file is not None: |
| 259 | + try: |
| 260 | + output_file.write_text(gen_result.text + "\n", encoding="utf-8") |
| 261 | + con.print(f"[green]✔ Changelog written to {output_file}[/green]") |
| 262 | + except OSError as exc: |
| 263 | + con.print(f"[red]error writing changelog file:[/red] {exc}") |
| 264 | + |
| 265 | + return gen_result |
0 commit comments