Creating custom Mix tasks
Sometimes, the existing Mix tasks just aren't enough. Fortunately, Mix allows the creation of customized tasks that integrate as if they were shipped with Mix itself. In this recipe, we will create a custom Mix task that will print the Erlang VM memory status.
How to do it…
The steps required to create a custom task are as follows:
- Create a new file,
meminfo.ex
, that defines theMeminfo
module insideMix.Tasks
:defmodule Mix.Tasks.Meminfo do use Mix.Task end
- Add the new task description to be displayed when
mix help
is invoked:@shortdoc "Get Erlang VM memory usage information"
- Add the new task module documentation:
@moduledoc """ A mix custom task that outputs some information regarding the Erlang VM memory usage """
- Create a
run/1
function:def run(_) do meminfo = :erlang.memory IO.puts """ Total #{meminfo[:total]} Processes #{meminfo[:processes]} Processes (used) #{meminfo[:processes_used]} System #{meminfo[:system]} Atom #{meminfo[:atom]} Atom (used) #{meminfo[:atom_used]} Binary #{meminfo[:binary]} Code #{meminfo[:code]} ETS #{meminfo[:ets]} """ end
- Compile the code using the Elixir compiler,
elixirc
:elixirc meminfo.ex
No message should appear but a file named
Elixir.Mix.Tasks.Meminfo.beam
is created. - Run
mix help
to see the new task listed and its short description:> mix help mix # Run the default task (current: mix run) mix archive # List all archives (…) mix meminfo # Get Erlang VM memory usage information mix new # Create a new Elixir project mix run # Run the given file or expression mix test # Run a project's tests iex -S mix # Start IEx and run the default task
- Execute the custom task:
> mix meminfo Total 17692216 Processes 4778984 Processes (used) 4777656 System 12913232 Atom 339441 Atom (used) 321302 Binary 14152 Code 8136817 ETS 452832
How it works…
Mix tasks are just modules that are declared as Mix.Tasks.<MODULENAME>
with a run
function defined.
In meminfo.ex
, we use the Mix.Task
module by declaring use Mix.Task
. The use
directive allows us to use a given module in the current context.
The @shortdoc
attribute allows us to define a short description to display when some help on Mix or the mix.task
is displayed.
The run/1
function is the place where all of the task's work is done. In this particular case, we use an Erlang function to return a keyword list with several entries, and print them for the user in a formatted way.