Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / screenshots-report.py
screenshots-report.py168 lines · 7.5 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Collect Compose screenshot (metadata) results and publish them to |
| 3 | https://git.maproj.org/screenshots (see location_share_server |
| 4 | handlers/screenshots). |
| 5 | |
| 6 | Modes: |
| 7 | (default) Collect the goldens already in metadata_data/photos/<module>/ |
| 8 | (e.g. after a `./gradlew :<module>:metadata` sweep someone ran). |
| 9 | A module with >=1 capture is `passed`; otherwise `failed` |
| 10 | with first_error "no captures collected". |
| 11 | --run First run `./gradlew :<gradle-path>:metadata` per module, |
| 12 | recording exit status + first error line, counting goldens |
| 13 | whose hash changed, then collect. Slow (full sweep). |
| 14 | |
| 15 | Upload (default, disable with --no-upload): |
| 16 | PUT {base}/c_password123/screenshots/gold/<run-id>/<module>/<bucket>/<file> |
| 17 | POST {base}/c_password123/screenshots/runs (the manifest) |
| 18 | The /c_password123 prefix is the server's existing unguessable admin |
| 19 | prefix — the same auth the tests/dependencies admin endpoints use; there |
| 20 | is no public write endpoint. Override base with --base or |
| 21 | SCREENSHOTS_BASE (e.g. http://127.0.0.1:8080 for a local server). |
| 22 | |
| 23 | Also always writes the manifest to --out (default /tmp/screenshots-run.json) |
| 24 | so the dataset can be inspected/re-uploaded without re-collecting. |
| 25 | """ |
| 26 | import argparse, hashlib, json, os, re, secrets, struct, subprocess, sys, time, urllib.request |
| 27 | from pathlib import Path |
| 28 | |
| 29 | BUCKETS = ["phone", "tablet", "large-tablet", "tv", "wear"] |
| 30 | ROOT = Path(__file__).resolve().parent.parent |
| 31 | |
| 32 | def png_size(p: Path): |
| 33 | try: |
| 34 | with p.open("rb") as f: |
| 35 | head = f.read(24) |
| 36 | if head[:8] == b"\x89PNG\r\n\x1a\n": |
| 37 | w, h = struct.unpack(">II", head[16:24]) |
| 38 | return w, h |
| 39 | except OSError: |
| 40 | pass |
| 41 | return 0, 0 |
| 42 | |
| 43 | def modules(): |
| 44 | """(module-key, gradle-path, dir) for apps applying preview-metadata.""" |
| 45 | out = [] |
| 46 | for bf in sorted(ROOT.rglob("build.gradle.kts")): |
| 47 | rel = bf.parent.relative_to(ROOT) |
| 48 | if any(part in ("build", ".git", "analysis", "personal") for part in rel.parts): |
| 49 | continue |
| 50 | try: |
| 51 | text = bf.read_text(errors="ignore") |
| 52 | except OSError: |
| 53 | continue |
| 54 | if 'id("common-conventions-preview-metadata")' not in text: |
| 55 | continue |
| 56 | key = str(rel).replace("/", "-") |
| 57 | gradle = ":" + str(rel).replace("/", ":") |
| 58 | out.append((key, gradle, bf.parent)) |
| 59 | return out |
| 60 | |
| 61 | def hashes(module_key): |
| 62 | base = ROOT / "metadata_data" / "photos" / module_key |
| 63 | h = {} |
| 64 | if base.is_dir(): |
| 65 | for p in base.rglob("*.png"): |
| 66 | h[str(p.relative_to(base))] = hashlib.sha256(p.read_bytes()).hexdigest() |
| 67 | return h |
| 68 | |
| 69 | def collect(module_key, status, first_error, regenerated): |
| 70 | base = ROOT / "metadata_data" / "photos" / module_key |
| 71 | captures = [] |
| 72 | if base.is_dir(): |
| 73 | for bucket in BUCKETS: |
| 74 | d = base / bucket |
| 75 | if not d.is_dir(): |
| 76 | continue |
| 77 | for p in sorted(d.glob("*.png")): |
| 78 | w, ht = png_size(p) |
| 79 | captures.append({"bucket": bucket, "file": p.name, "width": w, "height": ht, "bytes": p.stat().st_size}) |
| 80 | # Non-bucket goldens (e.g. camera.png) are not store captures; ignore. |
| 81 | if status is None: |
| 82 | status = "passed" if captures else "failed" |
| 83 | if not captures and not first_error: |
| 84 | first_error = "no captures collected" |
| 85 | return {"module": module_key, "gradle_path": "", "status": status, |
| 86 | "first_error": first_error, "captures": captures, "regenerated": regenerated} |
| 87 | |
| 88 | def first_error_line(output): |
| 89 | for line in output.splitlines(): |
| 90 | s = line.strip() |
| 91 | if re.search(r"(FAILED|FAILURE|Exception|error:|BUILD FAILED)", s): |
| 92 | return s[:500] |
| 93 | tail = [l.strip() for l in output.splitlines() if l.strip()] |
| 94 | return (tail[-1][:500] if tail else "gradle metadata failed") |
| 95 | |
| 96 | def main(): |
| 97 | ap = argparse.ArgumentParser() |
| 98 | ap.add_argument("--run", action="store_true", help="run :<module>:metadata per module first") |
| 99 | ap.add_argument("--no-upload", action="store_true") |
| 100 | ap.add_argument("--base", default=os.environ.get("SCREENSHOTS_BASE", "https://git.maproj.org")) |
| 101 | ap.add_argument("--out", default="/tmp/screenshots-run.json") |
| 102 | ap.add_argument("--only", default="", help="comma-separated module keys") |
| 103 | args = ap.parse_args() |
| 104 | |
| 105 | mods = modules() |
| 106 | if args.only: |
| 107 | want = set(args.only.split(",")) |
| 108 | mods = [m for m in mods if m[0] in want] |
| 109 | sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip() |
| 110 | subject = subprocess.run(["git", "log", "-1", "--format=%s"], cwd=ROOT, capture_output=True, text=True).stdout.strip() |
| 111 | run_id = secrets.token_hex(8) |
| 112 | results = [] |
| 113 | for key, gradle, _dir in mods: |
| 114 | status, err, regen = None, None, 0 |
| 115 | if args.run: |
| 116 | before = hashes(key) |
| 117 | proc = subprocess.run(["./gradlew", "--console=plain", f"{gradle}:metadata"], |
| 118 | cwd=ROOT, capture_output=True, text=True) |
| 119 | after = hashes(key) |
| 120 | regen = sum(1 for k, v in after.items() if before.get(k) != v) + sum(1 for k in before if k not in after) |
| 121 | if proc.returncode != 0: |
| 122 | status, err = "failed", first_error_line((proc.stdout or "") + (proc.stderr or "")) |
| 123 | else: |
| 124 | status = "passed" |
| 125 | print(f"{key}: {status} regenerated={regen}", flush=True) |
| 126 | else: |
| 127 | # Changed vs HEAD right now (0 on a clean tree). |
| 128 | dirty = subprocess.run(["git", "status", "--porcelain", "--", f"metadata_data/photos/{key}"], |
| 129 | cwd=ROOT, capture_output=True, text=True).stdout.strip() |
| 130 | regen = len([l for l in dirty.splitlines() if l.strip()]) if dirty else 0 |
| 131 | r = collect(key, status, err, regen) |
| 132 | r["gradle_path"] = gradle |
| 133 | results.append(r) |
| 134 | |
| 135 | run = {"id": run_id, "sha": sha, "subject": subject, "timestamp": int(time.time()), "modules": results} |
| 136 | Path(args.out).write_text(json.dumps(run, indent=1)) |
| 137 | passed = sum(1 for r in results if r["status"] == "passed") |
| 138 | print(f"run {run_id} sha={sha[:9]} modules={len(results)} passed={passed} failed={len(results)-passed} -> {args.out}") |
| 139 | if args.no_upload: |
| 140 | return 0 |
| 141 | |
| 142 | base = args.base.rstrip("/") |
| 143 | host_header = os.environ.get("SCREENSHOTS_HOST", "") |
| 144 | def req(method, url, data=None, ctype=None): |
| 145 | r = urllib.request.Request(url, data=data, method=method) |
| 146 | # Cloudflare rejects the default Python-urllib user agent (403); |
| 147 | # identify as the screenshots producer instead. |
| 148 | r.add_header("User-Agent", "screenshots-report/1.0") |
| 149 | if host_header: |
| 150 | r.add_header("Host", host_header) |
| 151 | if ctype: |
| 152 | r.add_header("Content-Type", ctype) |
| 153 | with urllib.request.urlopen(r, timeout=120) as resp: |
| 154 | return resp.status, resp.read() |
| 155 | n = 0 |
| 156 | for r in results: |
| 157 | for c in r["captures"]: |
| 158 | p = ROOT / "metadata_data" / "photos" / r["module"] / c["bucket"] / c["file"] |
| 159 | url = f"{base}/c_password123/screenshots/gold/{run_id}/{r['module']}/{c['bucket']}/{c['file']}" |
| 160 | req("PUT", url, data=p.read_bytes(), ctype="image/png") |
| 161 | n += 1 |
| 162 | status, _ = req("POST", f"{base}/c_password123/screenshots/runs", |
| 163 | data=json.dumps(run).encode(), ctype="application/json") |
| 164 | print(f"uploaded {n} goldens, manifest POST -> {status}; page: {base}/screenshots") |
| 165 | return 0 |
| 166 | |
| 167 | if __name__ == "__main__": |
| 168 | sys.exit(main()) |