wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
"""Record, check, survey, and verify a workspace release candidate.

- ``record`` describes the packaged archives, and retains them beside the record.
- ``check`` requires archives to match a record, before anything is published.
- ``survey`` asks crates.io about every crate and writes the workflow decision.
- ``verify`` downloads the published archives and compares their digests.
- ``digests`` writes the candidate's digests for lading.
- ``check-rehearsal`` requires an acceptable lading outcome for each crate.

No command takes a credential: lading publishes, in a step of its own.
Behavioural coverage lives in
``scripts/release/tests/test_release_workspace_cli.py``.
"""

import argparse
import collections.abc as cabc
import functools
import pathlib
import sys
import time

import crates_io_registry_http
import rehearsal_report
import verify_crates_io_bytes
import workspace_candidate
from release_workspace_policy import (
    SurveyError,
    plan_publication,
    plan_rehearsal,
    verify_published,
)
from release_workspace_registry import CrateState, Registry, observe_download, survey
from workspace_candidate import Candidate, CandidateError, Expectation

EXIT_OK = 0
EXIT_REFUSED = 1


def _live_registry() -> Registry:
    """Return the allowlisted HTTP opener and real retry delay."""
    return Registry(crates_io_registry_http.default_opener, time.sleep)


def build_parser() -> argparse.ArgumentParser:
    """Build the parser for the workspace release commands."""
    parser = argparse.ArgumentParser(prog="release_workspace_cli")
    commands = parser.add_subparsers(dest="command", required=True)
    for name, summary in (
        ("record", "describe the packaged archives"),
        ("check", "require archives to match a record"),
        ("survey", "check crates.io and write the decision to --github-output"),
        ("verify", "compare the published archives with a record"),
        ("digests", "write a record's digests for lading's --expect-digests"),
        ("check-rehearsal", "check lading's archive summary against the candidate"),
    ):
        command = commands.add_parser(name, help=summary)
        command.add_argument("--candidate", required=True, type=pathlib.Path)
        if name in {"record", "check"}:
            command.add_argument(
                "--package-directory", required=True, type=pathlib.Path
            )
            command.add_argument("--commit", required=True)
            command.add_argument("--tag", default="")
        if name == "record":
            command.add_argument(
                "--workspace-root", default=pathlib.Path(), type=pathlib.Path
            )
        if name == "survey":
            command.add_argument("--github-output", required=True, type=pathlib.Path)
        if name == "digests":
            command.add_argument("--output", required=True, type=pathlib.Path)
        if name == "check-rehearsal":
            command.add_argument("--report", required=True, type=pathlib.Path)
    return parser


def _run(arguments: argparse.Namespace, registry: Registry) -> None:
    """Run one parsed command."""
    if arguments.command == "record":
        candidate = workspace_candidate.record_candidate(
            arguments.workspace_root,
            arguments.package_directory,
            Expectation(arguments.commit, arguments.tag),
        )
        workspace_candidate.retain_archives(
            candidate, arguments.package_directory, arguments.candidate.parent
        )
        workspace_candidate.write_candidate(candidate, arguments.candidate)
        return
    candidate = workspace_candidate.read_candidate(arguments.candidate)
    if arguments.command == "check":
        workspace_candidate.check_candidate(
            candidate,
            arguments.package_directory,
            Expectation(arguments.commit, arguments.tag),
        )
    elif arguments.command == "digests":
        text = workspace_candidate.expected_digests(candidate)
        arguments.output.write_text(text, encoding="utf-8")
    elif arguments.command == "check-rehearsal":
        report = arguments.report.read_text(encoding="utf-8")
        rehearsal_report.check_rehearsal_report(candidate, report)
    elif arguments.command == "survey":
        _run_survey(candidate, registry, arguments.github_output)
    else:
        download = functools.partial(observe_download, registry=registry)
        for crate in verify_published(candidate, download):
            print(f"{crate.filename}: published bytes match {crate.sha256}")


def _report_registry_failures(observed: cabc.Mapping[str, CrateState]) -> None:
    """Explain crates whose registry state could not be determined."""
    for name, crate_state in observed.items():
        if crate_state.reason:
            print(f"{name}: {crate_state.reason}", file=sys.stderr)


def _write_action_output(path: pathlib.Path, *, action: str, version: str) -> None:
    """Append the release decision to GitHub Actions' output file."""
    with path.open("a", encoding="utf-8") as output:
        output.write(f"action={action}\nversion={version}\n")


def _run_survey(
    candidate: Candidate, registry: Registry, github_output: pathlib.Path
) -> None:
    """Survey crates.io, report why any crate was unreadable, and plan the run.

    Raises
    ------
    SurveyError
        If observation fails or the registry refuses a tagged release.
    """
    observed = survey(candidate, registry)
    _report_registry_failures(observed)
    states = {name: crate_state.state for name, crate_state in observed.items()}
    plan = plan_publication if candidate.tag else plan_rehearsal
    action = plan(states)
    logged = {name: state.value for name, state in states.items()}
    print(f"registry states: {logged}; action: {action}")
    _write_action_output(github_output, action=action, version=candidate.version)


def main(argv: list[str] | None = None, *, registry: Registry | None = None) -> int:
    """Run one command and return its exit code.

    Parameters
    ----------
    argv
        Command-line arguments. Defaults to ``sys.argv[1:]``.
    registry
        Network boundary. Defaults to crates.io.

    Returns
    -------
    int
        ``EXIT_OK``, or ``EXIT_REFUSED`` with the reason on standard error.
    """
    arguments = build_parser().parse_args(argv)
    try:
        _run(arguments, registry or _live_registry())
    except (
        CandidateError,
        SurveyError,
        UnicodeError,
        verify_crates_io_bytes.VerificationError,
        OSError,
    ) as error:
        print(f"::error title=Release candidate::{error}", file=sys.stderr)
        return EXIT_REFUSED
    return EXIT_OK


if __name__ == "__main__":
    raise SystemExit(main())