croft-software 0.2.3

VSCode-style TUI written in Rust
#!/usr/bin/env python3
"""Render the Homebrew formula for a tagged release (#375).

    python3 scripts/homebrew_formula.py <version> <SHA256SUMS> > croft.rb

The formula installs the prebuilt archive release.yml publishes for the
machine brew runs on (macOS arm64/x86_64, Linux arm64/x86_64), so
`brew install vitali87/croft/croft` needs no Rust toolchain. The URLs and
checksums come from the release's own SHA256SUMS, the same file cosign signs,
so the formula cannot point at bytes the release does not vouch for.

Fails, printing why, when SHA256SUMS does not name each of the four archives
exactly once with a well-formed sum: a formula with a missing platform would
install on some machines and 404 on others, which is worse than no bump.

The archive holds `croft-<target>/croft`. Homebrew steps into an archive's
single top-level directory before `install` runs, so `bin.install "croft"`
finds the binary without naming the target directory.
"""

import re
import sys
from pathlib import Path

REPO = "https://github.com/vitali87/croft"

# Each Homebrew platform block and the release target that serves it. The
# targets must stay the four release.yml builds; the tests check that against
# the workflow's matrix so a target added or renamed there cannot leave the
# formula pointing at an archive no release carries.
PLATFORMS = (
    ("on_macos", "on_arm", "aarch64-apple-darwin"),
    ("on_macos", "on_intel", "x86_64-apple-darwin"),
    ("on_linux", "on_arm", "aarch64-unknown-linux-musl"),
    ("on_linux", "on_intel", "x86_64-unknown-linux-musl"),
)

VERSION = re.compile(r"\d+\.\d+\.\d+")
SUM_LINE = re.compile(r"([0-9a-f]{64}) [ *](\S+)")


class FormulaError(Exception):
    pass


def archive(target: str) -> str:
    return f"croft-{target}.tar.gz"


def parse_sums(text: str) -> dict[str, str]:
    """Archive name to sha256, refusing anything but one sum per archive."""
    sums: dict[str, str] = {}
    for line in text.splitlines():
        if not line.strip():
            continue
        m = SUM_LINE.fullmatch(line.strip())
        if not m:
            raise FormulaError(f"not a sha256sum line: {line!r}")
        digest, name = m.groups()
        if name in sums:
            raise FormulaError(f"SHA256SUMS names {name} more than once")
        sums[name] = digest
    wanted = {archive(t) for _, _, t in PLATFORMS}
    missing = sorted(wanted - sums.keys())
    if missing:
        raise FormulaError(f"SHA256SUMS has no sum for {', '.join(missing)}")
    return sums


def render(version: str, sums_text: str) -> str:
    if not VERSION.fullmatch(version):
        raise FormulaError(f"version {version!r} is not x.y.z")
    sums = parse_sums(sums_text)
    out = [
        "# Generated by scripts/homebrew_formula.py in vitali87/croft; the",
        "# release workflow opens a pull request with each new version.",
        "class Croft < Formula",
        '  desc "VSCode-style TUI written in Rust"',
        f'  homepage "{REPO}"',
        f'  version "{version}"',
        '  license "MIT"',
        "",
    ]
    for os_block in ("on_macos", "on_linux"):
        out.append(f"  {os_block} do")
        for block, arch, target in PLATFORMS:
            if block != os_block:
                continue
            name = archive(target)
            out += [
                f"    {arch} do",
                f'      url "{REPO}/releases/download/v{version}/{name}"',
                f'      sha256 "{sums[name]}"',
                "    end",
            ]
        out += ["  end", ""]
    out += [
        "  def install",
        '    bin.install "croft"',
        "  end",
        "",
        "  test do",
        '    assert_match version.to_s, shell_output("#{bin}/croft --version")',
        "  end",
        "end",
    ]
    return "\n".join(out) + "\n"


def main(argv: list[str]) -> int:
    if len(argv) != 3:
        print(__doc__.strip().splitlines()[2].strip(), file=sys.stderr)
        return 2
    try:
        sys.stdout.write(render(argv[1], Path(argv[2]).read_text()))
    except (FormulaError, OSError) as e:
        print(f"homebrew_formula: {e}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))