OptionParser
This module contains functions to parse command line options.
Summary
Types
Functions
- next(argv, opts \\ [])
-
Low-level function that parses one option
- parse(argv, opts \\ [])
-
Parses
argvinto a keywords list - parse!(argv, opts \\ [])
-
The same as
parse/2but raises anOptionParser.ParseErrorexception if any invalid options are given - parse_head(argv, opts \\ [])
-
Similar to
parse/2but only parses the head ofargv; as soon as it finds a non-switch, it stops parsing - parse_head!(argv, opts \\ [])
-
The same as
parse_head/2but raises anOptionParser.ParseErrorexception if any invalid options are given - split(string)
-
Splits a string into argv chunks
- to_argv(enum)
-
Receives a key-value enumerable and converts it to argv
Types
argv()
argv() :: [String.t]
errors()
errors() :: [{String.t, String.t | nil}] options()
options() :: [switches: Keyword.t, strict: Keyword.t, aliases: Keyword.t]
parsed()
parsed() :: Keyword.t
Functions
next(argv, opts \\ [])
next(argv, options) ::
{:ok, key :: atom, value :: term, argv} |
{:invalid, String.t, String.t | nil, argv} |
{:undefined, String.t, String.t | nil, argv} |
{:error, argv} Low-level function that parses one option.
It accepts the same options as parse/2 and parse_head/2 as both functions are built on top of this function. This function may return:
-
{:ok, key, value, rest}- the optionkeywithvaluewas successfully parsed -
{:invalid, key, value, rest}- the optionkeyis invalid withvalue(returned when the value cannot be parsed according to the switch type) -
{:undefined, key, value, rest}- the optionkeyis undefined (returned in strict mode when the switch is unknown) -
{:error, rest}- there are no switches at the head of the givenargv
parse(argv, opts \\ [])
parse(argv, options) :: {parsed, argv, errors} Parses argv into a keywords list.
It returns a three-element tuple with the form {parsed, args, invalid}, where:
-
parsedis a keyword list of parsed switches with{switch_name, value}tuples in it;switch_nameis the atom representing the switch name whilevalueis the value for that switch parsed according toopts(see the “Examples” section for more information) -
argsis a list of the remaining arguments inargvas strings -
invalidis a list of invalid options as{option_name, value}whereoption_nameis the raw option andvalueisnilif the option wasn’t expected or the string value if the value didn’t have the expected type for the corresponding option
Elixir converts switches to underscored atoms, so --source-path becomes :source_path. This is done to better suit Elixir conventions. However, this means that switches can’t contain underscores and switches that do contain underscores are always returned in the list of invalid options.
Without any options, this function will try to parse all switches in the argv.
iex> OptionParser.parse(["--debug"])
{[debug: true], [], []}
iex> OptionParser.parse(["--source", "lib"])
{[source: "lib"], [], []}
iex> OptionParser.parse(["--source-path", "lib", "test/enum_test.exs", "--verbose"])
{[source_path: "lib", verbose: true], ["test/enum_test.exs"], []} Switches followed by a value will be assigned the value, as a string. Switches without an argument, like --debug in the examples above, will automatically be set to true.
Options
The following options are supported:
-
:switchesor:strict- see the “Switch definitions” section below -
:aliases- see the “Aliases” section below
Switch definitions
Often it is better to explicitly list the known switches and their formats. The switches can be specified via one of two options:
-
:switches- defines some switches and their types. This function still attempts to parse switches that are not in this list. -
:strict- defines strict switches. Any switch inargvthat is not specified in the list is returned in the invalid options list.
Both these options accept a keyword list of {name, type} tuples where name is an atom defining the name of the switch and type is an atom that specifies the type for the value of this switch (see the “Types” section below for the possible types and more information about type casting).
Note that you should only supply the :switches or :strict option. If you supply both, an ArgumentError exception will be raised.
Types
Switches parsed by OptionParser may take zero or one arguments.
The following switches types take no arguments:
-
:boolean- sets the value totruewhen given (see also the “Negation switches” section below) -
:count- counts the number of times the switch is given
The following switches take one argument:
-
:integer- parses the value as an integer -
:float- parses the value as a float -
:string- parses the value as a string
If a switch can’t be parsed according to the given type, it is returned in the invalid options list.
Modifiers
Switches can be specified with modifiers, which change how they behave. The following modifiers are supported:
-
:keep- keeps duplicated items instead of overriding them; works with all types except:count. Specifyingswitch_name: :keepassumes the type of:switch_namewill be:string.
Note that if you want to use :keep with a type other than :string, use a list as the type for the switch. For example: [foo: [:integer, :keep]].
Negation switches
In case a switch SWITCH is specified to have type :boolean, it may be passed as --no-SWITCH as well which will set the option to false:
iex> OptionParser.parse(["--no-op", "path/to/file"], switches: [op: :boolean])
{[op: false], ["path/to/file"], []} Aliases
A set of aliases can be specified in the :aliases option:
iex> OptionParser.parse(["-d"], aliases: [d: :debug])
{[debug: true], [], []} Examples
Here are some examples of working with different types and modifiers:
iex> OptionParser.parse(["--unlock", "path/to/file"], strict: [unlock: :boolean])
{[unlock: true], ["path/to/file"], []}
iex> OptionParser.parse(["--unlock", "--limit", "0", "path/to/file"],
...> strict: [unlock: :boolean, limit: :integer])
{[unlock: true, limit: 0], ["path/to/file"], []}
iex> OptionParser.parse(["--limit", "3"], strict: [limit: :integer])
{[limit: 3], [], []}
iex> OptionParser.parse(["--limit", "xyz"], strict: [limit: :integer])
{[], [], [{"--limit", "xyz"}]}
iex> OptionParser.parse(["--verbose"], switches: [verbose: :count])
{[verbose: 1], [], []}
iex> OptionParser.parse(["-v", "-v"], aliases: [v: :verbose], strict: [verbose: :count])
{[verbose: 2], [], []}
iex> OptionParser.parse(["--unknown", "xyz"], strict: [])
{[], ["xyz"], [{"--unknown", nil}]}
iex> OptionParser.parse(["--limit", "3", "--unknown", "xyz"],
...> switches: [limit: :integer])
{[limit: 3, unknown: "xyz"], [], []}
iex> OptionParser.parse(["--unlock", "path/to/file", "--unlock", "path/to/another/file"], strict: [unlock: :keep])
{[unlock: "path/to/file", unlock: "path/to/another/file"], [], []} parse!(argv, opts \\ [])
parse!(argv, options) :: {parsed, argv} | no_return The same as parse/2 but raises an OptionParser.ParseError exception if any invalid options are given.
If there are no errors, returns a {parsed, rest} tuple where:
-
parsedis the list of parsed switches (same as inparse/2) -
restis the list of arguments (same as inparse/2)
Examples
iex> OptionParser.parse!(["--debug", "path/to/file"], strict: [debug: :boolean])
{[debug: true], ["path/to/file"]}
iex> OptionParser.parse!(["--limit", "xyz"], strict: [limit: :integer])
** (OptionParser.ParseError) 1 error found!
--limit : Expected type integer, got "xyz"
iex> OptionParser.parse!(["--unknown", "xyz"], strict: [])
** (OptionParser.ParseError) 1 error found!
--unknown : Unknown option
iex> OptionParser.parse!(["-l", "xyz", "-f", "bar"],
...> switches: [limit: :integer, foo: :integer], aliases: [l: :limit, f: :foo])
** (OptionParser.ParseError) 2 errors found!
-l : Expected type integer, got "xyz"
-f : Expected type integer, got "bar" parse_head(argv, opts \\ [])
parse_head(argv, options) :: {parsed, argv, errors} Similar to parse/2 but only parses the head of argv; as soon as it finds a non-switch, it stops parsing.
See parse/2 for more information.
Example
iex> OptionParser.parse_head(["--source", "lib", "test/enum_test.exs", "--verbose"])
{[source: "lib"], ["test/enum_test.exs", "--verbose"], []}
iex> OptionParser.parse_head(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"])
{[verbose: true, source: "lib"], ["test/enum_test.exs", "--unlock"], []} parse_head!(argv, opts \\ [])
parse_head!(argv, options) :: {parsed, argv} | no_return The same as parse_head/2 but raises an OptionParser.ParseError exception if any invalid options are given.
If there are no errors, returns a {parsed, rest} tuple where:
-
parsedis the list of parsed switches (same as inparse_head/2) -
restis the list of arguments (same as inparse_head/2)
Examples
iex> OptionParser.parse_head!(["--source", "lib", "path/to/file", "--verbose"])
{[source: "lib"], ["path/to/file", "--verbose"]}
iex> OptionParser.parse_head!(["--number", "lib", "test/enum_test.exs", "--verbose"], strict: [number: :integer])
** (OptionParser.ParseError) 1 error found!
--number : Expected type integer, got "lib"
iex> OptionParser.parse_head!(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
...> strict: [verbose: :integer, source: :integer])
** (OptionParser.ParseError) 2 errors found!
--verbose : Missing argument of type integer
--source : Expected type integer, got "lib" split(string)
split(String.t) :: argv
Splits a string into argv chunks.
This function splits the given string into a list of strings in a similar way to many shells.
Examples
iex> OptionParser.split("foo bar")
["foo", "bar"]
iex> OptionParser.split("foo \"bar baz\"")
["foo", "bar baz"] to_argv(enum)
to_argv(Enumerable.t) :: argv
Receives a key-value enumerable and converts it to argv.
Keys must be atoms. Keys with nil value are discarded, boolean values are converted to --key or --no-key (if the value is true or false, respectively), and all other values are converted using to_string/1.
Examples
iex> OptionParser.to_argv([foo_bar: "baz"]) ["--foo-bar", "baz"] iex> OptionParser.to_argv([bool: true, bool: false, discarded: nil]) ["--bool", "--no-bool"]
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.3.4/OptionParser.html