Skip to content

Commit 16323ed

Browse files
Merge pull request #12 from getdownandcode/feat
feat: Phase 7 — PR summaries, release changelogs, and unified orchestrator
2 parents 8491ff8 + 7219d29 commit 16323ed

16 files changed

Lines changed: 1707 additions & 256 deletions

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ dependencies = [
1919
"httpx>=0.27",
2020
"google-genai>=0.3", # default provider (Gemini 3 Flash / Flash-Lite)
2121
"anthropic>=0.34", # secondary provider, same LLMProvider interface
22+
"pyperclip>=1.8.2",
2223
]
2324

2425
[project.optional-dependencies]

‎src/gitmate/changelog.py‎

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
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

‎src/gitmate/cli.py‎

Lines changed: 91 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
import dataclasses
6+
from pathlib import Path
67

78
import typer
89
from rich.console import Console
@@ -20,6 +21,7 @@
2021
app.add_typer(config_app, name="config")
2122

2223
console = Console()
24+
err_console = Console(stderr=True)
2325
secret_store: config_mod.SecretStore = config_mod.KeyringSecretStore()
2426

2527

@@ -117,16 +119,97 @@ def stats(
117119
console.print(cmd_table)
118120

119121

120-
@app.command()
121-
def pr_summary() -> None:
122-
"""Generate a PR description for the current branch."""
123-
_stub("pr-summary", "coming in Phase 7")
122+
@app.command("pr-summary")
123+
def pr_summary(
124+
base: str = typer.Option("main", "--base", "-b", help="Base branch to compare against."),
125+
title: str | None = typer.Option(None, "--title", "-t", help="PR title for gh pr create."),
126+
copy: bool = typer.Option(True, "--copy/--no-copy", help="Copy summary to clipboard."),
127+
create_pr: bool = typer.Option(
128+
False, "--create-pr", help="Open GitHub PR create flow with gh CLI."
129+
),
130+
bypass_cache: bool = typer.Option(False, "--bypass-cache", help="Bypass cached generations."),
131+
) -> None:
132+
"""Generate a PR description by comparing HEAD against a base branch."""
133+
from rich.markdown import Markdown
134+
from rich.panel import Panel
124135

136+
from gitmate.diff_extractor import GitCommandError
137+
from gitmate.orchestrator import BudgetCapExceededError
138+
from gitmate.pr_summary import GitHubCliError, generate_pr_summary
125139

126-
@app.command()
127-
def changelog() -> None:
128-
"""Generate a changelog section for a tag range."""
129-
_stub("changelog", "coming in Phase 7")
140+
try:
141+
res = generate_pr_summary(
142+
base=base,
143+
title=title,
144+
console=err_console,
145+
secret_store=secret_store,
146+
bypass_cache=bypass_cache,
147+
copy_to_cb=copy,
148+
create_pr=create_pr,
149+
)
150+
except (GitCommandError, BudgetCapExceededError, GitHubCliError) as exc:
151+
err_console.print(f"[red]error:[/red] {exc}")
152+
raise typer.Exit(1) from None
153+
154+
if res.text.startswith("No changes between"):
155+
err_console.print(f"[dim]{res.text}[/dim]")
156+
return
157+
158+
status_badge = (
159+
"[yellow bold]⚠ FALLBACK TEMPLATE[/yellow bold]"
160+
if res.is_fallback
161+
else f"[green bold]{res.model}[/green bold]"
162+
)
163+
panel = Panel(
164+
Markdown(res.text),
165+
title=f"PR Summary [dim]({base}...HEAD) ({status_badge})[/dim]",
166+
border_style="yellow" if res.is_fallback else "green",
167+
padding=(1, 2),
168+
)
169+
console.print(panel)
170+
171+
172+
@app.command("changelog")
173+
def changelog(
174+
from_ref: str = typer.Option(
175+
..., "--from", "-f", help="Starting git revision or tag (exclusive)."
176+
),
177+
to_ref: str = typer.Option(
178+
"HEAD", "--to", "-t", help="Ending git revision or tag (inclusive)."
179+
),
180+
output: Path | None = typer.Option( # noqa: B008
181+
None, "--output", "-o", help="Output file path (prints to stdout if omitted)."
182+
),
183+
include_diff: bool = typer.Option(
184+
False, "--include-diff", help="Include diff summaries in addition to commits."
185+
),
186+
bypass_cache: bool = typer.Option(False, "--bypass-cache", help="Bypass cached generations."),
187+
) -> None:
188+
"""Generate a changelog section between two git tags or revisions."""
189+
from gitmate.changelog import generate_changelog
190+
from gitmate.diff_extractor import GitCommandError
191+
from gitmate.orchestrator import BudgetCapExceededError
192+
193+
try:
194+
res = generate_changelog(
195+
from_ref=from_ref,
196+
to_ref=to_ref,
197+
include_diff=include_diff,
198+
output_file=output,
199+
console=err_console,
200+
secret_store=secret_store,
201+
bypass_cache=bypass_cache,
202+
)
203+
except (GitCommandError, BudgetCapExceededError) as exc:
204+
err_console.print(f"[red]error:[/red] {exc}")
205+
raise typer.Exit(1) from None
206+
207+
if res.text.startswith("No commits found"):
208+
err_console.print(f"[dim]{res.text}[/dim]")
209+
return
210+
211+
if output is None:
212+
typer.echo(res.text)
130213

131214

132215
@app.command()

0 commit comments

Comments
 (0)