Skip to content

Commit ffcf5bd

Browse files
committed
ruff fix
1 parent 15a02a2 commit ffcf5bd

File tree

7 files changed

+286
-233
lines changed

7 files changed

+286
-233
lines changed

changeset/changelog.py

Lines changed: 87 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,19 @@
88
import os
99
import re
1010
import subprocess
11-
from datetime import datetime
1211
from pathlib import Path
1312

1413
import click
15-
import toml
16-
import tomllib
1714

1815
# Import from changeset.py to reuse logic
1916
from changeset.changeset import (
20-
determine_version_bump,
2117
bump_version,
18+
determine_version_bump,
2219
find_project_pyproject,
23-
get_changesets as get_changesets_from_changeset,
2420
get_current_version,
25-
parse_changeset,
21+
)
22+
from changeset.changeset import (
23+
get_changesets as get_changesets_from_changeset,
2624
)
2725

2826
CHANGESET_DIR = Path(".changeset")
@@ -42,7 +40,7 @@ def load_config() -> dict:
4240
def get_git_info() -> dict:
4341
"""Get git information for the current commit/PR."""
4442
info = {}
45-
43+
4644
# Get the current commit hash
4745
try:
4846
result = subprocess.run(
@@ -52,9 +50,9 @@ def get_git_info() -> dict:
5250
check=True
5351
)
5452
info["commit"] = result.stdout.strip()[:7] # Short hash
55-
except:
53+
except Exception:
5654
info["commit"] = None
57-
55+
5856
# Get GitHub repo info
5957
try:
6058
result = subprocess.run(
@@ -70,9 +68,9 @@ def get_git_info() -> dict:
7068
info["owner"] = match.group(1)
7169
info["repo"] = match.group(2)
7270
info["repo_url"] = f"https://github.com/{info['owner']}/{info['repo']}"
73-
except:
71+
except Exception:
7472
pass
75-
73+
7674
return info
7775

7876

@@ -83,17 +81,17 @@ def get_pr_metadata() -> dict:
8381
"pr_author": os.environ.get("PR_AUTHOR"),
8482
"commit_hash": os.environ.get("COMMIT_SHA", ""),
8583
}
86-
84+
8785
# Always get git info for repo URL
8886
git_info = get_git_info()
89-
87+
9088
# Use git commit if not in environment
9189
if not metadata["commit_hash"]:
9290
metadata["commit_hash"] = git_info.get("commit", "")
93-
91+
9492
# Always use repo URL from git
9593
metadata["repo_url"] = git_info.get("repo_url", "")
96-
94+
9795
return metadata
9896

9997

@@ -108,25 +106,25 @@ def format_changelog_entry(
108106
pr_author = pr_metadata.get("pr_author")
109107
commit_hash = pr_metadata.get("commit_hash", "")[:7]
110108
repo_url = pr_metadata.get("repo_url", "")
111-
109+
112110
# Build the entry
113111
parts = []
114-
112+
115113
# Add PR link if available
116114
if pr_number and repo_url:
117115
parts.append(f"[#{pr_number}]({repo_url}/pull/{pr_number})")
118-
116+
119117
# Add commit link if available
120118
if commit_hash and repo_url:
121119
parts.append(f"[`{commit_hash}`]({repo_url}/commit/{commit_hash})")
122-
120+
123121
# Add author thanks if available
124122
if pr_author:
125123
parts.append(f"Thanks @{pr_author}!")
126-
124+
127125
# Add description
128126
parts.append(f"- {description}")
129-
127+
130128
return " ".join(parts)
131129

132130

@@ -139,40 +137,40 @@ def generate_changelog_section(
139137
) -> str:
140138
"""Generate changelog section for a package version."""
141139
lines = []
142-
140+
143141
# Add version header
144142
lines.append(f"## {new_version}")
145143
lines.append("")
146-
144+
147145
# Group entries by change type
148146
grouped = {}
149147
for entry in entries:
150148
change_type = entry["type"]
151149
if change_type not in grouped:
152150
grouped[change_type] = []
153151
grouped[change_type].append(entry)
154-
152+
155153
# Add sections for each change type
156154
for change_type in ["major", "minor", "patch"]:
157155
if change_type not in grouped:
158156
continue
159-
157+
160158
# Get the change type label
161159
type_label = {
162160
"major": "Major Changes",
163161
"minor": "Minor Changes",
164162
"patch": "Patch Changes"
165163
}.get(change_type, f"{change_type.capitalize()} Changes")
166-
164+
167165
lines.append(f"### {type_label}")
168166
lines.append("")
169-
167+
170168
# Add each entry
171169
for entry in grouped[change_type]:
172170
lines.append(format_changelog_entry(entry, config, pr_metadata))
173-
171+
174172
lines.append("")
175-
173+
176174
return "\n".join(lines).strip()
177175

178176

@@ -187,11 +185,11 @@ def update_or_create_changelog(
187185
else:
188186
# Create new changelog with package name header
189187
content = f"# {package_name}\n\n"
190-
188+
191189
# Insert the new section after the package name header
192190
lines = content.split("\n")
193191
insert_index = None
194-
192+
195193
# Find where to insert (after header, before first version)
196194
for i, line in enumerate(lines):
197195
if line.startswith("# "):
@@ -203,7 +201,7 @@ def update_or_create_changelog(
203201
if insert_index is None:
204202
insert_index = i + 1
205203
break
206-
204+
207205
if insert_index is None:
208206
# No header found, just prepend
209207
new_content = new_section + "\n\n" + content
@@ -212,7 +210,7 @@ def update_or_create_changelog(
212210
lines.insert(insert_index, new_section)
213211
lines.insert(insert_index + 1, "")
214212
new_content = "\n".join(lines)
215-
213+
216214
# Write the updated content
217215
changelog_path.write_text(new_content)
218216
return True
@@ -221,26 +219,26 @@ def update_or_create_changelog(
221219
def generate_pr_description(package_updates: list[dict]) -> str:
222220
"""Generate a combined PR description for all package updates."""
223221
lines = ["# Releases", ""]
224-
222+
225223
for update in package_updates:
226224
package = update["package"]
227225
version = update["version"]
228226
changelog_content = update["changelog_content"]
229-
227+
230228
# Add package header
231229
lines.append(f"## {package}@{version}")
232230
lines.append("")
233-
231+
234232
# Add the changelog content (without the package header)
235233
# Skip the first line if it's a version header
236234
changelog_lines = changelog_content.split("\n")
237235
start_index = 0
238236
if changelog_lines and changelog_lines[0].startswith("## "):
239237
start_index = 1
240-
238+
241239
lines.extend(changelog_lines[start_index:])
242240
lines.append("")
243-
241+
244242
return "\n".join(lines)
245243

246244

@@ -251,16 +249,16 @@ def process_changesets_for_changelog() -> tuple[list[dict], str]:
251249
"""
252250
config = load_config()
253251
pr_metadata = get_pr_metadata()
254-
252+
255253
# Get all changesets
256254
changesets = get_changesets_from_changeset()
257255
if not changesets:
258256
return [], ""
259-
257+
260258
# Group changesets by package
261259
package_changes = {}
262260
changeset_files = set()
263-
261+
264262
for filepath, package, change_type, desc in changesets:
265263
changeset_files.add(filepath)
266264
if package not in package_changes:
@@ -271,23 +269,23 @@ def process_changesets_for_changelog() -> tuple[list[dict], str]:
271269
"description": desc,
272270
"changeset": filepath.name
273271
})
274-
272+
275273
# Process each package
276274
package_updates = []
277-
275+
278276
for package, info in package_changes.items():
279277
# Find pyproject.toml
280278
try:
281279
pyproject_path = find_project_pyproject(package)
282280
except ValueError as e:
283281
click.echo(click.style(f"⚠️ {e}", fg="yellow"))
284282
continue
285-
283+
286284
# Determine new version
287285
bump_type = determine_version_bump(info["changes"])
288286
current_version = get_current_version(pyproject_path)
289287
new_version = bump_version(current_version, bump_type)
290-
288+
291289
# Generate changelog content
292290
changelog_content = generate_changelog_section(
293291
package,
@@ -296,10 +294,10 @@ def process_changesets_for_changelog() -> tuple[list[dict], str]:
296294
config,
297295
pr_metadata
298296
)
299-
297+
300298
# Find changelog path (same directory as pyproject.toml)
301299
changelog_path = pyproject_path.parent / "CHANGELOG.md"
302-
300+
303301
package_updates.append({
304302
"package": package,
305303
"version": new_version,
@@ -308,68 +306,88 @@ def process_changesets_for_changelog() -> tuple[list[dict], str]:
308306
"changelog_content": changelog_content,
309307
"pyproject_path": pyproject_path,
310308
})
311-
309+
312310
# Generate PR description
313311
pr_description = generate_pr_description(package_updates)
314-
312+
315313
return package_updates, pr_description
316314

317315

318316
@click.command()
319-
@click.option("--dry-run", is_flag=True, help="Show what would be done without making changes")
317+
@click.option(
318+
"--dry-run", is_flag=True, help="Show what would be done without making changes"
319+
)
320320
@click.option("--output-pr-description", help="File to write PR description to")
321321
def main(dry_run: bool, output_pr_description: str):
322322
"""Generate changelogs from changesets with version bumping."""
323-
323+
324324
click.echo(click.style("📜 Generating changelogs...\n", fg="cyan", bold=True))
325-
325+
326326
# Process changesets
327327
package_updates, pr_description = process_changesets_for_changelog()
328-
328+
329329
if not package_updates:
330330
click.echo(click.style("No changesets found. Nothing to do!", fg="yellow"))
331331
return
332-
332+
333333
# Show what will be done
334-
click.echo(click.style(f"Found updates for {len(package_updates)} package(s):", fg="green"))
334+
click.echo(
335+
click.style(f"Found updates for {len(package_updates)} package(s):", fg="green")
336+
)
335337
for update in package_updates:
336-
click.echo(f" 📦 {update['package']}: {update['current_version']}{update['version']}")
337-
338+
current = update['current_version']
339+
new = update['version']
340+
click.echo(f" 📦 {update['package']}: {current}{new}")
341+
338342
if dry_run:
339-
click.echo(click.style("\n🔍 Dry run mode - no changes will be made", fg="yellow"))
343+
click.echo(
344+
click.style("\n🔍 Dry run mode - no changes will be made", fg="yellow")
345+
)
340346
click.echo("\n" + "="*60)
341347
click.echo(click.style("PR Description:", fg="cyan"))
342348
click.echo("="*60)
343349
click.echo(pr_description)
344350
click.echo("="*60)
345-
351+
346352
for update in package_updates:
347-
click.echo(click.style(f"\nChangelog for {update['changelog_path']}:", fg="cyan"))
353+
click.echo(
354+
click.style(f"\nChangelog for {update['changelog_path']}:", fg="cyan")
355+
)
348356
click.echo("-"*60)
349357
click.echo(update["changelog_content"])
350358
click.echo("-"*60)
351359
return
352-
360+
353361
# Update changelog files
354362
for update in package_updates:
355363
success = update_or_create_changelog(
356364
update["changelog_path"],
357365
update["package"],
358366
update["changelog_content"]
359367
)
360-
368+
361369
if success:
362-
click.echo(click.style(f"✅ Updated {update['changelog_path']}", fg="green"))
370+
click.echo(
371+
click.style(f"✅ Updated {update['changelog_path']}", fg="green")
372+
)
363373
else:
364-
click.echo(click.style(f"❌ Failed to update {update['changelog_path']}", fg="red"))
365-
374+
click.echo(
375+
click.style(f"❌ Failed to update {update['changelog_path']}", fg="red")
376+
)
377+
366378
# Write PR description if requested
367379
if output_pr_description:
368380
Path(output_pr_description).write_text(pr_description)
369-
click.echo(click.style(f"✅ Wrote PR description to {output_pr_description}", fg="green"))
370-
371-
click.echo(click.style("\n✅ Changelog generation complete!", fg="green", bold=True))
381+
click.echo(
382+
click.style(
383+
f"✅ Wrote PR description to {output_pr_description}", fg="green"
384+
)
385+
)
386+
387+
click.echo(
388+
click.style("\n✅ Changelog generation complete!", fg="green", bold=True)
389+
)
372390

373391

374392
if __name__ == "__main__":
375-
main()
393+
main()

0 commit comments

Comments
 (0)