|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Guardrail script that keeps Cargo-produced WASM modules aligned with the Earthly |
| 4 | +artifact names we publish from each module directory. |
| 5 | +
|
| 6 | +It crawls every `Cargo.toml`, looks for `cdylib` targets (the only ones that |
| 7 | +output `.wasm`), extracts the declared library name, and compares it with the |
| 8 | +first Earthly `--out=...` or `SAVE ARTIFACT ...` directive found nearby. |
| 9 | +
|
| 10 | +Any mismatch causes a non-zero exit code so CI/just/earthly targets can enforce |
| 11 | +the contract described in the `Cargo.toml` comments. |
| 12 | +""" |
| 13 | + |
| 14 | +import re |
| 15 | +import sys |
| 16 | +import tomllib |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +ROOT = Path(__file__).resolve().parents[2] |
| 20 | +# Regex captures artifact names from statements like `--out=foo.wasm` or |
| 21 | +# `SAVE ARTIFACT ... foo.wasm`. |
| 22 | +EARTHLY_RE = re.compile(r"(?:--out=|SAVE ARTIFACT )([A-Za-z0-9_-]+)\.wasm") |
| 23 | + |
| 24 | + |
| 25 | +def earthly_name(dir): |
| 26 | + """Extract the WASM artifact name from the module's Earthfile.""" |
| 27 | + ef = dir / "Earthfile" |
| 28 | + if not ef.exists(): |
| 29 | + return None |
| 30 | + match = EARTHLY_RE.search(ef.read_text()) |
| 31 | + return match.group(1) if match else None |
| 32 | + |
| 33 | + |
| 34 | +def cargo_name(path): |
| 35 | + """Return the cdylib name declared in Cargo.toml, if any.""" |
| 36 | + data = tomllib.loads(path.read_text()) |
| 37 | + lib = data.get("lib", {}) |
| 38 | + # Only modules compiled as `cdylib` produce WASM artifacts we care about. |
| 39 | + if "cdylib" not in lib.get("crate-type", []): |
| 40 | + return None |
| 41 | + return lib.get("name") or data["package"]["name"] |
| 42 | + |
| 43 | + |
| 44 | +def normalize(name: str | None): |
| 45 | + if not name: |
| 46 | + return None |
| 47 | + # Earthly (snake_case) and Cargo (kebab-case) often differ only by |
| 48 | + # punctuation; normalize both sides before comparing. |
| 49 | + return name.replace("-", "_").lower() |
| 50 | + |
| 51 | + |
| 52 | +errors = [] |
| 53 | +for cargo in ROOT.rglob("Cargo.toml"): |
| 54 | + name = cargo_name(cargo) |
| 55 | + if not name: |
| 56 | + continue |
| 57 | + e_name = earthly_name(cargo.parent) |
| 58 | + # Only flag an error when both sources provide a name and the normalized |
| 59 | + # identifiers still differ. (Missing Earthfile entries are ignored so the |
| 60 | + # script can be run in repos that mix Rust and non-Rust modules.) |
| 61 | + if e_name and normalize(e_name) != normalize(name): |
| 62 | + errors.append(f"{cargo.parent}: Cargo '{name}' vs Earthly '{e_name}'") |
| 63 | + |
| 64 | +if errors: |
| 65 | + print("\n".join(errors)) |
| 66 | + sys.exit(1) |
0 commit comments