|
| 1 | +"""Changelog generation from conventional commits and git diffs.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import re |
| 7 | +import time |
| 8 | +from dataclasses import dataclass |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +from rich.console import Console |
| 12 | + |
| 13 | +from gitmate import config as config_mod |
| 14 | +from gitmate.config import GitmateConfig, SecretStore |
| 15 | +from gitmate.diff_extractor import DiffExtractor, GitCommandError, GitRunner, SubprocessGitRunner |
| 16 | +from gitmate.fallback import generate_fallback_changelog |
| 17 | +from gitmate.metrics import get_monthly_spend, record_invocation |
| 18 | +from gitmate.orchestrator import GenerationResult, run_generation_pipeline |
| 19 | +from gitmate.providers.base import LLMProvider |
| 20 | +from gitmate.token_budget import TokenCounter |
| 21 | + |
| 22 | +logger = logging.getLogger("gitmate.changelog") |
| 23 | + |
| 24 | +CONVENTIONAL_PATTERN = re.compile( |
| 25 | + r"^(?P<type>[a-zA-Z]+)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?:\s*(?P<desc>.*)$" |
| 26 | +) |
| 27 | + |
| 28 | +CATEGORIES: list[str] = [ |
| 29 | + "Features", |
| 30 | + "Bug Fixes", |
| 31 | + "Performance & Refactoring", |
| 32 | + "Documentation", |
| 33 | + "Maintenance & Tooling", |
| 34 | + "Other Changes", |
| 35 | +] |
| 36 | + |
| 37 | +TYPE_TO_CATEGORY: dict[str, str] = { |
| 38 | + "feat": "Features", |
| 39 | + "fix": "Bug Fixes", |
| 40 | + "perf": "Performance & Refactoring", |
| 41 | + "refactor": "Performance & Refactoring", |
| 42 | + "docs": "Documentation", |
| 43 | + "chore": "Maintenance & Tooling", |
| 44 | + "build": "Maintenance & Tooling", |
| 45 | + "ci": "Maintenance & Tooling", |
| 46 | + "test": "Maintenance & Tooling", |
| 47 | + "style": "Maintenance & Tooling", |
| 48 | +} |
| 49 | + |
| 50 | + |
| 51 | +@dataclass(frozen=True) |
| 52 | +class CommitLogEntry: |
| 53 | + """Parsed commit record with conventional commit metadata.""" |
| 54 | + |
| 55 | + commit_hash: str |
| 56 | + subject: str |
| 57 | + body: str |
| 58 | + author: str |
| 59 | + date: str |
| 60 | + commit_type: str | None = None |
| 61 | + scope: str | None = None |
| 62 | + description: str | None = None |
| 63 | + |
| 64 | + |
| 65 | +def parse_commit_message( |
| 66 | + commit_hash: str, |
| 67 | + subject: str, |
| 68 | + body: str = "", |
| 69 | + author: str = "", |
| 70 | + date: str = "", |
| 71 | +) -> CommitLogEntry: |
| 72 | + """Parse a single commit subject into conventional commit type, scope, and description.""" |
| 73 | + match = CONVENTIONAL_PATTERN.match(subject.strip()) |
| 74 | + if match: |
| 75 | + c_type = match.group("type").lower() |
| 76 | + scope = match.group("scope") |
| 77 | + desc = match.group("desc").strip() |
| 78 | + return CommitLogEntry( |
| 79 | + commit_hash=commit_hash, |
| 80 | + subject=subject.strip(), |
| 81 | + body=body.strip(), |
| 82 | + author=author.strip(), |
| 83 | + date=date.strip(), |
| 84 | + commit_type=c_type, |
| 85 | + scope=scope, |
| 86 | + description=desc, |
| 87 | + ) |
| 88 | + |
| 89 | + return CommitLogEntry( |
| 90 | + commit_hash=commit_hash, |
| 91 | + subject=subject.strip(), |
| 92 | + body=body.strip(), |
| 93 | + author=author.strip(), |
| 94 | + date=date.strip(), |
| 95 | + commit_type=None, |
| 96 | + scope=None, |
| 97 | + description=subject.strip(), |
| 98 | + ) |
| 99 | + |
| 100 | + |
| 101 | +def extract_commits_between( |
| 102 | + from_ref: str, |
| 103 | + to_ref: str = "HEAD", |
| 104 | + runner: GitRunner | None = None, |
| 105 | + repo: Path | None = None, |
| 106 | +) -> list[CommitLogEntry]: |
| 107 | + """Retrieve and parse git commits in the revision range from_ref..to_ref.""" |
| 108 | + git_runner = runner if runner is not None else SubprocessGitRunner() |
| 109 | + repo_dir = repo if repo is not None else Path.cwd() |
| 110 | + |
| 111 | + # Use ASCII record separator \x1e between commits and \x00 between fields |
| 112 | + output = git_runner.run( |
| 113 | + ["log", f"{from_ref}..{to_ref}", "--format=%H%x00%s%x00%b%x00%an%x00%ad%x1e"], |
| 114 | + repo_dir, |
| 115 | + ) |
| 116 | + |
| 117 | + commits: list[CommitLogEntry] = [] |
| 118 | + records = output.split("\x1e") |
| 119 | + for rec in records: |
| 120 | + rec = rec.strip() |
| 121 | + if not rec: |
| 122 | + continue |
| 123 | + parts = rec.split("\x00") |
| 124 | + if len(parts) >= 5: |
| 125 | + commit_hash, subject, body, author, date = ( |
| 126 | + parts[0], |
| 127 | + parts[1], |
| 128 | + parts[2], |
| 129 | + parts[3], |
| 130 | + parts[4], |
| 131 | + ) |
| 132 | + commits.append( |
| 133 | + parse_commit_message( |
| 134 | + commit_hash=commit_hash, |
| 135 | + subject=subject, |
| 136 | + body=body, |
| 137 | + author=author, |
| 138 | + date=date, |
| 139 | + ) |
| 140 | + ) |
| 141 | + elif len(parts) >= 2: |
| 142 | + commits.append( |
| 143 | + parse_commit_message( |
| 144 | + commit_hash=parts[0], |
| 145 | + subject=parts[1], |
| 146 | + ) |
| 147 | + ) |
| 148 | + |
| 149 | + return commits |
| 150 | + |
| 151 | + |
| 152 | +def group_commits(commits: list[CommitLogEntry]) -> dict[str, list[CommitLogEntry]]: |
| 153 | + """Group commits into conventional categories with an explicit 'Other Changes' bucket.""" |
| 154 | + grouped: dict[str, list[CommitLogEntry]] = {cat: [] for cat in CATEGORIES} |
| 155 | + |
| 156 | + for c in commits: |
| 157 | + if c.commit_type and c.commit_type in TYPE_TO_CATEGORY: |
| 158 | + category = TYPE_TO_CATEGORY[c.commit_type] |
| 159 | + else: |
| 160 | + category = "Other Changes" |
| 161 | + grouped[category].append(c) |
| 162 | + |
| 163 | + return grouped |
| 164 | + |
| 165 | + |
| 166 | +def format_commits_for_prompt(grouped: dict[str, list[CommitLogEntry]]) -> str: |
| 167 | + """Format grouped commits into markdown sections for prompt template substitution.""" |
| 168 | + sections: list[str] = [] |
| 169 | + for category, items in grouped.items(): |
| 170 | + if not items: |
| 171 | + continue |
| 172 | + sections.append(f"### {category}") |
| 173 | + for item in items: |
| 174 | + scope_prefix = f"({item.scope}): " if item.scope else ": " |
| 175 | + t = item.commit_type or "other" |
| 176 | + desc = item.description or item.subject |
| 177 | + sections.append(f"- [{item.commit_hash[:7]}] {t}{scope_prefix}{desc}") |
| 178 | + sections.append("") |
| 179 | + |
| 180 | + return "\n".join(sections).strip() |
| 181 | + |
| 182 | + |
| 183 | +def _safe_record_telemetry( |
| 184 | + command: str, |
| 185 | + model: str, |
| 186 | + tokens_in: int | None, |
| 187 | + tokens_out: int | None, |
| 188 | + cache_hit: bool, |
| 189 | + latency_ms: int | None, |
| 190 | + fallback_used: bool, |
| 191 | + estimated_cost_usd: float | None = None, |
| 192 | + free_tier: bool = False, |
| 193 | +) -> None: |
| 194 | + """Record invocation to metrics database without propagating errors.""" |
| 195 | + try: |
| 196 | + record_invocation( |
| 197 | + command=command, |
| 198 | + model=model, |
| 199 | + tokens_in=tokens_in, |
| 200 | + tokens_out=tokens_out, |
| 201 | + cache_hit=cache_hit, |
| 202 | + latency_ms=latency_ms, |
| 203 | + fallback_used=fallback_used, |
| 204 | + estimated_cost_usd=estimated_cost_usd, |
| 205 | + free_tier=free_tier, |
| 206 | + ) |
| 207 | + except Exception as exc: # noqa: BLE001 |
| 208 | + logger.warning("Failed to record telemetry: %s", exc) |
| 209 | + |
| 210 | + |
| 211 | +def generate_changelog( |
| 212 | + from_ref: str, |
| 213 | + to_ref: str = "HEAD", |
| 214 | + include_diff: bool = False, |
| 215 | + output_file: Path | None = None, |
| 216 | + cfg: GitmateConfig | None = None, |
| 217 | + diff_extractor: DiffExtractor | None = None, |
| 218 | + git_runner: GitRunner | None = None, |
| 219 | + provider: LLMProvider | None = None, |
| 220 | + counter: TokenCounter | None = None, |
| 221 | + console: Console | None = None, |
| 222 | + secret_store: SecretStore | None = None, |
| 223 | + bypass_cache: bool = False, |
| 224 | + repo_dir: Path | None = None, |
| 225 | +) -> GenerationResult: |
| 226 | + """Generate structured release notes between two git references.""" |
| 227 | + con = console if console is not None else Console() |
| 228 | + active_cfg = cfg if cfg is not None else config_mod.load_config() |
| 229 | + |
| 230 | + # Budget cap check |
| 231 | + if active_cfg.budget_cap_usd is not None: |
| 232 | + monthly_spend = get_monthly_spend() |
| 233 | + if monthly_spend >= active_cfg.budget_cap_usd: |
| 234 | + con.print( |
| 235 | + f"[red]error:[/red] Monthly budget cap exceeded " |
| 236 | + f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). " |
| 237 | + "Aborting to prevent further LLM spend." |
| 238 | + ) |
| 239 | + return GenerationResult( |
| 240 | + text="Monthly budget cap exceeded. Generation aborted.", |
| 241 | + is_fallback=True, |
| 242 | + model=active_cfg.model, |
| 243 | + fallback_reason="Monthly budget cap exceeded", |
| 244 | + ) |
| 245 | + if monthly_spend >= 0.8 * active_cfg.budget_cap_usd: |
| 246 | + con.print( |
| 247 | + f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% " |
| 248 | + f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]" |
| 249 | + ) |
| 250 | + |
| 251 | + repo_path = repo_dir if repo_dir is not None else Path.cwd() |
| 252 | + runner = git_runner if git_runner is not None else SubprocessGitRunner() |
| 253 | + |
| 254 | + try: |
| 255 | + commits = extract_commits_between(from_ref, to_ref, runner=runner, repo=repo_path) |
| 256 | + except GitCommandError as exc: |
| 257 | + con.print(f"[red]git error:[/red] {exc}") |
| 258 | + return GenerationResult( |
| 259 | + text=f"Git error: {exc}", |
| 260 | + is_fallback=True, |
| 261 | + model=active_cfg.model, |
| 262 | + fallback_reason=str(exc), |
| 263 | + ) |
| 264 | + |
| 265 | + if not commits: |
| 266 | + empty_msg = f"No commits found between '{from_ref}' and '{to_ref}'." |
| 267 | + con.print(f"[dim]{empty_msg}[/dim]") |
| 268 | + return GenerationResult( |
| 269 | + text=empty_msg, |
| 270 | + is_fallback=False, |
| 271 | + model=active_cfg.model, |
| 272 | + ) |
| 273 | + |
| 274 | + extractor = ( |
| 275 | + diff_extractor |
| 276 | + if diff_extractor is not None |
| 277 | + else DiffExtractor(repo=repo_path, runner=runner) |
| 278 | + ) |
| 279 | + diffs = [] |
| 280 | + if include_diff: |
| 281 | + try: |
| 282 | + diffs = extractor.rev_range(from_ref, to_ref) |
| 283 | + except GitCommandError as exc: |
| 284 | + con.print( |
| 285 | + f"[yellow]warning: Could not extract diffs ({exc}), proceeding with commits only.[/yellow]" |
| 286 | + ) |
| 287 | + |
| 288 | + grouped = group_commits(commits) |
| 289 | + formatted_commits = format_commits_for_prompt(grouped) |
| 290 | + |
| 291 | + active_counter = counter |
| 292 | + if active_counter is None and provider is not None: |
| 293 | + |
| 294 | + class _SimpleCounter(TokenCounter): |
| 295 | + def count_tokens(self, text: str, model: str) -> int: |
| 296 | + return max(1, len(text) // 4) |
| 297 | + |
| 298 | + active_counter = _SimpleCounter() |
| 299 | + |
| 300 | + t0 = time.perf_counter() |
| 301 | + gen_result = run_generation_pipeline( |
| 302 | + diffs=diffs, |
| 303 | + cfg=active_cfg, |
| 304 | + template_name="changelog", |
| 305 | + fallback_generator=lambda: generate_fallback_changelog( |
| 306 | + commits, from_ref=from_ref, to_ref=to_ref |
| 307 | + ), |
| 308 | + template_vars={ |
| 309 | + "commits": formatted_commits, |
| 310 | + "from_ref": from_ref, |
| 311 | + "to_ref": to_ref, |
| 312 | + }, |
| 313 | + provider=provider, |
| 314 | + counter=active_counter, |
| 315 | + console=con, |
| 316 | + secret_store=secret_store, |
| 317 | + bypass_cache=bypass_cache, |
| 318 | + ) |
| 319 | + latency_ms = int((time.perf_counter() - t0) * 1000) |
| 320 | + |
| 321 | + _safe_record_telemetry( |
| 322 | + command="changelog", |
| 323 | + model=gen_result.model, |
| 324 | + tokens_in=gen_result.input_tokens, |
| 325 | + tokens_out=gen_result.output_tokens, |
| 326 | + cache_hit=gen_result.cache_hit, |
| 327 | + latency_ms=latency_ms, |
| 328 | + fallback_used=gen_result.is_fallback, |
| 329 | + estimated_cost_usd=gen_result.estimated_cost_usd, |
| 330 | + free_tier=active_cfg.free_tier, |
| 331 | + ) |
| 332 | + |
| 333 | + if output_file is not None: |
| 334 | + try: |
| 335 | + output_file.write_text(gen_result.text + "\n", encoding="utf-8") |
| 336 | + con.print(f"[green]✔ Changelog written to {output_file}[/green]") |
| 337 | + except OSError as exc: |
| 338 | + con.print(f"[red]error writing changelog file:[/red] {exc}") |
| 339 | + |
| 340 | + return gen_result |
0 commit comments