Repository navigation
ci: preflight generated release bodies before publishing #1001
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| #!/usr/bin/env python3 | ||
| """Read-only preflight for a decoded cargo-dist announcement or final notes file. | ||
|
|
||
| Exit 0: pass/warning; 1: a size policy fails; 2: input/configuration error. | ||
| GitHub reports a 125,000-character maximum, without documenting its Unicode | ||
| unit. Code points are this check's explicit character-counting policy. The | ||
| optional UTF-8 budget is a conservative project policy, not an API byte limit. | ||
| No text is trimmed, normalized, truncated, published, or written by this tool. | ||
| Configuration checks require Python 3.11+; --check-dist-config prints the audited | ||
| version instead of a body report, for use by the installer step. | ||
| """ | ||
|
|
||
| import argparse | ||
| import hashlib | ||
| import json | ||
| import os | ||
| from pathlib import Path | ||
| import sys | ||
|
|
||
| GITHUB_MAX_CHARS = 125_000 | ||
| DEFAULT_WARN_AT = 120_000 | ||
| # Audit notes-file transport and release-job ordering before changing this pin. | ||
| AUDITED_DIST_VERSION = "0.31.0" | ||
| ENV_OVERHEAD = len(b"ANNOUNCEMENT_BODY=") + 1 # Include the terminating NUL. | ||
|
|
||
|
|
||
| def diagnostic(level, message): | ||
|
|
||
| # Keep untrusted paths/JSON diagnostics inside one workflow command. | ||
| message = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") | ||
| print(f"::{level}::{message}", file=sys.stderr) | ||
| else: | ||
| print(f"{level.upper()}: {message}", file=sys.stderr) | ||
|
|
||
|
|
||
| class PreflightParser(argparse.ArgumentParser): | ||
| def error(self, message): | ||
| self.print_usage(sys.stderr) | ||
| diagnostic("error", message) | ||
| self.exit(2) | ||
|
|
||
|
|
||
| def audited_dist_version(path): | ||
| try: | ||
| import tomllib | ||
| except ImportError as exc: | ||
| raise ValueError("cargo-dist configuration checks require Python 3.11+") from exc | ||
| config = tomllib.loads(path.read_bytes().decode("utf-8", errors="strict")) | ||
| dist = config.get("dist") | ||
| if not isinstance(dist, dict) or dist.get("cargo-dist-version") != AUDITED_DIST_VERSION: | ||
| raise ValueError("configured cargo-dist version must match audited version " | ||
| + AUDITED_DIST_VERSION | ||
| + "; review the notes transport before upgrading the audit pin") | ||
| return AUDITED_DIST_VERSION | ||
|
|
||
|
|
||
| def unique_object(pairs): | ||
| result = {} | ||
| for key, value in pairs: | ||
| if key in result: | ||
| raise ValueError("duplicate JSON key: " + json.dumps(key)) | ||
| result[key] = value | ||
| return result | ||
|
|
||
|
|
||
| def reject_constant(value): | ||
| raise ValueError("non-standard JSON constant: " + value) | ||
|
|
||
|
|
||
| def read_input(args): | ||
| source = args.manifest or args.notes_file | ||
| # read_text() would translate CRLF and could undercount a notes file. | ||
| raw = source.read_bytes().decode("utf-8", errors="strict") | ||
| metadata = {} | ||
| if args.manifest: | ||
| doc = json.loads(raw, object_pairs_hook=unique_object, | ||
| parse_constant=reject_constant) | ||
| if not isinstance(doc, dict): | ||
| raise ValueError("manifest must be a JSON object") | ||
| body = doc.get("announcement_github_body") | ||
| if args.require_changelog: | ||
| changelog = doc.get("announcement_changelog") | ||
| if not isinstance(changelog, str) or not changelog.strip(): | ||
| raise ValueError("manifest must contain a nonempty changelog") | ||
| for key, expected in (("announcement_tag", args.expected_tag), | ||
| ("dist_version", args.expected_dist_version)): | ||
| if expected is not None and doc.get(key) != expected: | ||
| raise ValueError(key + " does not match the expected value") | ||
| if key in doc: | ||
| if not isinstance(doc[key], str) or not doc[key]: | ||
| raise ValueError(key + " must be a nonempty string") | ||
| metadata[key] = doc[key] | ||
| else: | ||
| body = raw | ||
| if not isinstance(body, str) or not body.strip(): | ||
| raise ValueError("release body must be a nonempty, non-whitespace string") | ||
| if "\x00" in body: | ||
| raise ValueError("release body contains NUL, unsupported by the transport") | ||
| # json.loads permits lone escaped surrogates; valid UTF-8 does not. | ||
| body.encode("utf-8", errors="strict") | ||
| return body, metadata | ||
|
|
||
|
|
||
| def check(body, args, metadata): | ||
| submitted = body + ("\n" if args.append_final_lf else "") | ||
| encoded = submitted.encode("utf-8") | ||
| counts = { | ||
| "announcement_code_points": len(body), | ||
| "submitted_code_points": len(submitted), | ||
| "submitted_utf8_bytes": len(encoded), | ||
| "submitted_utf16_units": len(submitted.encode("utf-16-le")) // 2, | ||
| "submitted_sha256": hashlib.sha256(encoded).hexdigest(), | ||
| "headroom_code_points": args.max_chars - len(submitted), | ||
| } | ||
| if args.manifest: | ||
| counts["announcement_env_entry_bytes"] = ( | ||
| len(body.encode("utf-8")) + ENV_OVERHEAD | ||
| ) | ||
| errors = [] | ||
| warnings = [] | ||
| if len(submitted) > args.max_chars: | ||
| errors.append(f"Submitted body has {len(submitted):,} code points; " | ||
| f"maximum {args.max_chars:,}; remove at least " | ||
| f"{len(submitted) - args.max_chars:,} code points.") | ||
| if args.max_utf8_bytes is not None and len(encoded) > args.max_utf8_bytes: | ||
| errors.append(f"Submitted body has {len(encoded):,} UTF-8 bytes; " | ||
| f"project byte budget {args.max_utf8_bytes:,}.") | ||
| if args.max_env_bytes is not None: | ||
| env_size = counts["announcement_env_entry_bytes"] | ||
| if env_size > args.max_env_bytes: | ||
| errors.append(f"ANNOUNCEMENT_BODY environment entry is {env_size:,} " | ||
| f"bytes including name and NUL; transport maximum " | ||
| f"{args.max_env_bytes:,}.") | ||
| if not errors: | ||
| if len(submitted) >= args.warn_at: | ||
| warnings.append(f"Submitted body reached warning threshold " | ||
| f"{args.warn_at:,} code points; " | ||
| f"{counts['headroom_code_points']:,} remain.") | ||
| if (args.max_utf8_bytes is not None and len(encoded) >= args.warn_at): | ||
| warnings.append(f"Submitted body reached {args.warn_at:,} UTF-8 " | ||
| f"bytes; project byte-budget headroom is " | ||
| f"{args.max_utf8_bytes - len(encoded):,} bytes.") | ||
| return { | ||
| "status": "fail" if errors else "warn" if warnings else "pass", | ||
| "metadata": metadata, | ||
| "measurements": counts, | ||
| "policy": { | ||
| "max_code_points": args.max_chars, | ||
| "warn_at": args.warn_at, | ||
| "max_utf8_bytes": args.max_utf8_bytes, | ||
| "max_env_bytes": args.max_env_bytes, | ||
| "append_final_lf": args.append_final_lf, | ||
| }, | ||
| "errors": errors, | ||
| "warnings": warnings, | ||
| } | ||
|
|
||
|
|
||
| def main(argv=None): | ||
| parser = PreflightParser(description=__doc__) | ||
| source = parser.add_mutually_exclusive_group(required=True) | ||
| source.add_argument("--manifest", type=Path) | ||
| source.add_argument("--notes-file", type=Path) | ||
| source.add_argument("--check-dist-config", type=Path, | ||
| help="validate TOML against the audit pin and print its version") | ||
| parser.add_argument("--expected-tag") | ||
| parser.add_argument("--expected-dist-version") | ||
| parser.add_argument("--audited-dist-config", type=Path, | ||
| help="validate TOML and manifest against the shared audit pin") | ||
| parser.add_argument("--require-changelog", action="store_true", | ||
| help="reject an announcement containing only downloads") | ||
| parser.add_argument("--append-final-lf", action="store_true", | ||
| help="model the LF added by cargo-dist's audited echo transport") | ||
| parser.add_argument("--max-chars", type=int, | ||
| help="character ceiling (default: 125000)") | ||
| parser.add_argument("--warn-at", type=int, | ||
| help="warning threshold (default: min(120000, --max-chars))") | ||
| parser.add_argument("--max-utf8-bytes", type=int, | ||
| help="optional conservative project byte budget") | ||
| parser.add_argument("--max-env-bytes", type=int, | ||
| help="target Linux per-env-string cap, including NUL") | ||
| args = parser.parse_args(argv) | ||
| if args.check_dist_config: | ||
| if (args.expected_tag is not None or args.expected_dist_version is not None | ||
| or args.audited_dist_config is not None or args.require_changelog | ||
| or args.append_final_lf or args.max_chars is not None | ||
| or args.warn_at is not None or args.max_utf8_bytes is not None | ||
| or args.max_env_bytes is not None): | ||
| parser.error("--check-dist-config must be used without body-check options") | ||
| try: | ||
| print(audited_dist_version(args.check_dist_config)) | ||
| except (OSError, ValueError, UnicodeError) as exc: | ||
| diagnostic("error", "release-body preflight input error: " + str(exc)) | ||
| return 2 | ||
| return 0 | ||
| if args.max_chars is None: | ||
| args.max_chars = GITHUB_MAX_CHARS | ||
| if not 0 < args.max_chars <= GITHUB_MAX_CHARS: | ||
| parser.error("--max-chars must be between 1 and 125000") | ||
| if args.warn_at is None: | ||
| args.warn_at = min(DEFAULT_WARN_AT, args.max_chars) | ||
| if not 0 < args.warn_at <= args.max_chars: | ||
| parser.error("--warn-at must be positive and no greater than --max-chars") | ||
| for value in (args.max_utf8_bytes, args.max_env_bytes): | ||
| if value is not None and value <= 0: | ||
| parser.error("byte budgets must be positive") | ||
| if args.notes_file and (args.expected_tag is not None | ||
| or args.expected_dist_version is not None | ||
| or args.audited_dist_config is not None | ||
| or args.require_changelog | ||
| or args.append_final_lf | ||
| or args.max_env_bytes is not None): | ||
| parser.error("metadata, LF and environment options require --manifest") | ||
| if args.audited_dist_config is not None and args.expected_dist_version is not None: | ||
| parser.error("choose --audited-dist-config or --expected-dist-version, not both") | ||
| try: | ||
| if args.audited_dist_config is not None: | ||
| args.expected_dist_version = audited_dist_version(args.audited_dist_config) | ||
| body, metadata = read_input(args) | ||
| report = check(body, args, metadata) | ||
| except (OSError, ValueError, UnicodeError) as exc: | ||
| diagnostic("error", "release-body preflight input error: " + str(exc)) | ||
| return 2 | ||
| print(json.dumps(report, indent=2, ensure_ascii=True)) | ||
| counts = report["measurements"] | ||
| print(f"release-body preflight {report['status']}: " | ||
| f"{counts['submitted_code_points']:,}/{args.max_chars:,} code points, " | ||
| f"{counts['submitted_utf8_bytes']:,} UTF-8 bytes, " | ||
| f"{counts['headroom_code_points']:,} code-point headroom", file=sys.stderr) | ||
| for message in report["errors"]: | ||
| diagnostic("error", message) | ||
| for message in report["warnings"]: | ||
| diagnostic("warning", message) | ||
| return 1 if report["errors"] else 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while
2DA8
the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.