Buckets:

download
raw
7.49 kB
#!/usr/bin/env python3
"""
Coverage PR Comment Generator
Generates a formatted coverage report for GitHub PR comments.
Compares coverage between base and head branches.
"""
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional
import defusedxml.ElementTree as ET
@dataclass
class CoverageData:
"""Coverage data container"""
line_rate: float
branch_rate: float
lines_covered: int
lines_valid: int
branches_covered: int
branches_valid: int
packages: Dict[str, Dict]
def parse_coverage_xml(xml_path: str) -> CoverageData:
"""Parse coverage XML file generated by pytest-cov."""
tree = ET.parse(xml_path)
root = tree.getroot()
# Get overall coverage
line_rate = float(root.get("line-rate", 0))
branch_rate = float(root.get("branch-rate", 0))
lines_covered = int(root.get("lines-covered", 0))
lines_valid = int(root.get("lines-valid", 0))
branches_covered = int(root.get("branches-covered", 0))
branches_valid = int(root.get("branches-valid", 0))
# Parse package details
packages = {}
packages_elem = root.find("packages")
if packages_elem is not None:
for package in packages_elem.findall("package"):
pkg_name = package.get("name", "unknown")
pkg_line_rate = float(package.get("line-rate", 0))
pkg_branch_rate = float(package.get("branch-rate", 0))
packages[pkg_name] = {
"line_rate": pkg_line_rate,
"branch_rate": pkg_branch_rate,
"classes": [],
}
classes_elem = package.find("classes")
if classes_elem is not None:
for cls in classes_elem.findall("class"):
cls_name = cls.get("name", "unknown").split(".")[-1]
cls_line_rate = float(cls.get("line-rate", 0))
if cls_line_rate < 1.0: # Only show files with missing coverage
packages[pkg_name]["classes"].append({"name": cls_name, "line_rate": cls_line_rate})
return CoverageData(
line_rate=line_rate,
branch_rate=branch_rate,
lines_covered=lines_covered,
lines_valid=lines_valid,
branches_covered=branches_covered,
branches_valid=branches_valid,
packages=packages,
)
def generate_coverage_badge(coverage: float) -> str:
"""Generate a coverage badge emoji based on percentage."""
if coverage >= 0.9:
return "๐ŸŸข"
elif coverage >= 0.75:
return "๐ŸŸก"
elif coverage >= 0.5:
return "๐ŸŸ "
else:
return "๐Ÿ”ด"
def generate_pr_comment(
current: CoverageData,
previous: Optional[CoverageData] = None,
threshold: float = 0.75,
) -> str:
"""Generate formatted PR comment with coverage information."""
current_pct = current.line_rate * 100
threshold_pct = threshold * 100
# Calculate change
change_str = ""
if previous:
prev_pct = previous.line_rate * 100
change = current_pct - prev_pct
if change > 0:
change_str = f" (+{change:.2f}%) ๐Ÿ“ˆ"
elif change < 0:
change_str = f" ({change:.2f}%) ๐Ÿ“‰"
else:
change_str = " (ยฑ0.00%) โžก๏ธ"
# Status indicator
badge = generate_coverage_badge(current.line_rate)
status = "โœ… PASSED" if current.line_rate >= threshold else "โŒ FAILED"
comment = f"""## ๐Ÿ“Š Coverage Report
| Metric | Value | Threshold |
|--------|-------|-----------|
| {badge} **Line Coverage** | **{current_pct:.2f}%**{change_str} | {threshold_pct:.0f}% |
| ๐ŸŒฟ **Branch Coverage** | {current.branch_rate * 100:.2f}% | - |
| ๐Ÿ“ **Lines Covered** | {current.lines_covered:,} / {current.lines_valid:,} | - |
| ๐Ÿ”€ **Branches Covered** | {current.branches_covered:,} / {current.branches_valid:,} | - |
**Status:** {status}
---
"""
# Add package breakdown
if current.packages:
comment += "\n### ๐Ÿ“ฆ Coverage by Package\n\n"
comment += "| Package | Line Coverage | Status |\n"
comment += "|---------|--------------|--------|\n"
# Sort packages by coverage
sorted_packages = sorted(current.packages.items(), key=lambda x: x[1]["line_rate"])
for pkg_name, pkg_data in sorted_packages:
pkg_rate = pkg_data["line_rate"] * 100
pkg_badge = generate_coverage_badge(pkg_data["line_rate"])
comment += f"| {pkg_name} | {pkg_badge} {pkg_rate:.1f}% | {'โš ๏ธ' if pkg_rate < threshold_pct else 'โœ…'} |\n"
# Add files with low coverage
low_coverage_files = []
for pkg_name, pkg_data in current.packages.items():
for cls in pkg_data.get("classes", []):
if cls["line_rate"] < threshold:
low_coverage_files.append(
{
"package": pkg_name,
"class": cls["name"],
"coverage": cls["line_rate"] * 100,
}
)
if low_coverage_files:
comment += "\n### โš ๏ธ Files Below Threshold\n\n"
comment += "| File | Coverage |\n"
comment += "|------|----------|\n"
# Sort by coverage (lowest first)
low_coverage_files.sort(key=lambda x: x["coverage"])
# Show top 10
for file_info in low_coverage_files[:10]:
comment += f"| `{file_info['package']}.{file_info['class']}` | {file_info['coverage']:.1f}% |\n"
if len(low_coverage_files) > 10:
comment += f"\n*... and {len(low_coverage_files) - 10} more files*\n"
comment += """
---
*Generated by Coverage PR Comment Generator*
"""
return comment
def main():
"""Main entry point."""
import argparse
parser = argparse.ArgumentParser(description="Generate coverage PR comment")
parser.add_argument("coverage_xml", help="Path to coverage XML file")
parser.add_argument("--previous", help="Path to previous coverage XML for comparison")
parser.add_argument("--threshold", type=float, default=0.75, help="Coverage threshold")
parser.add_argument("--output", help="Output file path")
parser.add_argument(
"--github-action",
action="store_true",
help="Output for GitHub Actions",
)
args = parser.parse_args()
# Parse current coverage
if not Path(args.coverage_xml).exists():
print(
f"Error: Coverage file not found: {args.coverage_xml}",
file=sys.stderr,
)
sys.exit(1)
current = parse_coverage_xml(args.coverage_xml)
# Parse previous coverage if provided
previous = None
if args.previous and Path(args.previous).exists():
previous = parse_coverage_xml(args.previous)
# Generate comment
comment = generate_pr_comment(current, previous, args.threshold)
# Output
if args.output:
Path(args.output).write_text(comment)
print(f"Comment written to {args.output}")
else:
print(comment)
# GitHub Actions output
if args.github_action:
# Set outputs for GitHub Actions
print(f"::set-output name=coverage::{current.line_rate * 100:.2f}")
print(f"::set-output name=status::{'passed' if current.line_rate >= args.threshold else 'failed'}")
# Exit with error if below threshold
if current.line_rate < args.threshold:
sys.exit(1)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
7.49 kB
ยท
Xet hash:
6e5ea68743a18f3d5c0d64756bf01eae25e63d935b7b227a1c05cce0f61cd724

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.