croft-software 0.2.3

VSCode-style TUI written in Rust
"""The Homebrew formula generator (#375) must refuse a release it cannot fully
describe, and must describe exactly the archives release.yml publishes."""

import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(ROOT / "scripts"))

import check_binstall_contract  # noqa: E402
import homebrew_formula as hf  # noqa: E402

TARGETS = [t for _, _, t in hf.PLATFORMS]


def sums(targets=TARGETS, sep="  "):
    """A SHA256SUMS as sha256sum writes it, one distinct digest per target."""
    return "".join(
        f"{i:064x}{sep}{hf.archive(t)}\n" for i, t in enumerate(targets, start=1)
    )


class Render(unittest.TestCase):
    def test_each_platform_gets_its_own_archive_and_sum(self):
        formula = hf.render("0.1.1044", sums())
        for i, (_, arch, target) in enumerate(hf.PLATFORMS, start=1):
            url = (
                f"{hf.REPO}/releases/download/v0.1.1044/croft-{target}.tar.gz"
            )
            block = f'    {arch} do\n      url "{url}"\n      sha256 "{i:064x}"\n'
            self.assertIn(block, formula)
        self.assertIn('version "0.1.1044"', formula)
        self.assertIn('bin.install "croft"', formula)

    def test_macos_and_linux_blocks_hold_their_own_targets(self):
        formula = hf.render("1.2.3", sums())
        macos, linux = formula.split("  on_linux do")
        self.assertIn("apple-darwin", macos)
        self.assertNotIn("linux-musl", macos)
        self.assertIn("linux-musl", linux)
        self.assertNotIn("apple-darwin", linux)

    def test_binary_mode_sum_lines_are_accepted(self):
        # `sha256sum -b` and `shasum -a 256 -b` mark the name with `*`.
        self.assertIn("sha256", hf.render("1.2.3", sums(sep=" *")))

    def test_a_missing_archive_is_refused(self):
        with self.assertRaisesRegex(hf.FormulaError, "aarch64-apple-darwin"):
            hf.render("1.2.3", sums(TARGETS[1:]))

    def test_a_duplicated_archive_is_refused(self):
        with self.assertRaisesRegex(hf.FormulaError, "more than once"):
            hf.render("1.2.3", sums(TARGETS + TARGETS[:1]))

    def test_a_malformed_line_is_refused(self):
        with self.assertRaisesRegex(hf.FormulaError, "not a sha256sum line"):
            hf.render("1.2.3", sums() + "deadbeef  croft-extra.tar.gz\n")

    def test_a_tag_shaped_version_is_refused(self):
        # The workflow strips the `v`; passing the tag through would build
        # `.../download/vv1.2.3/...` URLs that 404.
        with self.assertRaisesRegex(hf.FormulaError, "not x.y.z"):
            hf.render("v1.2.3", sums())


class MatchesTheRelease(unittest.TestCase):
    def test_targets_are_the_release_matrix(self):
        workflow = (ROOT / ".github" / "workflows" / "release.yml").read_text()
        self.assertEqual(
            set(TARGETS), check_binstall_contract.matrix_targets(workflow)
        )

    def test_archive_names_match_the_package_step(self):
        workflow = (ROOT / ".github" / "workflows" / "release.yml").read_text()
        self.assertIn('name="croft-${{ matrix.target }}"', workflow)
        self.assertIn('tar -czf "dist/$name.tar.gz"', workflow)
        self.assertEqual(hf.archive("x"), "croft-x.tar.gz")

    def test_the_workflow_runs_the_generator(self):
        workflow = (ROOT / ".github" / "workflows" / "release.yml").read_text()
        self.assertTrue("scripts/homebrew_formula.py" in workflow)


class RubySyntax(unittest.TestCase):
    @unittest.skipUnless(shutil.which("ruby"), "ruby is not installed")
    def test_the_formula_parses_as_ruby(self):
        with tempfile.NamedTemporaryFile("w", suffix=".rb", delete=False) as f:
            f.write(hf.render("1.2.3", sums()))
        self.addCleanup(Path(f.name).unlink)
        r = subprocess.run(["ruby", "-c", f.name], capture_output=True, text=True)
        self.assertEqual(r.returncode, 0, r.stderr)


class Cli(unittest.TestCase):
    def run_cli(self, *args):
        return subprocess.run(
            [sys.executable, str(ROOT / "scripts" / "homebrew_formula.py"), *args],
            capture_output=True,
            text=True,
        )

    def test_writes_the_formula_and_exits_zero(self):
        with tempfile.NamedTemporaryFile("w", suffix="SUMS", delete=False) as f:
            f.write(sums())
        self.addCleanup(Path(f.name).unlink)
        r = self.run_cli("1.2.3", f.name)
        self.assertEqual(r.returncode, 0, r.stderr)
        self.assertTrue(r.stdout.startswith("# Generated by"))

    def test_an_incomplete_release_exits_nonzero_and_writes_nothing(self):
        with tempfile.NamedTemporaryFile("w", suffix="SUMS", delete=False) as f:
            f.write(sums(TARGETS[:3]))
        self.addCleanup(Path(f.name).unlink)
        r = self.run_cli("1.2.3", f.name)
        self.assertEqual(r.returncode, 1)
        self.assertEqual(r.stdout, "")
        self.assertIn("no sum for", r.stderr)


if __name__ == "__main__":
    unittest.main()