返回 CodeWhale
check-crate-sizes.py
根目录 / scripts / release / check-crate-sizes.py
1 #!/usr/bin/env python3
2 """Refuse release tarballs that exceed crates.io's 10 MiB upload limit.
3
4 crates.io answers an oversized upload with HTTP 413 only when the upload
5 happens, which can strand a release half-published: v0.10.1 uploaded 26
6 crates, then codewhale-tui was refused at 11.93 MiB compressed before its
7 dependent codewhale-cli could follow. The packaging step already builds
8 every tarball (`cargo publish --dry-run` stages them under
9 Cargo's build-directory `package/tmp-registry/`, `cargo package` writes
10 `package/` there); this checks those files so the refusal happens before the
11 first real upload, at dry-run time as well as publish time.
12
13 Usage: check-crate-sizes.py <crate> [<crate> ...]
14 """
15
16 from __future__ import annotations
17
18 import json
19 import subprocess
20 import sys
21 import tarfile
22 from pathlib import Path
23
24 # crates.io's own number, verbatim: "max upload size is: 10485760".
25 LIMIT_BYTES = 10 * 1024 * 1024
26 # Notice before the wall: codewhale-tui went from 8.94 MiB (0.10.0) to
27 # 11.93 MiB (0.10.1, refused) in one cycle. Warn at 90% so a release has a
28 # cycle to act instead of a failed publish.
29 WARN_BYTES = LIMIT_BYTES * 90 // 100
30
31
32 def main() -> int:
33 crates = sys.argv[1:]
34 if not crates:
35 print("usage: check-crate-sizes.py <crate> [<crate> ...]", file=sys.stderr)
36 return 2
37
38 metadata = subprocess.run(
39 ["cargo", "metadata", "--locked", "--format-version", "1", "--no-deps"],
40 check=False,
41 capture_output=True,
42 text=True,
43 )
44 if metadata.returncode != 0:
45 print("::error::cargo metadata failed; cannot locate release tarballs", file=sys.stderr)
46 print(metadata.stderr, file=sys.stderr)
47 return 1
48 parsed = json.loads(metadata.stdout)
49 target_directory = Path(parsed.get("build_directory") or parsed["target_directory"])
50 versions = {package["name"]: package["version"] for package in parsed["packages"]}
51
52 root = Path(parsed["workspace_root"])
53 notices = {name: (root / name).read_bytes() for name in ("LICENSE", "THIRD_PARTY_NOTICES.md", "docs/THIRD_PARTY_NOTICES.md")}
54 failures: list[str] = []
55 warnings: list[str] = []
56 for name in crates:
57 version = versions.get(name)
58 if version is None:
59 failures.append(f"{name}: not a workspace package in cargo metadata")
60 continue
61 candidates = [
62 target_directory / "package" / "tmp-registry" / f"{name}-{version}.crate",
63 target_directory / "package" / f"{name}-{version}.crate",
64 ]
65 tarball = next((candidate for candidate in candidates if candidate.is_file()), None)
66 if tarball is None:
67 failures.append(
68 f"{name}: no tarball at "
69 + " or ".join(str(candidate) for candidate in candidates)
70 + "; package the release crates first"
71 )
72 continue
73 with tarfile.open(tarball, "r:gz") as archive:
74 for document, expected in notices.items():
75 member = f"{name}-{version}/codewhale-notices/{document}"
76 try:
77 packed = archive.getmember(member)
78 except KeyError:
79 failures.append(f"{name}: missing {document} in package")
80 continue
81 if not packed.isfile() or archive.extractfile(packed).read() != expected:
82 failures.append(f"{name}: packaged {document} differs from release source")
83 size = tarball.stat().st_size
84 status = "ok"
85 if size > LIMIT_BYTES:
86 status = "OVER"
87 elif size > WARN_BYTES:
88 status = "close"
89 print(f" {status:>5} {name}-{version}.crate {size / 1048576:.2f} MiB")
90 if status == "OVER":
91 failures.append(
92 f"{name}: tarball is {size} bytes ({size / 1048576:.2f} MiB), over the "
93 f"crates.io limit of {LIMIT_BYTES} bytes (10 MiB). Trim the package "
94 "with `exclude` in its Cargo.toml."
95 )
96 elif status == "close":
97 warnings.append(
98 f"{name}: tarball is {size} bytes ({size / 1048576:.2f} MiB), "
99 f"{size * 100 // LIMIT_BYTES}% of the crates.io cap"
100 )
101
102 for warning in warnings:
103 print(f"::warning::{warning}", file=sys.stderr)
104 for failure in failures:
105 print(f"::error::{failure}", file=sys.stderr)
106 if failures:
107 return 1
108 print(
109 f"Release tarball sizes OK: all {len(crates)} crates under the "
110 f"crates.io {LIMIT_BYTES}-byte cap."
111 )
112 return 0
113
114
115 if __name__ == "__main__":
116 raise SystemExit(main())
117
117 lines PYTHON