OptionParser
This module contains functions to parse command line arguments.
Summary
| parse(argv, opts \\ []) | Parses |
| parse_head(argv, opts \\ []) | Similar to |
Functions
Parses argv and returns a tuple with the parsed options, its
arguments, and a list options that couldn't be parsed.
Examples
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"], [] }
Notice how Elixir automatically translates the "--source-path"
switch to the underscored atom :source_path, which better follows
Elixir conventions.
Aliases
A set of aliases can be given as the second argument:
iex> OptionParser.parse(["-d"], aliases: [d: :debug])
{ [debug: true], [], [] }
Switches
Extra information about switches can be given as arguments, too. This is useful when a switch must behave as a boolean or if duplicated switches should be kept, overridden or accumulated.
The following types are supported:
:boolean- Marks the given switch as a boolean. Boolean switches never consume the following value unless it istrueorfalse;:integer- Parses the switch as an integer;:float- Parses the switch as a float;
If a switch can't be parsed, the option is returned in the invalid options list (third element of the returned tuple).
The following extra options are supported:
:keep- Keeps duplicated items in the list instead of overriding;
Examples:
iex> OptionParser.parse(["--unlock", "path/to/file"], switches: [unlock: :boolean])
{ [unlock: true], ["path/to/file"], [] }
iex> OptionParser.parse(["--unlock", "--limit", "0", "path/to/file"],
...> switches: [unlock: :boolean, limit: :integer])
{ [unlock: true, limit: 0], ["path/to/file"], [] }
iex> OptionParser.parse(["-limit", "3"], switches: [limit: :integer])
{ [limit: 3], [], [] }
iex> OptionParser.parse(["-limit", "yyz"], switches: [limit: :integer])
{ [], [], [limit: "yyz"] }
Negation switches
Any switches starting with --no- are always considered to be
booleans and never parse the next value:
iex> OptionParser.parse(["--no-op", "path/to/file"])
{ [no_op: true], ["path/to/file"], [] }
In case the negated switch exists as a boolean, it sets the boolean to false:
iex> OptionParser.parse(["--no-op", "path/to/file"], switches: [op: :boolean])
{ [op: false], ["path/to/file"], [] }
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"], [] }