Questions, menus and progress lines for command-line programs, drawn in place below the shell prompt. No alternate screen, no app module, no widgets.
alias Drafter.Prompt
with {:ok, name} <- Prompt.text("Project name", default: "my_app"),
{:ok, kind} <- Prompt.select("Template", ["Phoenix", "Escript", "Library"]),
{:ok, extras} <- Prompt.multiselect("Extras", ["Credo", "Dialyxir", "ExDoc"]),
{:ok, true} <- Prompt.confirm("Create it?") do
Prompt.spinner("Creating #{name}", fn -> create(name, kind, extras) end)
endFunctions
text/2,password/2,number/2— one line of typed inputconfirm/2— yes or noselect/3,multiselect/3,search/3— pick from a listreadline/2— a bare input line with history and Tab completion, for a command loopform/1— several questions, answered into one mapspinner/3,progress/4— a moving line while work runssay/2— a status linerun/2— a prompt of your own, written as aDrafter.Prompt.Component
Results
Every question returns {:ok, value} or {:error, reason}, where reason is a
reason/0. Each has a ! twin that returns the value and raises
Drafter.Prompt.Stopped instead. spinner/3 and progress/4 return what the work
returned.
Without a terminal
When standard input is not a terminal, or TERM is dumb, nothing is drawn. Each
question is written as one line and answered by one line of standard input, so a
program can be driven by a pipe:
printf 'my_app\n2\n\ny\n' | my_tool newA list is answered by the number of an entry, several by numbers separated by commas, and an empty line gives the default. Spinners and progress bars write only their final line.
Reading input elsewhere
After the first question asked on a terminal, standard input is read through
Drafter.Terminal.Stdin for the rest of the run. Ask later questions through this
module; IO.gets/1 would compete with it for keys.
Appearance
Colours come from the active Drafter.Theme and symbols from the active skin; see
Drafter.Prompt.Style. Every function takes style: with overrides for
Drafter.Prompt.Style.current/1.
Testing
Drafter.Prompt.Script.run/3 runs code that asks questions against a list of keys.
Summary
Types
One entry of form/1: a tuple naming a question function of this module followed
by its arguments, a function from the answers so far to such a tuple, or :skip.
Why a question ended without an answer.
Functions
Ask a yes or no question.
As confirm/2, returning the answer or raising Drafter.Prompt.Stopped.
Ask several questions and return the answers as a map.
As form/1, returning the answers or raising Drafter.Prompt.Stopped.
Pick any number of entries from a list.
As multiselect/3, returning the answer or raising Drafter.Prompt.Stopped.
Ask for a number.
As number/2, returning the answer or raising Drafter.Prompt.Stopped.
Ask for a secret. Typed characters are shown as *.
As password/2, returning the answer or raising Drafter.Prompt.Stopped.
Show a progress bar beside label while work runs.
Read one line after prompt, as a shell does.
As readline/2, returning the line or raising Drafter.Prompt.Stopped.
Run a prompt component with opts and return its value.
Write a status line: a symbol for kind, then message.
Pick one entry from a list that depends on what the user types.
As search/3, returning the answer or raising Drafter.Prompt.Stopped.
Pick one entry from a list.
As select/3, returning the answer or raising Drafter.Prompt.Stopped.
Show a spinner beside label while work runs, and return what work returns.
Ask for one line of text.
As text/2, returning the answer or raising Drafter.Prompt.Stopped.
Types
@type question() :: {atom(), String.t()} | {atom(), String.t(), term()} | {atom(), String.t(), term(), keyword()} | :skip | (map() -> question())
One entry of form/1: a tuple naming a question function of this module followed
by its arguments, a function from the answers so far to such a tuple, or :skip.
@type reason() :: :cancelled | :interrupted | :eof | :not_a_terminal
Why a question ended without an answer.
:cancelled- Esc was pressed:interrupted- Ctrl+C was pressed:eof- Ctrl+D was pressed on an empty line, or standard input ended:not_a_terminal- there is no terminal and the prompt cannot be answered by a line of input
@type result(value) :: {:ok, value} | {:error, reason()}
Functions
Ask a yes or no question.
Drafter.Prompt.confirm("Overwrite the file?", default: false)
#=> {:ok, false}:default is the answer Enter gives, true unless set.
As confirm/2, returning the answer or raising Drafter.Prompt.Stopped.
Ask several questions and return the answers as a map.
Drafter.Prompt.form(
name: {:text, "Project name", default: "my_app"},
kind: {:select, "Template", ["Phoenix", "Escript"]},
port: fn
%{kind: "Phoenix"} -> {:number, "Port", default: 4000}
_answers -> :skip
end,
go: {:confirm, "Create it?"}
)
#=> {:ok, %{name: "my_app", kind: "Phoenix", port: 4000, go: true}}Each entry is a question/0, asked in order. A function receives the answers so
far and returns the question to ask, or :skip to leave its key out. The first
question that ends without an answer ends the form with its {:error, reason}.
As form/1, returning the answers or raising Drafter.Prompt.Stopped.
@spec multiselect(String.t(), [Drafter.Prompt.Choice.input()], keyword()) :: result([term()])
Pick any number of entries from a list.
Drafter.Prompt.multiselect("Extras", ["Credo", "Dialyxir", "ExDoc"], default: ["Credo"])
#=> {:ok, ["Credo", "ExDoc"]}The result holds the picked values in the order of the list.
Options
:default- the values picked first:minand:max- the fewest and most entries that may be picked:filterand:limit, as inselect/3
@spec multiselect!(String.t(), [Drafter.Prompt.Choice.input()], keyword()) :: [term()]
As multiselect/3, returning the answer or raising Drafter.Prompt.Stopped.
Ask for a number.
Drafter.Prompt.number("Port", default: 4000, min: 1, max: 65_535)
#=> {:ok, 4000}Options
:float-trueaccepts a decimal and returns a float. Defaultfalse, which returns an integer:minand:max- the smallest and largest number accepted:default,:placeholderand:validate, as intext/2;:validatereceives the number
As number/2, returning the answer or raising Drafter.Prompt.Stopped.
Ask for a secret. Typed characters are shown as *.
Takes the options of text/2, and :mask to change the character shown.
As password/2, returning the answer or raising Drafter.Prompt.Stopped.
Show a progress bar beside label while work runs.
With a list or other enumerable, work is called with each element, the bar moves
one step per element, and the results are returned as a list:
Drafter.Prompt.progress("Resizing", images, fn image -> resize(image) end)With a number of steps, work is called once with a function that moves the bar by
the steps it is given, and what work returns is returned:
Drafter.Prompt.progress("Downloading", byte_size, fn advance ->
download(fn chunk -> advance.(byte_size(chunk)) end)
end)Output, failure and :interval behave as in spinner/3.
Read one line after prompt, as a shell does.
def loop(history) do
case Drafter.Prompt.readline("db> ", history: history, complete: ["select", "insert", "quit"]) do
{:ok, "quit"} ->
:ok
{:ok, line} ->
run(line)
loop([line | history])
{:error, _reason} ->
:ok
end
endThe line is left on screen as typed. Takes the options of text/2.
As readline/2, returning the line or raising Drafter.Prompt.Stopped.
Run a prompt component with opts and return its value.
component implements Drafter.Prompt.Component. opts is passed to its
Drafter.Prompt.Component.init/1.
@spec say(:info | :success | :warning | :error, String.t()) :: :ok
Write a status line: a symbol for kind, then message.
Drafter.Prompt.say(:success, "Created my_app")kind is :info, :success, :warning or :error. The line goes to standard
output, coloured when standard output is a terminal.
@spec search(String.t(), (String.t() -> [Drafter.Prompt.Choice.input()]), keyword()) :: result(term())
Pick one entry from a list that depends on what the user types.
Drafter.Prompt.search("Package", fn query -> Hex.search(query) end)source is called with the typed text, first with "", and returns the entries to
list. It runs in the calling process on every change to the text.
@spec search!(String.t(), (String.t() -> [Drafter.Prompt.Choice.input()]), keyword()) :: term()
As search/3, returning the answer or raising Drafter.Prompt.Stopped.
@spec select(String.t(), [Drafter.Prompt.Choice.input()], keyword()) :: result(term())
Pick one entry from a list.
Drafter.Prompt.select("Template", ["Phoenix", "Escript", {"Plain library", :library}])
#=> {:ok, :library}Each entry is anything Drafter.Prompt.Choice.new/1 accepts; the result is the
picked entry's value.
Options
:default- the value highlighted first:filter-truenarrows the list as the user types:limit- the most entries shown at once
See Drafter.Prompt.Select for the keys.
@spec select!(String.t(), [Drafter.Prompt.Choice.input()], keyword()) :: term()
As select/3, returning the answer or raising Drafter.Prompt.Stopped.
@spec spinner(String.t(), (-> result) | ((String.t() -> :ok) -> result), keyword()) :: result when result: var
Show a spinner beside label while work runs, and return what work returns.
Drafter.Prompt.spinner("Fetching dependencies", fn -> fetch() end)
Drafter.Prompt.spinner("Building", fn status ->
compile()
status.("Linking")
link()
end)work runs in the calling process. Given one argument, it receives a function that
changes the label. What work writes to standard output appears above the spinner.
The line ends with a done mark, or a failed mark when work raises, exits or throws,
which then continues to the caller.
:interval sets the milliseconds between redraws, 80 unless
config :drafter, prompt_interval: says otherwise.
Ask for one line of text.
Drafter.Prompt.text("Project name", default: "my_app")
#=> {:ok, "my_app"}Options
:default- returned when the line is submitted empty:placeholder- dimmed text shown while the line is empty:validate-(value -> :ok | {:error, message}). A rejected line stays open withmessageunder it:complete- Tab completion: a list of words, or a function from the text before the cursor to candidates. SeeDrafter.Prompt.Completion:history- earlier answers, newest first, recalled with Up and Down
See Drafter.Prompt.Text for the keys.
As text/2, returning the answer or raising Drafter.Prompt.Stopped.