sastri 0.1.0

Scaffold multi-ecosystem packaging and CI/CD for Rust CLIs (Homebrew, Scoop, PyPI, npm, Hex, mise, asdf, …)
Documentation
use anyhow::Result;
use heck::ToPascalCase;

use super::{GeneratedFile, Mechanism, MechanismContext, StepResult};

pub struct Hex;

impl Mechanism for Hex {
    fn id(&self) -> &'static str {
        "hex"
    }

    fn description(&self) -> &'static str {
        "packaging/hex Mix wrapper (downloads CLI; not a NIF)"
    }

    fn generate(&self, ctx: &MechanismContext<'_>) -> Result<StepResult> {
        let p = &ctx.config.project;
        let bin = &p.binary_name;
        let hex_name = ctx
            .config
            .org
            .hex_package
            .clone()
            .unwrap_or_else(|| bin.clone());
        let module = hex_name.to_pascal_case();
        let version = &p.version;
        let owner = &p.github_owner;
        let repo = &p.github_repo;
        let desc = &p.description;

        let mix = format!(
            r#"defmodule {module}.MixProject do
  use Mix.Project

  @version "{version}"

  def project do
    [
      app: :{hex_name},
      version: @version,
      elixir: "~> 1.15",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      description: description(),
      package: package(),
      docs: [
        main: "readme",
        extras: ["README.md"],
        source_url: "https://github.com/{owner}/{repo}"
      ]
    ]
  end

  def application do
    [extra_applications: [:logger]]
  end

  defp deps do
    [
      {{:req, "~> 0.5"}},
      {{:ex_doc, "~> 0.34", only: :dev, runtime: false}}
    ]
  end

  defp description do
    """
    Mix tasks for {bin} — downloads a prebuilt CLI from GitHub Releases (no Rust).
    {desc}
    """
  end

  defp package do
    [
      name: "{hex_name}",
      licenses: ["{license}"],
      links: %{{
        "GitHub" => "https://github.com/{owner}/{repo}"
      }},
      files: ~w(lib mix.exs README.md)
    ]
  end
end
"#,
            license = p.license,
        );

        let lib = format!(
            r#"defmodule {module} do
  @moduledoc """
  Manages the native `{bin}` CLI for Elixir projects.

  This Hex package downloads a prebuilt binary from GitHub Releases — it does
  **not** run the tool inside the BEAM.

      # mix.exs — not needed in production
      {{:{hex_name}, "~> {version}", only: [:dev, :test], runtime: false}}
  """

  @repo "{owner}/{repo}"
  @default_version "{version}"

  def version do
    Application.get_env(:{hex_name}, :version, @default_version)
    |> to_string()
    |> String.trim_leading("v")
  end

  def binary_path do
    name = if match?({{:win32, _}}, :os.type()), do: "{bin}.exe", else: "{bin}"
    Path.join([:code.priv_dir(:{hex_name}), "bin", name])
  end

  def ensure_binary! do
    case ensure_binary() do
      {{:ok, path}} -> path
      {{:error, reason}} -> Mix.raise("{bin}: #{{reason}}")
    end
  end

  def ensure_binary do
    path = binary_path()

    cond do
      Application.get_env(:{hex_name}, :path) ->
        custom = Application.get_env(:{hex_name}, :path)
        if File.exists?(custom), do: {{:ok, custom}}, else: {{:error, "configured :path not found"}}

      System.find_executable("{bin}") && Application.get_env(:{hex_name}, :prefer_path, false) ->
        {{:ok, System.find_executable("{bin}")}}

      File.exists?(path) ->
        {{:ok, path}}

      true ->
        download(path)
    end
  end

  defp download(dest) do
    {{os, arch}} = host_platform()
    tag = "v" <> version()
    ext = if os == "windows", do: "zip", else: "tar.gz"
    asset = "{bin}-#{{tag}}-#{{os}}-#{{arch}}.#{{ext}}"
    url = "https://github.com/#{{@repo}}/releases/download/#{{tag}}/#{{asset}}"
    decode = if os == "windows", do: &Req.ZIP.decode/1, else: &Req.Tar.decode/1

    Mix.shell().info("{bin}: downloading #{{url}}")
    {{:ok, _}} = Application.ensure_all_started(:req)

    case Req.get(url, decode_body: false, redirect: true) do
      {{:ok, %{{status: 200, body: body}}}} when is_binary(body) ->
        case decode.(body) do
          {{:ok, entries}} -> install_binary(entries, dest, if(os == "windows", do: "{bin}.exe", else: "{bin}"))
          {{:error, exception}} -> {{:error, Exception.message(exception)}}
        end

      {{:ok, %{{status: status}}}} ->
        {{:error, "download failed: HTTP #{{status}}"}}

      {{:error, exception}} ->
        {{:error, Exception.message(exception)}}
    end
  end

  defp install_binary(entries, dest, bin_name) do
    match =
      Enum.find(entries, fn {{name, _}} ->
        name |> to_string() |> Path.basename() == bin_name
      end)

    case match do
      {{_, contents}} ->
        File.mkdir_p!(Path.dirname(dest))
        File.write!(dest, contents)
        unless match?({{:win32, _}}, :os.type()), do: File.chmod!(dest, 0o755)
        {{:ok, dest}}

      nil ->
        {{:error, "archive missing #{{bin_name}}"}}
    end
  end

  defp host_platform do
    os =
      case :os.type() do
        {{:unix, :darwin}} -> "macos"
        {{:unix, _}} -> "linux"
        {{:win32, _}} -> "windows"
      end

    arch_string = :erlang.system_info(:system_architecture) |> to_string()

    arch =
      cond do
        String.contains?(arch_string, "aarch64") or String.contains?(arch_string, "arm64") ->
          "aarch64"

        String.starts_with?(arch_string, "x86_64") or arch_string in ["amd64", "x86_64"] ->
          "x86_64"

        true ->
          case System.cmd("uname", ["-m"], stderr_to_stdout: true) do
            {{"arm64\n", 0}} -> "aarch64"
            {{"aarch64\n", 0}} -> "aarch64"
            {{"x86_64\n", 0}} -> "x86_64"
            _ -> raise "{bin}: unsupported architecture #{{inspect(arch_string)}}"
          end
      end

    {{os, arch}}
  end
end
"#
        );

        let task = format!(
            r#"defmodule Mix.Tasks.{module} do
  @shortdoc "Run the {bin} CLI"
  @moduledoc "Forwards argv to the managed `{bin}` binary."
  use Mix.Task

  @impl true
  def run(args) do
    bin = {module}.ensure_binary!()
    forwarded = if args == [], do: ["--help"], else: args
    {{_, status}} = System.cmd(bin, forwarded, into: IO.stream(:stdio, :line))
    if status != 0, do: Mix.raise("{bin} exited with status #{{status}}")
  end
end
"#
        );

        let readme = format!(
            r#"# :{hex_name}

Mix wrapper for **{bin}**. Downloads a prebuilt CLI from GitHub Releases (no Rust).

```elixir
{{:{hex_name}, "~> {version}", only: [:dev, :test], runtime: false}}
```

```bash
mix deps.get
mix {hex_name} --version
```
"#
        );

        let base = format!(
            "{}/hex",
            ctx.config.paths.packaging_dir.trim_end_matches('/')
        );
        Ok(StepResult {
            files: vec![
                GeneratedFile {
                    relative_path: format!("{base}/mix.exs"),
                    contents: mix,
                    executable: false,
                },
                GeneratedFile {
                    relative_path: format!("{base}/lib/{hex_name}.ex"),
                    contents: lib,
                    executable: false,
                },
                GeneratedFile {
                    relative_path: format!("{base}/lib/mix/tasks/{hex_name}.ex"),
                    contents: task,
                    executable: false,
                },
                GeneratedFile {
                    relative_path: format!("{base}/README.md"),
                    contents: readme,
                    executable: false,
                },
            ],
            notes: vec![
                "Set HEX_API_KEY for mix hex.publish from packaging/hex.".into(),
                "Dev/test only dependency; runtime: false.".into(),
            ],
        })
    }
}