Cheer.MixTask (Cheer v0.2.0)

Copy Markdown View Source

Build a Mix task from a Cheer command.

use Cheer.MixTask combines use Mix.Task and use Cheer.Command and generates the Mix run/1 entry point. That entry point dispatches argv through the command with Cheer.run/3, using mix <task> as the program name in help and usage output, and translates a usage failure into exit({:shutdown, 2}), the Mix idiom for a nonzero exit.

Declare the command with the usual DSL and implement the leaf run/2:

defmodule Mix.Tasks.Greet do
  use Cheer.MixTask

  command "greet" do
    about "Greet someone"
    argument :name, type: :string, required: true
    option :loud, type: :boolean, short: :l
  end

  @impl Cheer.Command
  def run(%{name: name} = args, _raw) do
    greeting = "Hello, #{name}!"
    greeting = if args[:loud], do: String.upcase(greeting), else: greeting
    Mix.shell().info(greeting)
  end
end

Then mix greet world --loud parses, validates, and renders help exactly like a standalone CLI.

@shortdoc defaults to the command's about text when it is not set explicitly, so the task lists itself in mix help. Override run/1 if the task needs to do its own setup (such as Mix.Task.run("app.start")) before dispatching.

Do not use Cheer.main/3 in a Mix task: it calls System.halt, which hard-kills the VM and skips Mix's cleanup. This helper uses Cheer.run/3 and the exit idiom instead.