Prompt.Command behaviour (prompt v0.5.11) View Source
Helps users define and build command line commands.
Defines the behaviour for a Command.
We expect init/1
to be called with the command line options and get
back a data structure that is passed to parse/1
which handles all
of the side effects of the command itself.
Example
defmodule MyCommand do
@moduledoc "MyCommand's help message help() is defined in the __using__ macro that prints this message if called"
use Prompt.Command
@impl true
def init(args) do
# parse list of args to map or struct
%{list: true, help: false, directory: "path/to/dir"}
end
@impl true
def process(%{help: true}), do: help() # this help function is defined by default in the macro that prints the @moduledoc when called
def process(%{list: true, help: false, directory: dir}) do
display(File.ls!(dir))
end
end
Typically one will use the OptionParser.parse/1
function to parse
the command
defp parse(argv) do
argv
|> OptionParser.parse(
strict: [help: :boolean, directory: :string, list: :boolean],
aliases: [h: :help, d: :directory]
)
|> _parse()
end
defp _parse({opts, _, _}) do
help = Keyword.get(opts, :help, false)
dir = Keyword.get(opts, :directory, "./")
list = Keyword.get(opts, :length, true)
%{help: help, directory: dir, list: list}
end
If this is used in a release, help()
won't print the @moduledoc correctly because releases strip documentation by default. For this to work correctly, tell the release to keep docs:
releases: [
appname: [
strip_beams: [keep: ["Docs"]]
]
]
Link to this section Summary
Callbacks
Prints the help available for this command
Takes the options passed in via the command line and tramforms them into a struct that the process command can handle
Processes the command and does the things required
Link to this section Callbacks
Specs
help() :: :ok
Prints the help available for this command
Specs
Takes the options passed in via the command line and tramforms them into a struct that the process command can handle
Specs
Processes the command and does the things required