| 1 | #!/usr/bin/env python3 |
| 2 | """Validate the maintained crates.io publication order against Cargo metadata. |
| 3 | |
| 4 | On success, emit the workspace inventory consumed by publish-crates.sh. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import argparse |
| 10 | import json |
| 11 | import subprocess |
| 12 | import sys |
| 13 | from pathlib import Path |
| 14 | from typing import Any |
| 15 | |
| 16 | |
| 17 | INDEPENDENT_VERSION_CRATES = {"codewhale-ratatui"} |
| 18 | |
| 19 | |
| 20 | class ValidationError(Exception): |
| 21 | """A release-order or Cargo metadata contract violation.""" |
| 22 | |
| 23 | |
| 24 | def parse_args() -> argparse.Namespace: |
| 25 | parser = argparse.ArgumentParser() |
| 26 | parser.add_argument( |
| 27 | "--metadata-file", |
| 28 | type=Path, |
| 29 | help="Read Cargo metadata from this file instead of invoking cargo (tests only).", |
| 30 | ) |
| 31 | parser.add_argument("crates", nargs="+", help="Maintained publication order") |
| 32 | return parser.parse_args() |
| 33 | |
| 34 | |
| 35 | def load_metadata(metadata_file: Path | None) -> dict[str, Any]: |
| 36 | if metadata_file is not None: |
| 37 | try: |
| 38 | raw = metadata_file.read_text(encoding="utf-8") |
| 39 | except OSError as error: |
| 40 | raise ValidationError(f"could not read Cargo metadata: {error}") from error |
| 41 | else: |
| 42 | process = subprocess.run( |
| 43 | ["cargo", "metadata", "--locked", "--format-version", "1", "--no-deps"], |
| 44 | check=False, |
| 45 | capture_output=True, |
| 46 | text=True, |
| 47 | ) |
| 48 | if process.returncode != 0: |
| 49 | detail = process.stderr.strip() |
| 50 | suffix = f": {detail}" if detail else "" |
| 51 | raise ValidationError( |
| 52 | f"cargo metadata failed with exit code {process.returncode}{suffix}" |
| 53 | ) |
| 54 | raw = process.stdout |
| 55 | |
| 56 | try: |
| 57 | metadata = json.loads(raw) |
| 58 | except json.JSONDecodeError as error: |
| 59 | raise ValidationError(f"Cargo metadata is not valid JSON: {error}") from error |
| 60 | if not isinstance(metadata, dict): |
| 61 | raise ValidationError("Cargo metadata root must be an object") |
| 62 | return metadata |
| 63 | |
| 64 | |
| 65 | def workspace_packages(metadata: dict[str, Any]) -> list[dict[str, Any]]: |
| 66 | members = metadata.get("workspace_members") |
| 67 | packages = metadata.get("packages") |
| 68 | if not isinstance(members, list) or not isinstance(packages, list): |
| 69 | raise ValidationError("Cargo metadata must contain workspace_members and packages lists") |
| 70 | |
| 71 | packages_by_id = { |
| 72 | package.get("id"): package |
| 73 | for package in packages |
| 74 | if isinstance(package, dict) and isinstance(package.get("id"), str) |
| 75 | } |
| 76 | missing_ids = [member for member in members if member not in packages_by_id] |
| 77 | if missing_ids: |
| 78 | raise ValidationError( |
| 79 | "Cargo metadata omits workspace package ids: " + ", ".join(missing_ids) |
| 80 | ) |
| 81 | return [packages_by_id[member] for member in members] |
| 82 | |
| 83 | |
| 84 | def validate_order( |
| 85 | packages: list[dict[str, Any]], ordered_crates: list[str] |
| 86 | ) -> tuple[str, dict[str, bool], dict[str, str]]: |
| 87 | duplicate_crates = sorted( |
| 88 | {name for name in ordered_crates if ordered_crates.count(name) > 1} |
| 89 | ) |
| 90 | if duplicate_crates: |
| 91 | raise ValidationError( |
| 92 | "publish package list contains duplicates: " + ", ".join(duplicate_crates) |
| 93 | ) |
| 94 | |
| 95 | names = [package.get("name") for package in packages] |
| 96 | if any(not isinstance(name, str) or not name for name in names): |
| 97 | raise ValidationError("workspace package is missing a name") |
| 98 | if len(set(names)) != len(names): |
| 99 | raise ValidationError("Cargo metadata contains duplicate workspace package names") |
| 100 | |
| 101 | independent_versions = { |
| 102 | package["name"]: package.get("version") |
| 103 | for package in packages |
| 104 | if package["name"] in INDEPENDENT_VERSION_CRATES |
| 105 | } |
| 106 | for name, own_version in independent_versions.items(): |
| 107 | if not isinstance(own_version, str) or not own_version: |
| 108 | raise ValidationError(f"{name} has no version") |
| 109 | versions = sorted( |
| 110 | { |
| 111 | package.get("version") |
| 112 | for package in packages |
| 113 | if package["name"] not in INDEPENDENT_VERSION_CRATES |
| 114 | } |
| 115 | ) |
| 116 | if len(versions) != 1 or not isinstance(versions[0], str) or not versions[0]: |
| 117 | rendered = ", ".join(str(version) for version in versions) |
| 118 | raise ValidationError(f"workspace packages have mixed versions: {rendered}") |
| 119 | |
| 120 | workspace_by_name = {package["name"]: package for package in packages} |
| 121 | # `cargo metadata` renders `publish = false` as an empty registry list. |
| 122 | # Such a crate cannot be published, so demanding it appear in the publish |
| 123 | # order is a contradiction: `crates.sh` drives `cargo publish`, which would |
| 124 | # refuse it. Vendored, workspace-internal crates live here. |
| 125 | release_names = sorted( |
| 126 | name |
| 127 | for name, package in workspace_by_name.items() |
| 128 | if name.startswith("codewhale-") and package.get("publish") != [] |
| 129 | ) |
| 130 | ordered_set = set(ordered_crates) |
| 131 | missing = sorted(set(release_names) - ordered_set) |
| 132 | extra = sorted(ordered_set - set(release_names)) |
| 133 | if missing or extra: |
| 134 | messages = [] |
| 135 | if missing: |
| 136 | messages.append("publish package list is missing workspace crates: " + " ".join(missing)) |
| 137 | if extra: |
| 138 | messages.append( |
| 139 | "publish package list contains non-workspace crates: " + " ".join(extra) |
| 140 | ) |
| 141 | raise ValidationError("\n".join(messages)) |
| 142 | |
| 143 | positions = {name: index for index, name in enumerate(ordered_crates)} |
| 144 | has_workspace_dependencies = {name: False for name in release_names} |
| 145 | publish_edges: set[tuple[str, str, str]] = set() |
| 146 | for dependent in release_names: |
| 147 | dependencies = workspace_by_name[dependent].get("dependencies", []) |
| 148 | if not isinstance(dependencies, list): |
| 149 | raise ValidationError(f"Cargo metadata dependencies for {dependent} must be a list") |
| 150 | for dependency in dependencies: |
| 151 | if not isinstance(dependency, dict) or dependency.get("path") is None: |
| 152 | continue |
| 153 | dependency_name = dependency.get("name") |
| 154 | if dependency_name not in workspace_by_name: |
| 155 | continue |
| 156 | has_workspace_dependencies[dependent] = True |
| 157 | kind = dependency.get("kind") or "normal" |
| 158 | # Cargo does not compile dev-dependencies while verifying a publish. |
| 159 | # They may legitimately point back across the publication DAG. |
| 160 | if kind == "dev": |
| 161 | continue |
| 162 | if dependency_name not in positions: |
| 163 | raise ValidationError( |
| 164 | f"{dependent} depends on workspace crate {dependency_name} " |
| 165 | f"[{kind}], which is not in the codewhale-* release inventory" |
| 166 | ) |
| 167 | publish_edges.add((dependency_name, dependent, str(kind))) |
| 168 | |
| 169 | violations = sorted( |
| 170 | ( |
| 171 | dependency, |
| 172 | dependent, |
| 173 | kind, |
| 174 | ) |
| 175 | for dependency, dependent, kind in publish_edges |
| 176 | if positions[dependency] >= positions[dependent] |
| 177 | ) |
| 178 | if violations: |
| 179 | lines = ["crate publication order is not topological:"] |
| 180 | for dependency, dependent, kind in violations: |
| 181 | lines.append( |
| 182 | f" {dependent} (position {positions[dependent] + 1}) depends on " |
| 183 | f"{dependency} (position {positions[dependency] + 1}) [{kind}]" |
| 184 | ) |
| 185 | lines.append( |
| 186 | "Move every workspace dependency before its dependent in " |
| 187 | "scripts/release/crates.sh." |
| 188 | ) |
| 189 | raise ValidationError("\n".join(lines)) |
| 190 | |
| 191 | return versions[0], has_workspace_dependencies, independent_versions |
| 192 | |
| 193 | |
| 194 | def main() -> int: |
| 195 | args = parse_args() |
| 196 | try: |
| 197 | metadata = load_metadata(args.metadata_file) |
| 198 | packages = workspace_packages(metadata) |
| 199 | version, dependency_flags, independent_versions = validate_order(packages, args.crates) |
| 200 | except ValidationError as error: |
| 201 | print(error, file=sys.stderr) |
| 202 | return 1 |
| 203 | |
| 204 | print(f"version\t{version}\t") |
| 205 | for name in sorted(independent_versions): |
| 206 | print(f"own-version\t{name}\t{independent_versions[name]}") |
| 207 | build_directory = metadata.get("build_directory") or metadata.get("target_directory") |
| 208 | if isinstance(build_directory, str) and build_directory: |
| 209 | print(f"build-dir\t{build_directory}\t") |
| 210 | for name in sorted(dependency_flags): |
| 211 | print(f"crate\t{name}\t{1 if dependency_flags[name] else 0}") |
| 212 | return 0 |
| 213 | |
| 214 | |
| 215 | if __name__ == "__main__": |
| 216 | raise SystemExit(main()) |
| 217 |