import re
import sys
from pathlib import Path
REPO = "https://github.com/vitali87/croft"
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]:
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))