-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-ai-write-release-notes
More file actions
executable file
·391 lines (334 loc) · 16 KB
/
git-ai-write-release-notes
File metadata and controls
executable file
·391 lines (334 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/env -S uv --quiet run --script
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "gitpython",
# "click",
# "pydantic-ai",
# "rich",
# "tomli",
# ]
# ///
import os
import sys
from pathlib import Path
from typing import List, Optional
from enum import Enum
import click
import git
from pydantic_ai import Agent
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.theme import Theme
from rich.progress import Progress, SpinnerColumn, TextColumn
# Set up rich console with custom theme
custom_theme = Theme({
"heading": "bold blue",
"info": "green",
"error": "bold red",
"warning": "yellow",
})
console = Console(theme=custom_theme)
class ToneStyle(str, Enum):
STANDARD = "standard"
TECHNICAL = "technical"
CASUAL = "casual"
ENTHUSIASTIC = "enthusiastic"
MINIMAL = "minimal"
PIRATE = "pirate"
NERD = "nerd"
APOLOGETIC = "apologetic"
class BlogPostGenerator:
"""Generate a blog post announcing a new version based on git commits."""
model_name = "anthropic/claude-3-7-sonnet-latest"
def generate_blog_post(self, project_name: str, commits: List[str], tone: ToneStyle = ToneStyle.STANDARD) -> str:
"""
Generate a blog post announcing a new version based on git commits.
Args:
project_name: The name of the project
commits: A list of commit messages
tone: The tone/style to use for the blog post
Returns:
A markdown-formatted blog post announcing the new version
"""
# Base prompt structure
base_prompt = f"""
You are a technical writer for {project_name}. Create a blog post announcing a new version
of the software based on the following git commit messages. The blog post should:
1. Have a catchy title that mentions the project name
2. Include a brief introduction about the new release
3. Organize the changes into logical categories (features, bug fixes, etc.)
4. Highlight the most important changes
5. End with a call to action for users to update and provide feedback
Here are the commit messages:
{commits}
"""
# Add tone-specific instructions
tone_instructions = {
ToneStyle.STANDARD: """
Format your response in Markdown. Be concise but informative. Focus on the user benefits
of each change rather than technical implementation details.
""",
ToneStyle.TECHNICAL: """
Format your response in Markdown. Use a technical, detailed tone that emphasizes
implementation details and technical specifications. Include code examples or technical
concepts where relevant. This is for a technical audience who wants to understand the
engineering behind the changes.
""",
ToneStyle.CASUAL: """
Format your response in Markdown. Use a casual, conversational tone as if you're
chatting with the user. Be friendly and approachable, using simple language and
occasional humor. Avoid technical jargon unless absolutely necessary.
""",
ToneStyle.ENTHUSIASTIC: """
Format your response in Markdown. Be extremely enthusiastic and excited about the
changes. Use superlatives, exclamation points, and convey a sense of excitement
throughout the post. Make the reader feel like this is the most exciting update ever.
""",
ToneStyle.MINIMAL: """
Format your response in Markdown. Be extremely concise and to-the-point. Use bullet
points extensively and minimize prose. Focus only on what changed and why it matters,
with no marketing language or fluff.
""",
ToneStyle.PIRATE: """
Format your response in Markdown. Write the entire blog post in pirate speak, using
pirate slang, nautical references, and a swashbuckling tone. Say "arr" and "matey"
occasionally, refer to the software as "treasure" or "booty", and use other pirate
terminology throughout. Keep it fun but still make sure the information is clear.
""",
ToneStyle.NERD: """
Format your response in Markdown. Write the blog post in an extremely computer-nerdy tone.
Focus on technical programming details, algorithms, data structures, and system architecture.
Use programming jargon, reference computer science concepts, and show excitement about
implementation details like performance optimizations and elegant code patterns. Include
references to programming languages, tools, and computer science principles. Make technical
jokes and puns that would appeal to software developers and computer scientists. However,
stay grounded in the actual changes in the commit messages.
""",
ToneStyle.APOLOGETIC: """
Format your response in Markdown. Write the blog post in an apologetic tone, as if
the team is constantly apologizing for the changes or for taking so long to make them.
Express excessive gratitude for users' patience, apologize for any inconvenience, and
be overly humble about the achievements. Still describe all the changes accurately,
but frame them as if the team is nervous about how they'll be received.
"""
}
prompt = base_prompt + tone_instructions[tone]
agent = Agent(model=self.model_name)
with Progress(
SpinnerColumn(),
TextColumn(f"[info]Generating {tone.value} blog post...[/info]"),
console=console,
transient=True,
) as progress:
progress.add_task("generate", total=None)
result = agent.run_sync(prompt)
return result.data
def get_commit_messages(repo_path: Path, rev_range: Optional[str] = None, since_date: Optional[str] = None) -> List[str]:
"""Get commit messages from the specified git repository and revision range."""
try:
repo = git.Repo(repo_path)
# Create a git command object
git_cmd = repo.git
# Build the arguments for git log
kwargs = {
'pretty': 'format:%h %s%n%b' # Use kwargs for format to avoid quoting issues
}
# Add since date if provided
if since_date:
kwargs['since'] = since_date
# Add revision range if provided
args = []
if rev_range:
args.append(rev_range)
# Execute the git log command using the git.cmd_override method
# This properly handles the arguments without shell quoting issues
result = git_cmd.log(*args, **kwargs)
# Split the result into individual commit messages
commits = []
current_commit = ""
for line in result.split('\n'):
if line and line[0].isalnum() and len(line) >= 7 and line[7] == ' ':
# This is a new commit (starts with hash)
if current_commit:
commits.append(current_commit.strip())
current_commit = line
else:
# This is part of the current commit message
current_commit += f"\n{line}"
# Add the last commit
if current_commit:
commits.append(current_commit.strip())
return commits
except git.exc.GitCommandError as e:
console.print(f"[error]Git error: {e}[/error]")
sys.exit(1)
def get_project_name(repo_path: Path) -> str:
"""Try to determine the project name from the git repository or project files."""
try:
# Check for common project configuration files
# 1. Check pyproject.toml (Python)
pyproject_path = repo_path / "pyproject.toml"
if pyproject_path.exists():
import tomli
with open(pyproject_path, "rb") as f:
pyproject_data = tomli.load(f)
if "project" in pyproject_data and "name" in pyproject_data["project"]:
return pyproject_data["project"]["name"]
elif "tool" in pyproject_data and "poetry" in pyproject_data["tool"] and "name" in pyproject_data["tool"]["poetry"]:
return pyproject_data["tool"]["poetry"]["name"]
# 2. Check setup.py (Python)
setup_py_path = repo_path / "setup.py"
if setup_py_path.exists():
# Try to extract name from setup.py using a simple regex
import re
setup_content = setup_py_path.read_text()
if match := re.search(r'name\s*=\s*[\'"]([^\'"]+)[\'"]', setup_content):
return match.group(1)
# 3. Check package.json (Node.js)
package_json_path = repo_path / "package.json"
if package_json_path.exists():
import json
with open(package_json_path, "r") as f:
package_data = json.load(f)
if "name" in package_data:
return package_data["name"]
# 4. Check Cargo.toml (Rust)
cargo_toml_path = repo_path / "Cargo.toml"
if cargo_toml_path.exists():
import tomli
with open(cargo_toml_path, "rb") as f:
cargo_data = tomli.load(f)
if "package" in cargo_data and "name" in cargo_data["package"]:
return cargo_data["package"]["name"]
# 5. Check go.mod (Go)
go_mod_path = repo_path / "go.mod"
if go_mod_path.exists():
import re
go_mod_content = go_mod_path.read_text()
if match := re.search(r'^module\s+([^\s]+)', go_mod_content, re.MULTILINE):
# Extract the last part of the module path as the name
module_path = match.group(1)
return module_path.split('/')[-1]
# 6. Check composer.json (PHP)
composer_json_path = repo_path / "composer.json"
if composer_json_path.exists():
import json
with open(composer_json_path, "r") as f:
composer_data = json.load(f)
if "name" in composer_data:
# Composer uses vendor/package format, extract just the package name
return composer_data["name"].split('/')[-1]
# 7. Check build.gradle or settings.gradle (Java/Kotlin - Gradle)
gradle_files = [repo_path / "settings.gradle", repo_path / "settings.gradle.kts",
repo_path / "build.gradle", repo_path / "build.gradle.kts"]
for gradle_file in gradle_files:
if gradle_file.exists():
import re
content = gradle_file.read_text()
# Try to find rootProject.name or project name
if match := re.search(r'rootProject\.name\s*=\s*[\'"]([^\'"]+)[\'"]', content):
return match.group(1)
elif match := re.search(r'project\([\'"]([^\'"]+)[\'"]\)', content):
return match.group(1)
# 8. Check pom.xml (Java - Maven)
pom_xml_path = repo_path / "pom.xml"
if pom_xml_path.exists():
import re
pom_content = pom_xml_path.read_text()
if match := re.search(r'<artifactId>([^<]+)</artifactId>', pom_content):
return match.group(1)
# 9. Check gemspec files (Ruby)
import glob
gemspec_files = list(repo_path.glob("*.gemspec"))
if gemspec_files:
# Use the filename without extension as the project name
return gemspec_files[0].stem
# 10. Check pubspec.yaml (Dart/Flutter)
pubspec_path = repo_path / "pubspec.yaml"
if pubspec_path.exists():
import re
pubspec_content = pubspec_path.read_text()
if match := re.search(r'^name:\s*([^\s]+)', pubspec_content, re.MULTILINE):
return match.group(1)
# 11. Try to get the name from the remote URL
repo = git.Repo(repo_path)
if repo.remotes:
url = repo.remotes[0].url
# Extract project name from URL (works for GitHub, GitLab, etc.)
if '/' in url:
name = url.split('/')[-1]
# Remove .git suffix if present
if name.endswith('.git'):
name = name[:-4]
return name
# 12. Fallback: use the directory name
return repo_path.name
except Exception as e:
console.print(f"[warning]Error determining project name: {e}[/warning]", file=sys.stderr)
# If all else fails, use a generic name
return "Project"
@click.command()
@click.argument('rev_range', required=False)
@click.option('--repo-path', '-r', type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
default=Path('.'), help='Path to the git repository')
@click.option('--project-name', '-p', help='Name of the project (defaults to repo name)')
@click.option('--output', '-o', type=click.Path(path_type=Path),
help='Save the blog post to this file instead of printing to console')
@click.option('--raw', is_flag=True, help='Output raw markdown without rich formatting')
@click.option('--since', help='Show commits more recent than a specific date (e.g. "1 day ago")')
@click.option('--tone', '-t', type=click.Choice([t.value for t in ToneStyle]),
default=ToneStyle.STANDARD.value,
help='Tone/style of the blog post')
def main(rev_range: Optional[str], repo_path: Path, project_name: Optional[str],
output: Optional[Path], raw: bool, since: Optional[str], tone: str):
"""
Generate a blog post announcing a new version based on git commits.
REV_RANGE is an optional git revision range (e.g., 'v1.0..v1.1' or 'HEAD~10..HEAD').
If not provided, all commits will be included.
Examples:
git-ai-release-notes # Use all commits
git-ai-release-notes HEAD~5..HEAD # Use the last 5 commits
git-ai-release-notes v1.0..v1.1 # Use commits between tags v1.0 and v1.1
git-ai-release-notes --since="1 day ago" # Use commits from the last day
git-ai-release-notes -o blog-post.md # Save output to a file
git-ai-release-notes --tone=technical # Use a technical tone
"""
# Get commit messages
if since and not rev_range:
# Pass the since parameter directly to get_commit_messages
commits = get_commit_messages(repo_path, since_date=since)
else:
commits = get_commit_messages(repo_path, rev_range=rev_range)
if not commits:
console.print("[warning]No commits found in the specified range[/warning]")
return
# Determine project name if not provided
if not project_name:
project_name = get_project_name(repo_path)
# Convert tone string to enum - with error handling
try:
tone_enum = ToneStyle(tone)
except ValueError:
# This should not happen with Click's type checking, but just in case
available_tones = ", ".join([f"'{t.value}'" for t in ToneStyle])
console.print(f"[error]Error: Invalid tone '{tone}'[/error]")
console.print(f"[info]Available tones: {available_tones}[/info]")
sys.exit(1)
# Generate blog post
console.print(f"[info]Generating {tone_enum.value} blog post for [bold]{project_name}[/bold] based on {len(commits)} commits...[/info]")
generator = BlogPostGenerator()
blog_post = generator.generate_blog_post(project_name, commits, tone_enum)
# Output the blog post
if output:
output.write_text(blog_post)
console.print(f"[info]Blog post saved to [bold]{output}[/bold][/info]")
elif raw:
print(blog_post)
else:
md = Markdown(blog_post)
console.print(Panel(md, title=f"[bold]{project_name}[/bold] Release Announcement ({tone_enum.value})",
border_style="blue", padding=(1, 2)))
if __name__ == "__main__":
main()