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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#!/usr/bin/env python3
"""
Release management tools for Manim.

This script provides commands for preparing and managing Manim releases:
- Generate changelogs from GitHub's release notes API
- Update CITATION.cff with new version information
- Fetch existing release notes for documentation

Usage:
    # Generate changelog for an upcoming release
    uv run python scripts/release.py changelog --base v0.19.0 --version 0.20.0

    # Also update CITATION.cff at the same time
    uv run python scripts/release.py changelog --base v0.19.0 --version 0.20.0 --update-citation

    # Update only CITATION.cff
    uv run python scripts/release.py citation --version 0.20.0

    # Fetch existing release changelogs for documentation
    uv run python scripts/release.py fetch-releases

Requirements:
    - gh CLI installed and authenticated
    - Python 3.11+
"""

from __future__ import annotations

import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING

import click

if TYPE_CHECKING:
    from collections.abc import Sequence

# =============================================================================
# Constants
# =============================================================================

REPO = "manimcommunity/manim"

SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
CHANGELOG_DIR = REPO_ROOT / "docs" / "source" / "changelog"
CITATION_TEMPLATE = SCRIPT_DIR / "TEMPLATE.cff"
CITATION_FILE = REPO_ROOT / "CITATION.cff"

# Minimum version for fetching historical releases
DEFAULT_MIN_VERSION = "0.18.0"


# =============================================================================
# GitHub CLI Helpers
# =============================================================================


def run_gh(
    args: Sequence[str],
    *,
    check: bool = True,
    suppress_errors: bool = False,
) -> subprocess.CompletedProcess[str]:
    """
    Run a gh CLI command.

    Args:
        args: Arguments to pass to gh
        check: If True, raise on non-zero exit
        suppress_errors: If True, don't print errors to stderr

    Returns:
        CompletedProcess with stdout/stderr
    """
    result = subprocess.run(
        ["gh", *args],
        capture_output=True,
        text=True,
    )
    if (
        result.returncode != 0
        and not suppress_errors
        and "not found" not in result.stderr.lower()
    ):
        click.echo(f"gh error: {result.stderr}", err=True)
    if check and result.returncode != 0:
        raise click.ClickException(f"gh command failed: gh {' '.join(args)}")
    return result


def get_release_tags() -> list[str]:
    """Get all published release tags from GitHub, newest first."""
    result = run_gh(
        ["release", "list", "--repo", REPO, "--limit", "100", "--json", "tagName"],
        check=False,
    )
    if result.returncode != 0 or not result.stdout.strip():
        return []

    import json

    try:
        data = json.loads(result.stdout)
        return [item["tagName"] for item in data]
    except (json.JSONDecodeError, KeyError):
        return []


def get_release_body(tag: str) -> str | None:
    """Get the release body for a published release."""
    result = run_gh(
        ["release", "view", tag, "--repo", REPO, "--json", "body", "--jq", ".body"],
        check=False,
        suppress_errors=True,
    )
    if result.returncode != 0:
        return None
    return result.stdout.strip() or None


def get_release_date(tag: str) -> str | None:
    """Get the release date formatted as 'Month DD, YYYY'."""
    result = run_gh(
        [
            "release",
            "view",
            tag,
            "--repo",
            REPO,
            "--json",
            "createdAt",
            "--jq",
            ".createdAt",
        ],
        check=False,
    )
    if result.returncode != 0:
        return None

    date_str = result.stdout.strip().strip('"')
    try:
        dt = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
        return dt.strftime("%B %d, %Y")
    except ValueError:
        return None


def generate_release_notes(head_tag: str, base_tag: str) -> str:
    """
    Generate release notes using GitHub's API.

    This respects .github/release.yml for PR categorization.
    """
    result = run_gh(
        [
            "api",
            f"repos/{REPO}/releases/generate-notes",
            "--field",
            f"tag_name={head_tag}",
            "--field",
            f"previous_tag_name={base_tag}",
            "--jq",
            ".body",
        ]
    )
    body = result.stdout.strip()
    if not body:
        raise click.ClickException("GitHub API returned empty release notes")
    return body


# =============================================================================
# Version Utilities
# =============================================================================


def normalize_tag(tag: str) -> str:
    """Ensure tag has 'v' prefix."""
    return tag if tag.startswith("v") else f"v{tag}"


def version_from_tag(tag: str) -> str:
    """Extract version from tag (e.g., 'v0.18.0' -> '0.18.0')."""
    return tag[1:] if tag.startswith("v") else tag


def parse_version(version: str) -> tuple[int, ...]:
    """Parse version string into comparable tuple."""
    # Handle post-releases like '0.18.0.post0'
    version = version.replace(".post", "-post")
    parts = []
    for part in version.replace("-", ".").split("."):
        try:
            parts.append(int(part))
        except ValueError:
            continue
    # Pad to at least 3 components
    while len(parts) < 3:
        parts.append(0)
    return tuple(parts)


def version_gte(version: str, min_version: str) -> bool:
    """Check if version >= min_version."""
    return parse_version(version) >= parse_version(min_version)


# =============================================================================
# Markdown Conversion
# =============================================================================


def convert_to_myst(body: str) -> str:
    """
    Convert GitHub markdown to MyST format.

    - PR URLs -> {pr}`NUMBER`
    - Issue URLs -> {issue}`NUMBER`
    - @mentions -> {user}`USERNAME`
    - Strips HTML comments
    - Ensures proper list spacing
    """
    lines = body.split("\n")
    result = []
    prev_bullet = False

    for line in lines:
        # Skip HTML comments
        if line.strip().startswith("<!--") and line.strip().endswith("-->"):
            continue

        # Convert URLs to extlinks
        line = re.sub(
            r"https://github\.com/ManimCommunity/manim/pull/(\d+)",
            r"{pr}`\1`",
            line,
        )
        line = re.sub(
            r"https://github\.com/ManimCommunity/manim/issues/(\d+)",
            r"{issue}`\1`",
            line,
        )
        line = re.sub(r"@([a-zA-Z0-9_-]+)", r"{user}`\1`", line)

        if line.startswith("**Full Changelog**:"):
            _, url = line.split(":", 1)
            url = url.strip().replace("vmain", "main")
            line = f"**Full Changelog**: [Compare view]({url})"

        # Handle list spacing
        is_bullet = line.strip().startswith("*") and not line.strip().startswith("**")
        if prev_bullet and not is_bullet and line.strip():
            result.append("")

        result.append(line)
        prev_bullet = is_bullet

    return "\n".join(result)


def format_changelog(
    version: str,
    body: str,
    date: str | None = None,
    title: str | None = None,
) -> str:
    """Create changelog file content with MyST frontmatter."""
    title = title or f"v{version}"
    body = convert_to_myst(body)
    date_section = f"Date\n: {date}\n" if date else ""

    return f"""---
short-title: {title}
description: Changelog for {title}
---

# {title}

{date_section}
{body}
"""


# =============================================================================
# File Operations
# =============================================================================


def get_existing_versions() -> set[str]:
    """Get versions that already have changelog files."""
    if not CHANGELOG_DIR.exists():
        return set()
    return {
        f.stem.replace("-changelog", "") for f in CHANGELOG_DIR.glob("*-changelog.*")
    }


def save_changelog(version: str, content: str) -> Path:
    """Save changelog and return filepath."""
    filepath = CHANGELOG_DIR / f"{version}-changelog.md"
    filepath.write_text(content)
    return filepath


def update_citation(version: str, date: str | None = None) -> Path:
    """Update CITATION.cff from template."""
    if not CITATION_TEMPLATE.exists():
        raise click.ClickException(f"Citation template not found: {CITATION_TEMPLATE}")

    date = date or datetime.now().strftime("%Y-%m-%d")
    version_tag = normalize_tag(version)

    content = CITATION_TEMPLATE.read_text()
    content = content.replace("<version>", version_tag)
    content = content.replace("<date_released>", date)

    CITATION_FILE.write_text(content)
    return CITATION_FILE


# =============================================================================
# CLI Commands
# =============================================================================


@click.group()
@click.option(
    "--dry-run", is_flag=True, help="Show what would be done without making changes"
)
@click.pass_context
def cli(ctx: click.Context, dry_run: bool) -> None:
    """Release management tools for Manim."""
    ctx.ensure_object(dict)
    ctx.obj["dry_run"] = dry_run


@cli.command()
@click.option("--base", required=True, help="Base tag for comparison (e.g., v0.19.0)")
@click.option(
    "--version", "version", required=True, help="New version number (e.g., 0.20.0)"
)
@click.option("--head", default="main", help="Head ref for comparison (default: main)")
@click.option("--title", help="Custom changelog title (default: vX.Y.Z)")
@click.option(
    "--update-citation",
    "also_update_citation",
    is_flag=True,
    help="Also update CITATION.cff",
)
@click.pass_context
def changelog(
    ctx: click.Context,
    base: str,
    version: str,
    head: str,
    title: str | None,
    also_update_citation: bool,
) -> None:
    """Generate changelog for an upcoming release.

    Uses GitHub's release notes API with .github/release.yml categorization.
    """
    dry_run = ctx.obj["dry_run"]
    base_tag = normalize_tag(base)
    head_tag = normalize_tag(head) if head != "main" else normalize_tag(version)

    click.echo(f"Generating changelog for v{version}...")
    click.echo(f"  Comparing: {base_tag}{head}")

    body = generate_release_notes(head_tag, base_tag)
    date = datetime.now().strftime("%B %d, %Y")
    content = format_changelog(version, body, date=date, title=title)

    if dry_run:
        click.echo()
        click.secho("[DRY RUN]", fg="yellow", bold=True)
        click.echo(f"  Would save: {CHANGELOG_DIR / f'{version}-changelog.md'}")
        if also_update_citation:
            click.echo(f"  Would update: {CITATION_FILE}")
        click.echo()
        click.echo("--- Generated changelog ---")
        click.echo(content)
        return

    filepath = save_changelog(version, content)
    click.secho(f"  ✓ Saved: {filepath}", fg="green")

    if also_update_citation:
        citation_path = update_citation(version)
        click.secho(f"  ✓ Updated: {citation_path}", fg="green")

    click.echo()
    click.echo("Next steps:")
    click.echo("  • Review and edit the changelog as needed")
    click.echo("  • Update docs/source/changelog.rst to include the new file")


@cli.command()
@click.option(
    "--version", "version", required=True, help="Version number (e.g., 0.20.0)"
)
@click.option("--date", help="Release date as YYYY-MM-DD (default: today)")
@click.pass_context
def citation(ctx: click.Context, version: str, date: str | None) -> None:
    """Update CITATION.cff for a release."""
    dry_run = ctx.obj["dry_run"]
    display_date = date or datetime.now().strftime("%Y-%m-%d")

    if dry_run:
        click.secho("[DRY RUN]", fg="yellow", bold=True)
        click.echo(f"  Would update: {CITATION_FILE}")
        click.echo(f"  Version: v{version}")
        click.echo(f"  Date: {display_date}")
        return

    filepath = update_citation(version, date)
    click.secho(f"✓ Updated: {filepath}", fg="green")
    click.echo(f"  Version: v{version}")
    click.echo(f"  Date: {display_date}")


@cli.command("fetch-releases")
@click.option("--tag", help="Fetch a specific release tag")
@click.option(
    "--min-version",
    default=DEFAULT_MIN_VERSION,
    help=f"Minimum version to fetch (default: {DEFAULT_MIN_VERSION})",
)
@click.option("--force", is_flag=True, help="Overwrite existing changelog files")
@click.pass_context
def fetch_releases(
    ctx: click.Context,
    tag: str | None,
    min_version: str,
    force: bool,
) -> None:
    """Fetch existing release changelogs from GitHub.

    Converts GitHub release notes to documentation-ready MyST markdown.
    """
    dry_run = ctx.obj["dry_run"]
    existing = get_existing_versions()

    # Single tag mode
    if tag:
        tag = normalize_tag(tag)
        version = version_from_tag(tag)

        if version in existing and not force:
            click.echo(
                f"Changelog for {version} already exists. Use --force to overwrite."
            )
            return

        if dry_run:
            click.secho("[DRY RUN]", fg="yellow", bold=True)
            click.echo(f"  Would fetch: {version}")
            return

        _fetch_single_release(tag, version)
        return

    # Batch mode
    click.echo(f"Existing versions: {', '.join(sorted(existing)) or '(none)'}")
    click.echo("Fetching release list...")

    tags = get_release_tags()
    click.echo(f"Found {len(tags)} releases")

    fetched = 0
    prev_tag = None

    for tag in reversed(tags):
        version = version_from_tag(tag)

        if not version_gte(version, min_version):
            prev_tag = tag
            continue

        if version in existing and not force:
            click.echo(f"  Skipping {version} (exists)")
            prev_tag = tag
            continue

        if dry_run:
            click.echo(f"  [DRY RUN] Would fetch {version}")
            fetched += 1
        else:
            if _fetch_single_release(tag, version, prev_tag):
                existing.add(version)
                fetched += 1

        prev_tag = tag

    click.echo()
    click.echo(f"Processed {fetched} changelog(s)")

    if fetched > 0 and not dry_run:
        click.echo()
        click.echo("Next steps:")
        click.echo("  • Update docs/source/changelog.rst to include new files")


def _fetch_single_release(tag: str, version: str, prev_tag: str | None = None) -> bool:
    """Fetch and save a single release changelog."""
    click.echo(f"  Fetching {version}...")

    body = get_release_body(tag)

    if not body and prev_tag:
        click.echo(f"    No body, generating from {prev_tag}...")
        try:
            body = generate_release_notes(tag, prev_tag)
        except click.ClickException:
            body = None

    if not body:
        click.secho(f"    ✗ Could not get release notes for {tag}", fg="red", err=True)
        return False

    date = get_release_date(tag)
    content = format_changelog(version, body, date=date)

    filepath = save_changelog(version, content)
    click.secho(f"    ✓ Saved: {filepath}", fg="green")
    return True


# =============================================================================
# Entry Point
# =============================================================================


def main() -> None:
    """Entry point."""
    cli()


if __name__ == "__main__":
    sys.exit(main() or 0)