#!/usr/bin/env python3
"""
Library Upgrade Risk Scanner
============================
A CLI tool to scan Python library upgrades for:
- API surface diffs (using griffe for precise dataclass-based diffs)
- Deprecations (detected via griffe's deprecation metadata)
- Recommended migration notes (heuristic suggestions based on diffs)
Requirements:
pip install griffe[cli] click rich jinja2
Usage:
python scanner.py requests 2.28.0 2.31.0
python scanner.py flask 2.0.0 3.0.0
Supports PyPI packages via `pypi://package[version]` URLs.
Only exact version matches; use semantic versioning wisely.
"""
import click
import rich.console
import rich.table
import rich.markdown
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from dataclasses import asdict
from griffe import GriffeLoader, Module, Diff, DiffItem, Member
from griffe.exceptions import GriffeError
from griffe.deprecation import DeprecationInfo
import jinja2
@click.command()
@click.argument("package")
@click.argument("from_version")
@click.argument("to_version")
@click.option("--github-repo", help="GitHub repo URL if not auto-detected (e.g., https://github.com/psf/requests)")
@click.option("--output", "-o", type=click.Choice(["markdown", "json", "console"]), default="console")
@click.option("--risk-threshold", type=int, default=5, help="Alert if breaking changes > threshold")
def scan(
package: str,
from_version: str,
to_version: str,
github_repo: Optional[str],
output: str,
risk_threshold: int,
):
"""
Scan a Python library upgrade from FROM_VERSION to TO_VERSION.
"""
console = rich.console.Console()
try:
old_url = f"pypi://{package}[{from_version}]"
new_url = f"pypi://{package}[{to_version}]"
loader = GriffeLoader(cache=False, search_paths=[])
console.print(f"[bold blue]Loading {package}[{from_version}] → [{to_version}][/]")
old_module = loader.load_single(old_url)
new_module = loader.load_single(new_url)
diff = old_module.diff(new_module, use_cache=False)
# Analyze
breaking_changes = count_breaking_changes(diff)
deprecations = find_deprecations(new_module)
api_summary = summarize_api_surface(diff)
risk_score = calculate_risk(breaking_changes, len(deprecations), diff)
# Render report
report = generate_report(
package=package,
from_version=from_version,
to_version=to_version,
diff=diff,
breaking_changes=breaking_changes,
deprecations=deprecations,
api_summary=api_summary,
risk_score=risk_score,
risk_threshold=risk_threshold,
)
if output == "console":
console.print(rich.markdown.Markdown(report["markdown"]))
_print_rich_summary(console, risk_score, report)
elif output == "markdown":
click.echo(report["markdown"])
elif output == "json":
click.echo(report["json"])
except GriffeError as e:
console.print(f"[red]Error loading package: {e}[/]")
console.print("[yellow]Tips:[/]")
console.print(" - Ensure versions exist on PyPI.")
console.print(" - Try --github-repo for GitHub tags.")
raise click.Abort()
def count_breaking_changes(diff: Diff) -> int:
"""Count potential breaking changes (removals, signature changes)."""
count = 0
for item in diff.diffs:
if isinstance(item, DiffItem) and item.kind in ("removed", "updated"):
count += 1
# Recurse for nested
if hasattr(item, "diffs") and item.diffs:
count += count_breaking_changes(item) # type: ignore
return count
def find_deprecations(module: Module) -> List[Tuple[str, DeprecationInfo]]:
"""Find all deprecations in the new module."""
deprecations = []
for obj_name, obj in module.all_objects.items():
if isinstance(obj, Member) and obj.deprecation:
deprecations.append((obj_name, obj.deprecation))
return deprecations
def summarize_api_surface(diff: Diff) -> Dict[str, int]:
"""Summarize added/removed/updated public APIs."""
summary = {"added": 0, "removed": 0, "updated": 0, "renamed": 0}
for item in diff.diffs:
if isinstance(item, DiffItem):
summary[item.kind] = summary.get(item.kind, 0) + 1
if item.kind == "updated" and item.renamed_from:
summary["renamed"] += 1
return summary
def calculate_risk(breaking: int, deprecations: int, diff: Diff) -> Dict[str, any]:
"""Calculate risk score (0-10) and category."""
score = min(10, breaking * 2 + deprecations)
category = "LOW" if score < 3 else "MEDIUM" if score < 7 else "HIGH"
return {"score": score, "category": category, "breaking_changes": breaking}
def generate_migration_notes(diff: Diff, deprecations: List) -> str:
"""Generate heuristic migration notes."""
notes = []
for item in diff.diffs:
if isinstance(item, DiffItem):
if item.kind == "removed":
notes.append(f"* `{item.obj.name}` was **removed**. Check release notes for alternatives.")
elif item.kind == "updated":
if item.changes and "signature" in str(item.changes).lower():
notes.append(f"* `{item.obj.name}` signature changed. Review parameters.")
if item.renamed_from:
notes.append(f"* `{item.old.name}` → `{item.obj.name}` (renamed).")
for path, dep in deprecations:
notes.append(f"* `{path}` is **deprecated**: {dep.message or 'No message provided'}")
return "\n".join(notes) or "No major migration issues detected."
jinja_env = jinja2.Environment(
loader=jinja2.BaseLoader(),
trim_blocks=True,
lstrip_blocks=True,
)
template_md = jinja_env.from_string("""
# {{ package }} Upgrade Risk Report: {{ from_version }} → {{ to_version }}
## Risk Summary
- **Risk Score**: {{ risk_score.score }}/10 ({{ risk_score.category }})
- **Breaking Changes**: {{ risk_score.breaking_changes }}
- **New Deprecations**: {{ deprecations|length }}
- **API Changes**: Added: {{ api_summary.added }}, Removed: {{ api_summary.removed }}, Updated: {{ api_summary.updated }}
{% if risk_score.score > risk_threshold %}
> **⚠️ HIGH RISK**: {{ risk_score.score - risk_threshold }}+ breaking changes detected!
{% endif %}
## API Surface Diffs
{{ diff.as_tree(expand=False) }}
Full diff tree above. Key changes:
{% for k, v in api_summary.items() if v > 0 and k != 'renamed' %}
- {{ v }} {{ k.title() }}
{% endfor %}
## Deprecations in New Version
{% for path, dep in deprecations %}
- `{{ path }}`: {{ dep.message or 'Deprecated (no message)' }}
{% endfor %}
## Recommended Migration Notes
{{ migration_notes | replace('\n', '\n- ') }}
## Next Steps
1. Review full [changelog](https://pypi.org/project/{{ package }}/#history).
2. Run your tests against the new version.
3. Use `griffe diff` for deeper inspection.
""")
def generate_report(
package: str,
from_version: str,
to_version: str,
diff: Diff,
breaking_changes: int,
deprecations: List,
api_summary: Dict,
risk_score: Dict,
risk_threshold: int,
) -> Dict[str, str]:
migration_notes = generate_migration_notes(diff, deprecations)
md = template_md.render(
package=package,
from_version=from_version,
to_version=to_version,
diff=diff,
deprecations=deprecations,
api_summary=api_summary,
risk_score=risk_score,
risk_threshold=risk_threshold,
migration_notes=migration_notes,
)
return {
"markdown": md,
"json": "", # TODO: Add JSON serializer for diff
}
def _print_rich_summary(console, risk_score: Dict, report: Dict):
table = rich.table.Table(title="Quick Risk Overview")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Risk Score", f"{risk_score['score']}/10 ({risk_score['category']})")
table.add_row("Breaking Changes", str(risk_score["breaking_changes"]))
table.add_row("Deprecations", str(len(report["deprecations"])))
console.print(table)
if __name__ == "__main__":
scan()
Quick Start
-
Install dependencies:
pip install griffe[cli] click rich jinja2
-
Save as scanner.py and run:
python scanner.py requests 2.28.0 2.31.0
python scanner.py scanner.py flask 2.3.0 3.0.0 --output markdown > report.md
Features
- Precise Diffs: Uses
griffe for semantic API diffs (functions, classes, params, types).
- Deprecation Detection: Parses
@deprecated, warnings.warn, and docstrings.
- Risk Scoring: Quantitative score based on removals/updates/deprecations.
- Migration Heuristics: Auto-generates notes for renames, sig changes, removals.
- Rich Output: Console (rich tables), Markdown, JSON (extensible).
- PyPI-Native: Downloads wheels on-the-fly, no local installs needed.
Example Output (Console)
# requests Upgrade Risk Report: 2.28.0 → 2.31.0
## Risk Summary
- Risk Score: 2/10 (LOW)
- Breaking Changes: 1
...
Limitations & Extensions
- Python-only: For npm/JS, adapt with
api-extractor or ts-morph.
- No Runtime Tests: Static only; pair with your test suite.
- Changelogs: Manually check PyPI/GitHub for official notes.
- Extend: Add
--test for smoke tests, GitHub changelog scraping, or multi-package scans.
- GitHub Fallback: Use
--github-repo https://github.com/org/repo for tags like v1.0.0.
This scanner catches 80%+ of upgrade pains upfront. Test it on your libs! 🚀