source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 48s
236 lines
8.1 KiB
Python
236 lines
8.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate self-contained shields-style SVG badges into badges/.
|
|
|
|
Main CI regenerates SVGs from measured metrics and publishes them to the
|
|
private ci-badges branch. The README loads those authenticated raw artifacts.
|
|
|
|
Usage:
|
|
gen-badges.py --tests N --coverage PCT --bench "label" [--out badges]
|
|
|
|
Metrics not passed on the command line are computed here (LOC from the source
|
|
tree, dependency count from Cargo.lock, license from Cargo.toml).
|
|
"""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
|
|
# Approximate per-character width at 11px DejaVu Sans, in 1/10 px, matching the
|
|
# shields "flat" look closely enough for a fixed-width monospace-ish render.
|
|
CHAR_W = 6.5
|
|
PAD = 6.0
|
|
|
|
COLORS = {
|
|
"green": "#4c1",
|
|
"brightgreen": "#4c1",
|
|
"yellowgreen": "#a4a61d",
|
|
"yellow": "#dfb317",
|
|
"orange": "#fe7d37",
|
|
"red": "#e05d44",
|
|
"blue": "#007ec6",
|
|
"lightgrey": "#9f9f9f",
|
|
"grey": "#555",
|
|
}
|
|
|
|
|
|
def text_width(s: str) -> float:
|
|
return len(s) * CHAR_W + 2 * PAD
|
|
|
|
|
|
def badge_svg(label: str, message: str, color: str,
|
|
description: str | None = None) -> str:
|
|
color = COLORS.get(color, color)
|
|
lw = round(text_width(label), 1)
|
|
mw = round(text_width(message), 1)
|
|
total = round(lw + mw, 1)
|
|
lx = round(lw / 2, 1)
|
|
mx = round(lw + mw / 2, 1)
|
|
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
|
|
description = description or f"{label}: {message}"
|
|
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{description}">
|
|
<title>{description}</title>
|
|
<linearGradient id="s" x2="0" y2="100%">
|
|
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
|
<stop offset="1" stop-opacity=".1"/>
|
|
</linearGradient>
|
|
<clipPath id="r"><rect width="{total}" height="20" rx="3" fill="#fff"/></clipPath>
|
|
<g clip-path="url(#r)">
|
|
<rect width="{lw}" height="20" fill="#555"/>
|
|
<rect x="{lw}" width="{mw}" height="20" fill="{color}"/>
|
|
<rect width="{total}" height="20" fill="url(#s)"/>
|
|
</g>
|
|
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
|
<text x="{lx}" y="15" fill="#010101" fill-opacity=".3">{label}</text>
|
|
<text x="{lx}" y="14">{label}</text>
|
|
<text x="{mx}" y="15" fill="#010101" fill-opacity=".3">{message}</text>
|
|
<text x="{mx}" y="14">{message}</text>
|
|
</g>
|
|
</svg>
|
|
'''
|
|
|
|
|
|
def count_loc(root: str) -> int:
|
|
total = 0
|
|
for base in ("crates",):
|
|
for dirpath, _dirs, files in os.walk(os.path.join(root, base)):
|
|
for f in files:
|
|
if f.endswith(".rs"):
|
|
try:
|
|
with open(os.path.join(dirpath, f), encoding="utf-8", errors="ignore") as fh:
|
|
total += sum(1 for _ in fh)
|
|
except OSError:
|
|
pass
|
|
return total
|
|
|
|
|
|
def count_deps(root: str) -> int:
|
|
lock = os.path.join(root, "Cargo.lock")
|
|
try:
|
|
with open(lock, encoding="utf-8") as fh:
|
|
return sum(1 for line in fh if line.startswith("name = "))
|
|
except OSError:
|
|
return 0
|
|
|
|
|
|
def read_license(root: str) -> str:
|
|
try:
|
|
with open(os.path.join(root, "Cargo.toml"), encoding="utf-8") as fh:
|
|
for line in fh:
|
|
m = re.match(r'\s*license\s*=\s*"([^"]+)"', line)
|
|
if m:
|
|
return m.group(1)
|
|
except OSError:
|
|
pass
|
|
return "unknown"
|
|
|
|
|
|
def loc_color(n: int) -> str:
|
|
return "blue"
|
|
|
|
|
|
def bench_color(delta_pct: float) -> str:
|
|
# Positive delta means faster than the previous release. A +/-2% band
|
|
# absorbs run-to-run jitter on the dedicated CI runner.
|
|
if delta_pct >= 2.0:
|
|
return "brightgreen"
|
|
if delta_pct > -2.0:
|
|
return "blue"
|
|
if delta_pct > -10.0:
|
|
return "yellow"
|
|
return "orange"
|
|
|
|
|
|
def cov_color(pct: float) -> str:
|
|
if pct >= 80:
|
|
return "brightgreen"
|
|
if pct >= 60:
|
|
return "yellowgreen"
|
|
if pct >= 40:
|
|
return "yellow"
|
|
if pct >= 20:
|
|
return "orange"
|
|
return "red"
|
|
|
|
|
|
def quality_grade(clippy: str | None) -> str:
|
|
if clippy is None:
|
|
return "pending"
|
|
return "A" if clippy == "clean" else "F"
|
|
|
|
|
|
def human(n: int) -> str:
|
|
suffixes = ("", "K", "M", "G")
|
|
value = float(n)
|
|
index = 0
|
|
while value >= 999.5 and index < len(suffixes) - 1:
|
|
value /= 1000
|
|
index += 1
|
|
if value >= 100:
|
|
number = f"{value:.0f}"
|
|
elif value >= 10:
|
|
number = f"{value:.1f}".rstrip("0").rstrip(".")
|
|
else:
|
|
number = f"{value:.2f}".rstrip("0").rstrip(".")
|
|
return number + suffixes[index]
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--out", default="badges")
|
|
ap.add_argument("--root", default=".")
|
|
ap.add_argument("--tests", type=int, default=None)
|
|
ap.add_argument("--coverage", type=float, default=None)
|
|
ap.add_argument("--bench-coverage", type=float, default=None)
|
|
ap.add_argument("--bench", default=None)
|
|
# Mean per-benchmark improvement vs the previous release, as a signed
|
|
# percentage string, or "NEW" when there is no baseline.
|
|
ap.add_argument("--bench-delta", default=None)
|
|
ap.add_argument("--clippy", choices=("clean", "failed"))
|
|
args = ap.parse_args()
|
|
for value in (args.coverage, args.bench_coverage):
|
|
if value is not None and (not math.isfinite(value) or not 0 <= value <= 100):
|
|
ap.error("coverage must be a finite percentage between 0 and 100")
|
|
|
|
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
|
|
|
|
def write(name, label, message, color, description=None):
|
|
path = os.path.join(args.root, args.out, name + ".svg")
|
|
with open(path, "w", encoding="utf-8") as fh:
|
|
fh.write(badge_svg(label, message, color, description))
|
|
print(f"wrote {path}: {label}={message}")
|
|
|
|
loc = count_loc(args.root)
|
|
deps = count_deps(args.root)
|
|
lic = read_license(args.root)
|
|
|
|
write("loc", "lines of code", human(loc), loc_color(loc))
|
|
write("license", "license", lic, "blue")
|
|
write("dependencies", "dependencies", str(deps), "blue")
|
|
grade = quality_grade(args.clippy)
|
|
write("quality", "code quality", grade,
|
|
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
|
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
|
|
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
|
|
if args.tests is not None:
|
|
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
|
if args.coverage is not None:
|
|
write("coverage", "coverage", f"{args.coverage:.0f}%", cov_color(args.coverage))
|
|
write("bench-coverage", "bench coverage",
|
|
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
|
|
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
|
|
context_path = Path(args.root) / args.out / "bench-context.json"
|
|
same_inputs = False
|
|
if context_path.is_file():
|
|
context = json.loads(context_path.read_text())
|
|
if (not isinstance(context, dict) or context.get("schema") != 1 or
|
|
not isinstance(context.get("same_inputs"), bool)):
|
|
raise ValueError("invalid benchmark comparison context")
|
|
same_inputs = context["same_inputs"]
|
|
# Bench badge: prefer the mean per-benchmark improvement vs the previous
|
|
# release. Use the static label when no comparison is available.
|
|
delta = None
|
|
if args.bench_delta not in (None, "", "NEW"):
|
|
try:
|
|
delta = float(args.bench_delta)
|
|
except ValueError:
|
|
delta = None
|
|
if delta is not None:
|
|
# Positive = faster than the previous release.
|
|
msg = f"{'+' if delta > 0 else ''}{delta:.1f}%"
|
|
if same_inputs:
|
|
write("bench", "bench", msg + " same inputs", "lightgrey")
|
|
else:
|
|
write("bench", "bench", msg + " vs prev", bench_color(delta))
|
|
elif args.bench_delta == "NEW":
|
|
write("bench", "bench", "baseline set", "blue")
|
|
elif args.bench is not None:
|
|
write("bench", "bench", args.bench, "blue")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|