diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 92e3a76..0000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*~ -*.luac diff --git a/doc/images/bg_hr.png b/doc/images/bg_hr.png deleted file mode 100644 index 7973bd6..0000000 Binary files a/doc/images/bg_hr.png and /dev/null differ diff --git a/doc/images/blacktocat.png b/doc/images/blacktocat.png deleted file mode 100644 index 6e264fe..0000000 Binary files a/doc/images/blacktocat.png and /dev/null differ diff --git a/doc/index.html b/doc/index.html deleted file mode 100644 index b15f87b..0000000 --- a/doc/index.html +++ /dev/null @@ -1,894 +0,0 @@ - - - - - - - - - - - Argparse tutorial - - - - - -
-
- View on GitHub - -

Argparse tutorial

-

-
-
- - -
-
-

-Creating a parser

- -

The module is a function which, when called, creates an instance of the Parser class.

- -
-- script.lua
-local argparse = require "argparse"
-local parser = argparse()
-
- -

parser is now an empty parser which does not recognize any command line arguments or options.

- -

-Parsing command line arguments

- -

:parse([cmdline]) method of the Parser class returns a table with processed data from the command line or cmdline array.

- -
local args = parser:parse()
-for k, v in pairs(args) do print(k, v) end
-
- -

When executed, this script prints nothing because the parser is empty and no command line arguments were supplied.

- -
$ lua script.lua
-
- -

-Error handling

- -

If the provided command line arguments are not recognized by the parser, it will print an error message and call os.exit(1).

- -
$ lua script.lua foo
-
- -
Usage: script.lua [-h]
-
-Error: too many arguments
-
- -

If halting the program is undesirable, :pparse([cmdline]) method should be used. It returns boolean flag indicating success of parsing and result or error message.

- -

An error can raised manually using :error() method.

- -
parser:error("manual argument validation failed")
-
- -
Usage: script.lua [-h]
-
-Error: manual argument validation failed
-
- -

-Help option

- -

As the automatically generated usage message states, there is a help option -h added to any parser by default.

- -

When a help option is used, parser will print a help message and call os.exit(0).

- -
$ lua script.lua -h
-
- -
Usage: script.lua [-h]
-
-Options: 
-   -h, --help            Show this help message and exit. 
-
- -

-Typo autocorrection

- -

When an option is not recognized by the parser, but there is an option with a similar name, a suggestion is automatically added to the error message.

- -
$ lua script.lua --hepl
-
- -
Usage: script.lua [-h]
-
-Error: unknown option '--hepl'
-Did you mean '--help'?
-
- -

-Configuring parser

- -

Parsers have several fields affecting their behavior. For example, description field sets the text to be displayed in the help message between the usage message and the listings of options and arguments. Another is name, which overwrites the name of the program which is used in the usage message(default value is inferred from command line arguments).

- -

There are several ways to set fields. The first is to call a parser with a table containing some fields.

- -
local parser = argparse() {
-   name = "script",
-   description = "A testing script. "
-}
-
- -

The second is to chain setter methods of Parser object.

- -
local parser = argparse()
-   :name "script"
-   :description "A testing script. "
-
- -

As a special case, name field can be set by calling a parser with a string.

- -
local parser = argparse "script"
-   :description "A testing script. "
-
- -

-Adding arguments

- -

Positional arguments can be added using :argument() method. It returns an Argument instance, which can be configured in the same way as Parsers. The name field is required.

- -
parser:argument "input" -- sugar for :argument():name "input"
-
- -
$ lua script.lua foo
-
- -
input   foo
-
- -

The data passed to the argument is stored in the result table at index input because it is the argument's name. The index can be changed using target field.

- -

-Setting number of arguments

- -

args field sets how many command line arguments the argument consumes. Its value is interpreted as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValueInterpretation
Number N -Exactly N arguments
String "A-B", where A and B are numbersFrom A to B arguments
String "N+", where N is a number -N or more arguments
String "?" -An optional argument
String "*" -Any number of arguments
String "+" -At least one argument

If more than one argument can be passed, a table is used to store the data.

- -
parser:argument "pair"
-   :args(2)
-   :description "A pair of arguments. "
-parser:argument "optional"
-   :args "?"
-   :description "An optional argument. "
-
- -
$ lua script.lua foo bar
-
- -
pair    {foo, bar}
-
- -
$ lua script.lua foo bar baz
-
- -
pair    {foo, bar}
-optional    baz
-
- -

-Adding options

- -

Options can be added using :option() method. It returns an Option instance, which can be configured in the same way as Parsers. The name field is required. An option can have several aliases, which can be set using aliases field or by continuously calling the Option instance.

- -
parser:option "-f" "--from"
-
- -
$ lua script.lua --from there
-$ lua script.lua --from=there
-$ lua script.lua -f there
-$ lua script.lua -fthere
-
- -
from    there
-
- -

For an option, default index used to store arguments passed to it is the first 'long' alias (an alias starting with two control characters) or just the first alias, without control characters. Hyphens in the default index are replaced with underscores. In the following table it is assumed that local args = parser:parse() have been executed.

- - - - - - - - - - - - - - - - - - - - -
Option's aliasesLocation of option's arguments
-oargs.o
-o --outputargs.output
-s --from-serverargs.from_server
- -

As with arguments, the index can be explicitly set using target field.

- -

-Flags

- -

Flags are almost identical to options, except that they don't take an argument by default.

- -
parser:flag "-q" "--quiet"
-
- -
$ lua script.lua -q
-
- -
quiet   true
-
- -

-Control characters

- -

The first characters of all aliases of all options of a parser form the set of control characters, used to distinguish options from arguments. Typically the set only consists of a hyphen.

- -

-Setting number of arguments

- -

Just as arguments, options can be configured to take several command line arguments.

- -
parser:option "--pair"
-   :args(2)
-parser:option "--optional"
-   :args "?"
-
- -
$ lua script.lua --pair foo bar
-
- -
pair    {foo, bar}
-
- -
$ lua script.lua --pair foo bar --optional
-
- -
pair    {foo, bar}
-optional    {}
-
- -
$ lua script.lua --optional=baz
-
- -
optional    {baz}
-
- -

Note that the data passed to optional option is stored in an array. That is necessary to distinguish whether the option was invoked without an argument or it was not invoked at all.

- -

-Setting number of invocations

- -

For options, it is possible to control how many times they can be used. argparse uses count field to set how many times an option can be invoked. The value of the field is interpreted in the same way args is.

- -
parser:option "-e" "--exclude"
-   :count "*"
-
- -
$ lua script.lua -eFOO -eBAR
-
- -
exclude {FOO, BAR}
-
- -

If an option can be used more than once and it can consume more than one argument, the data is stored as an array of invocations, each being an array of arguments.

- -

As a special case, if an option can be used more than once and it consumes no arguments(e.g. it's a flag), than the number of invocations is stored in associated field of the result table.

- -
parser:flag "-v" "--verbose"
-   :count "0-2"
-   :target "verbosity"
-   :description [[Sets verbosity level. 
--v: Report all warning. 
--vv: Report all debugging information. ]]
-
- -
$ lua script.lua -vv
-
- -
verbosity   2
-
- -

-Mutually exclusive groups

- -

A group of options can be marked as mutually exclusive using :mutex() method of the Parser class.

- -
parser:mutex(
-   parser:flag "-q" "--quiet",
-   parser:flag "-v" "--verbose"
-)
-
- -

If more than one element of a mutually exclusive group is used, an error is raised.

- -
$ lua script.lua -qv
-
- -
Usage: script.lua ([-q] | [-v]) [-h]
-
-Error: option '-v' can not be used together with option '-q'
-
- -

-Commands

- -

A command is a subparser invoked when its name is passed as an argument. For example, in luarocks CLI install, make, build, etc. are commands. Each command has its own set of arguments and options.

- -

Commands can be added using :command() method. Just as options, commands can have several aliases.

- -
parser:command "install" "i"
-
- -

If a command it used, true is stored in the corresponding field of the result table.

- -
$ lua script.lua install
-
- -
install true
-
- -

A typo will result in an appropriate error message:

- -
$ lua script.lua instal
-
- -
Usage: script.lua [-h] <command> ...
-
-Error: unknown command 'instal'
-Did you mean 'install'?
-
- -

-Adding elements to commands

- -

The Command class is a subclass of the Parser class, so all the Parser's methods for adding elements work on commands, too.

- -
local install = parser:command "install"
-install:argument "rock"
-install:option "-f" "--from"
-
- -
$ lua script.lua install foo --from=bar
-
- -
install true
-rock    foo
-from    bar
-
- -

Commands have their own usage and help messages.

- -
$ lua script.lua install
-
- -
Usage: script.lua install [-f <from>] [-h] <rock>
-
-Error: too few arguments
-
- -
$ lua script.lua install --help
-
- -
Usage: script.lua install [-f <from>] [-h] <rock>
-
-Arguments: 
-   rock
-
-Options: 
-   -f <from>, --from <from>
-   -h, --help            Show this help message and exit. 
-
- -

-Making a command optional

- -

By default, if a parser has commands, using one of them is obligatory.

- -
local parser = argparse()
-parser:command "install"
-
- -
$ lua script.lua
-
- -
Usage: script.lua [-h] <command> ...
-
-Error: a command is required
-
- -

This can be changed using the require_command field.

- -
local parser = argparse()
-   :require_command(false)
-parser:command "install"
-
- -

Now not using a command is not an error:

- -
$ lua script.lua
-
- -

produces nothing.

- -

-Default values

- -

For elements such as arguments and options, if default field is set, its value is stored in case the element was not used.

- -
parser:option "-o" "--output"
-   :default "a.out"
-
- -
$ lua script.lua
-
- -
output  a.out
-
- -

The existence of a default value is reflected in help message.

- -
$ lua script.lua --help
-
- -
Usage: script [-o <output>] [-h]
-
-Options: 
-   -o <output>, --output <output>
-                         default: a.out
-   -h, --help            Show this help message and exit. 
-
- -

Note that invocation without required arguments is still an error.

- -
$ lua script.lua -o
-
- -
Usage: script [-o <output>] [-h]
-
-Error: too few arguments
-
- -

-Default mode

- -

The defmode field regulates how argparse should use the default value of an element.

- -

If defmode contains "u"(for unused), the default value will be automatically passed to the element if it was not invoked at all. This is the default behavior.

- -

If defmode contains "a"(for argument), the default value will be automatically passed to the element if not enough arguments were passed, or not enough invocations were made.

- -

Consider the difference:

- -
parser:option "-o"
-   :default "a.out"
-parser:option "-p" 
-   :default "password"
-   :defmode "arg"
-
- -
$ lua script.lua -h
-
- -
Usage: script [-o <o>] [-p [<p>]] [-h]
-
-Options: 
-   -o <o>                default: a.out
-   -p [<p>]              default: password
-   -h, --help            Show this help message and exit. 
-
- -
$ lua script.lua
-
- -
o   a.out
-
- -
$ lua script.lua -p
-
- -
o   a.out
-p   password
-
- -
$ lua script.lua -o
-
- -
Usage: script [-o <o>] [-p [<p>]] [-h]
-
-Error: too few arguments
-
- -

-Converters

- -

argparse can perform automatic validation and conversion on arguments. If convert field of an element is a function, it will be applied to all the arguments passed to it. The function should return nil and, optionally, an error message if conversion failed. Standard tonumber and io.open functions work exactly like that.

- -
parser:argument "input"
-   :convert(io.open)
-parser:option "-t" "--times"
-   :convert(tonumber)
-
- -
$ lua script.lua foo.txt -t5
-
- -
input   file (0xaddress)
-times   5 (number)
-
- -
$ lua script.lua nonexistent.txt
-
- -
Usage: script.lua [-t <times>] [-h] <input>
-
-Error: nonexistent.txt: No such file or directory
-
- -
$ lua script.lua foo.txt --times=many
-
- -
Usage: script.lua [-t <times>] [-h] <input>
-
-Error: malformed argument 'many'
-
- -

-Table converters

- -

If convert field of an element contains a table, arguments passed to it will be used as keys. If a key is missing, an error is raised.

- -
parser:argument "choice"
-   :convert {
-      foo = "Something foo-related",
-      bar = "Something bar-related"
-   }
-
- -
$ lua script.lua bar
-
- -
choice  Something bar-related
-
- -
$ lua script.lua baz
-
- -
Usage: script.lua [-h] <choice>
-
-Error: malformed argument 'baz'
-
- -

-Actions

- -

argparse can trigger a callback when an option or a command is encountered. The callback can be set using action field. Actions are called regardless of whether the rest of command line arguments are correct.

- -
parser:flag "-v" "--version"
-   :description "Show version info and exit. "
-   :action(function()
-      print("script.lua v1.0.0")
-      os.exit(0)
-   end)
-
- -
$ lua script.lua -v
-
- -
script.lua v1.0.0
-
- -

This example would work even if the script had mandatory arguments.

- -

-Miscellaneous

- -

-Overwriting default help option

- -

If the field add_help of a parser is set to false, no help option will be added to it. Otherwise, the value of the field will be used to configure it.

- -
local parser = argparse()
-   :add_help "/?"
-
- -
$ lua script.lua /?
-
- -
Usage: script.lua [/?]
-
-Options: 
-   /?                    Show this help message and exit.
-
- -

-Configuring usage and help messages

- -

-Setting description and epilog

- -

The value of description field of a parser is placed between the usage message and the argument list in the help message.

- -

The value of epilog field is appended to the help message.

- -
local parser = argparse "script"
-   :description "A description. "
-   :epilog "An epilog. "
-
- -
$ lua script.lua --help
-
- -
Usage: script [-h]
-
-A description. 
-
-Options: 
-   -h, --help            Show this help message and exit. 
-
-An epilog. 
-
- -

-Setting argument placeholder

- -

For options and arguments, argname field controls the placeholder for the argument in the usage message.

- -
parser:option "-f" "--from"
-   :argname "<server>"
-
- -
$ lua script.lua --help
-
- -
Usage: script.lua [-f <server>] [-h]
-
-Options: 
-   -f <server>, --from <server>
-   -h, --help            Show this help message and exit. 
-
- -

argname can be an array of placeholders.

- -
parser:option "--pair"
-   :args(2)
-   :argname{"<key>", "<value>"}
-
- -
$ lua script.lua --help
-
- -
Usage: script.lua [--pair <key> <value>] [-h]
-
-Options: 
-   --pair <key> <value>
-   -h, --help            Show this help message and exit. 
-
- -

-Hiding default value

- -If an option has a default value, argparse will automatically append (default: <value>>) to its usage message. This can be disabled using show_default field: - -
parser:option "-o" "--output"
-   :default "a.out"
-   :show_default(false)
-
- -
$ lua script.lua --help
-
- -
Usage: script [-o <output>] [-h]
-
-Options: 
-   -o <output>, --output <output>
-   -h, --help            Show this help message and exit. 
-
- -

-Prohibiting overuse of options

- -

By default, if an option is invoked too many times, latest invocations overwrite the data passed earlier.

- -
parser:option "-o" "--output"
-
- -
$ lua script.lua -oFOO -oBAR
-
- -
output   BAR
-
- -

Set the overwrite field to false to prohibit this behavior.

- -
parser:option "-o" "--output"
-   :overwrite(false)
-
- -
$ lua script.lua -oFOO -oBAR
-
- -
Usage: script.lua [-o <output>] [-h]
-
-Error: option '-o' must be used at most 1 time
-
- -

-Generating usage and help messages

- -

:get_help() and :get_usage() methods of Parser and Command classes can be used to generate their help and usage messages.

- -

-Parsing algorithm

- -

argparse interprets command line arguments in the following way:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ArgumentInterpretation
fooAn argument of an option or a positional argument.
--fooAn option.
--foo=barAn option and its argument. The option must be able to take arguments.
-fAn option.
-abcdefLetters are interpreted as options. If one of them can take an argument, the rest of the string is passed to it.
--The rest of the command line arguments will be interpreted as positional arguments.
-
-
- - - - - - - - diff --git a/doc/stylesheets/pygment_trac.css b/doc/stylesheets/pygment_trac.css deleted file mode 100644 index e65cedf..0000000 --- a/doc/stylesheets/pygment_trac.css +++ /dev/null @@ -1,70 +0,0 @@ -.highlight .hll { background-color: #ffffcc } -.highlight { background: #f0f3f3; } -.highlight .c { color: #0099FF; font-style: italic } /* Comment */ -.highlight .err { color: #AA0000; background-color: #FFAAAA } /* Error */ -.highlight .k { color: #006699; font-weight: bold } /* Keyword */ -.highlight .o { color: #555555 } /* Operator */ -.highlight .cm { color: #0099FF; font-style: italic } /* Comment.Multiline */ -.highlight .cp { color: #009999 } /* Comment.Preproc */ -.highlight .c1 { color: #0099FF; font-style: italic } /* Comment.Single */ -.highlight .cs { color: #0099FF; font-weight: bold; font-style: italic } /* Comment.Special */ -.highlight .gd { background-color: #FFCCCC; border: 1px solid #CC0000 } /* Generic.Deleted */ -.highlight .ge { font-style: italic } /* Generic.Emph */ -.highlight .gr { color: #FF0000 } /* Generic.Error */ -.highlight .gh { color: #003300; font-weight: bold } /* Generic.Heading */ -.highlight .gi { background-color: #CCFFCC; border: 1px solid #00CC00 } /* Generic.Inserted */ -.highlight .go { color: #AAAAAA } /* Generic.Output */ -.highlight .gp { color: #000099; font-weight: bold } /* Generic.Prompt */ -.highlight .gs { font-weight: bold } /* Generic.Strong */ -.highlight .gu { color: #003300; font-weight: bold } /* Generic.Subheading */ -.highlight .gt { color: #99CC66 } /* Generic.Traceback */ -.highlight .kc { color: #006699; font-weight: bold } /* Keyword.Constant */ -.highlight .kd { color: #006699; font-weight: bold } /* Keyword.Declaration */ -.highlight .kn { color: #006699; font-weight: bold } /* Keyword.Namespace */ -.highlight .kp { color: #006699 } /* Keyword.Pseudo */ -.highlight .kr { color: #006699; font-weight: bold } /* Keyword.Reserved */ -.highlight .kt { color: #007788; font-weight: bold } /* Keyword.Type */ -.highlight .m { color: #FF6600 } /* Literal.Number */ -.highlight .s { color: #CC3300 } /* Literal.String */ -.highlight .na { color: #330099 } /* Name.Attribute */ -.highlight .nb { color: #336666 } /* Name.Builtin */ -.highlight .nc { color: #00AA88; font-weight: bold } /* Name.Class */ -.highlight .no { color: #336600 } /* Name.Constant */ -.highlight .nd { color: #9999FF } /* Name.Decorator */ -.highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */ -.highlight .ne { color: #CC0000; font-weight: bold } /* Name.Exception */ -.highlight .nf { color: #CC00FF } /* Name.Function */ -.highlight .nl { color: #9999FF } /* Name.Label */ -.highlight .nn { color: #00CCFF; font-weight: bold } /* Name.Namespace */ -.highlight .nt { color: #330099; font-weight: bold } /* Name.Tag */ -.highlight .nv { color: #003333 } /* Name.Variable */ -.highlight .ow { color: #000000; font-weight: bold } /* Operator.Word */ -.highlight .w { color: #bbbbbb } /* Text.Whitespace */ -.highlight .mf { color: #FF6600 } /* Literal.Number.Float */ -.highlight .mh { color: #FF6600 } /* Literal.Number.Hex */ -.highlight .mi { color: #FF6600 } /* Literal.Number.Integer */ -.highlight .mo { color: #FF6600 } /* Literal.Number.Oct */ -.highlight .sb { color: #CC3300 } /* Literal.String.Backtick */ -.highlight .sc { color: #CC3300 } /* Literal.String.Char */ -.highlight .sd { color: #CC3300; font-style: italic } /* Literal.String.Doc */ -.highlight .s2 { color: #CC3300 } /* Literal.String.Double */ -.highlight .se { color: #CC3300; font-weight: bold } /* Literal.String.Escape */ -.highlight .sh { color: #CC3300 } /* Literal.String.Heredoc */ -.highlight .si { color: #AA0000 } /* Literal.String.Interpol */ -.highlight .sx { color: #CC3300 } /* Literal.String.Other */ -.highlight .sr { color: #33AAAA } /* Literal.String.Regex */ -.highlight .s1 { color: #CC3300 } /* Literal.String.Single */ -.highlight .ss { color: #FFCC33 } /* Literal.String.Symbol */ -.highlight .bp { color: #336666 } /* Name.Builtin.Pseudo */ -.highlight .vc { color: #003333 } /* Name.Variable.Class */ -.highlight .vg { color: #003333 } /* Name.Variable.Global */ -.highlight .vi { color: #003333 } /* Name.Variable.Instance */ -.highlight .il { color: #FF6600 } /* Literal.Number.Integer.Long */ - -.type-csharp .highlight .k { color: #0000FF } -.type-csharp .highlight .kt { color: #0000FF } -.type-csharp .highlight .nf { color: #000000; font-weight: normal } -.type-csharp .highlight .nc { color: #2B91AF } -.type-csharp .highlight .nn { color: #000000 } -.type-csharp .highlight .s { color: #A31515 } -.type-csharp .highlight .sc { color: #A31515 } diff --git a/doc/stylesheets/stylesheet.css b/doc/stylesheets/stylesheet.css deleted file mode 100644 index 7a08b01..0000000 --- a/doc/stylesheets/stylesheet.css +++ /dev/null @@ -1,423 +0,0 @@ -/******************************************************************************* -Slate Theme for GitHub Pages -by Jason Costello, @jsncostello -*******************************************************************************/ - -@import url(pygment_trac.css); - -/******************************************************************************* -MeyerWeb Reset -*******************************************************************************/ - -html, body, div, span, applet, object, iframe, -h1, h2, h3, h4, h5, h6, p, blockquote, pre, -a, abbr, acronym, address, big, cite, code, -del, dfn, em, img, ins, kbd, q, s, samp, -small, strike, strong, sub, sup, tt, var, -b, u, i, center, -dl, dt, dd, ol, ul, li, -fieldset, form, label, legend, -table, caption, tbody, tfoot, thead, tr, th, td, -article, aside, canvas, details, embed, -figure, figcaption, footer, header, hgroup, -menu, nav, output, ruby, section, summary, -time, mark, audio, video { - margin: 0; - padding: 0; - border: 0; - font: inherit; - vertical-align: baseline; -} - -/* HTML5 display-role reset for older browsers */ -article, aside, details, figcaption, figure, -footer, header, hgroup, menu, nav, section { - display: block; -} - -ol, ul { - list-style: none; -} - -table { - border-collapse: collapse; - border-spacing: 0; -} - -/******************************************************************************* -Theme Styles -*******************************************************************************/ - -body { - box-sizing: border-box; - color:#373737; - background: #212121; - font-size: 16px; - font-family: 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif; - line-height: 1.5; - -webkit-font-smoothing: antialiased; -} - -h1, h2, h3, h4, h5, h6 { - margin: 10px 0; - font-weight: 700; - color:#222222; - font-family: 'Lucida Grande', 'Calibri', Helvetica, Arial, sans-serif; - letter-spacing: -1px; -} - -h1 { - font-size: 36px; - font-weight: 700; -} - -h2 { - padding-bottom: 10px; - font-size: 32px; - background: url('../images/bg_hr.png') repeat-x bottom; -} - -h3 { - font-size: 24px; -} - -h4 { - font-size: 21px; -} - -h5 { - font-size: 18px; -} - -h6 { - font-size: 16px; -} - -p { - margin: 10px 0 15px 0; -} - -footer p { - color: #f2f2f2; -} - -a { - text-decoration: none; - color: #007edf; - text-shadow: none; - - transition: color 0.5s ease; - transition: text-shadow 0.5s ease; - -webkit-transition: color 0.5s ease; - -webkit-transition: text-shadow 0.5s ease; - -moz-transition: color 0.5s ease; - -moz-transition: text-shadow 0.5s ease; - -o-transition: color 0.5s ease; - -o-transition: text-shadow 0.5s ease; - -ms-transition: color 0.5s ease; - -ms-transition: text-shadow 0.5s ease; -} - -a:hover, a:focus {text-decoration: underline;} - -footer a { - color: #F2F2F2; - text-decoration: underline; -} - -em { - font-style: italic; -} - -strong { - font-weight: bold; -} - -img { - position: relative; - margin: 0 auto; - max-width: 739px; - padding: 5px; - margin: 10px 0 10px 0; - border: 1px solid #ebebeb; - - box-shadow: 0 0 5px #ebebeb; - -webkit-box-shadow: 0 0 5px #ebebeb; - -moz-box-shadow: 0 0 5px #ebebeb; - -o-box-shadow: 0 0 5px #ebebeb; - -ms-box-shadow: 0 0 5px #ebebeb; -} - -p img { - display: inline; - margin: 0; - padding: 0; - vertical-align: middle; - text-align: center; - border: none; -} - -pre, code { - width: 100%; - color: #222; - background-color: #fff; - - font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; - font-size: 14px; - - border-radius: 2px; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; -} - -pre { - width: 100%; - padding: 10px; - box-shadow: 0 0 10px rgba(0,0,0,.1); - overflow: auto; -} - -code { - padding: 3px; - margin: 0 3px; - box-shadow: 0 0 10px rgba(0,0,0,.1); -} - -pre code { - display: block; - box-shadow: none; -} - -blockquote { - color: #666; - margin-bottom: 20px; - padding: 0 0 0 20px; - border-left: 3px solid #bbb; -} - - -ul, ol, dl { - margin-bottom: 15px -} - -ul { - list-style: inside; - padding-left: 20px; -} - -ol { - list-style: decimal inside; - padding-left: 20px; -} - -dl dt { - font-weight: bold; -} - -dl dd { - padding-left: 20px; - font-style: italic; -} - -dl p { - padding-left: 20px; - font-style: italic; -} - -hr { - height: 1px; - margin-bottom: 5px; - border: none; - background: url('../images/bg_hr.png') repeat-x center; -} - -table { - border: 1px solid #373737; - margin-bottom: 20px; - text-align: left; - } - -th { - font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif; - padding: 10px; - background: #373737; - color: #fff; - } - -td { - padding: 10px; - border: 1px solid #373737; - } - -form { - background: #f2f2f2; - padding: 20px; -} - -/******************************************************************************* -Full-Width Styles -*******************************************************************************/ - -.outer { - width: 100%; -} - -.inner { - position: relative; - max-width: 640px; - padding: 20px 10px; - margin: 0 auto; -} - -#forkme_banner { - display: block; - position: absolute; - top:0; - right: 10px; - z-index: 10; - padding: 10px 50px 10px 10px; - color: #fff; - background: url('../images/blacktocat.png') #0090ff no-repeat 95% 50%; - font-weight: 700; - box-shadow: 0 0 10px rgba(0,0,0,.5); - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; -} - -#header_wrap { - background: #212121; - background: -moz-linear-gradient(top, #373737, #212121); - background: -webkit-linear-gradient(top, #373737, #212121); - background: -ms-linear-gradient(top, #373737, #212121); - background: -o-linear-gradient(top, #373737, #212121); - background: linear-gradient(top, #373737, #212121); -} - -#header_wrap .inner { - padding: 50px 10px 30px 10px; -} - -#project_title { - margin: 0; - color: #fff; - font-size: 42px; - font-weight: 700; - text-shadow: #111 0px 0px 10px; -} - -#project_tagline { - color: #fff; - font-size: 24px; - font-weight: 300; - background: none; - text-shadow: #111 0px 0px 10px; -} - -#downloads { - position: absolute; - width: 210px; - z-index: 10; - bottom: -40px; - right: 0; - height: 70px; - background: url('../images/icon_download.png') no-repeat 0% 90%; -} - -.zip_download_link { - display: block; - float: right; - width: 90px; - height:70px; - text-indent: -5000px; - overflow: hidden; - background: url(../images/sprite_download.png) no-repeat bottom left; -} - -.tar_download_link { - display: block; - float: right; - width: 90px; - height:70px; - text-indent: -5000px; - overflow: hidden; - background: url(../images/sprite_download.png) no-repeat bottom right; - margin-left: 10px; -} - -.zip_download_link:hover { - background: url(../images/sprite_download.png) no-repeat top left; -} - -.tar_download_link:hover { - background: url(../images/sprite_download.png) no-repeat top right; -} - -#main_content_wrap { - background: #f2f2f2; - border-top: 1px solid #111; - border-bottom: 1px solid #111; -} - -#main_content { - padding-top: 40px; -} - -#footer_wrap { - background: #212121; -} - - - -/******************************************************************************* -Small Device Styles -*******************************************************************************/ - -@media screen and (max-width: 480px) { - body { - font-size:14px; - } - - #downloads { - display: none; - } - - .inner { - min-width: 320px; - max-width: 480px; - } - - #project_title { - font-size: 32px; - } - - h1 { - font-size: 28px; - } - - h2 { - font-size: 24px; - } - - h3 { - font-size: 21px; - } - - h4 { - font-size: 18px; - } - - h5 { - font-size: 14px; - } - - h6 { - font-size: 12px; - } - - code, pre { - min-width: 320px; - max-width: 480px; - font-size: 11px; - } - -} diff --git a/docsrc/arguments.rst b/docsrc/arguments.rst new file mode 100644 index 0000000..7d8462c --- /dev/null +++ b/docsrc/arguments.rst @@ -0,0 +1,68 @@ +Adding and configuring arguments +================================ + +Positional arguments can be added using ``:argument(name, description, default, convert, args)`` method. It returns an Argument instance, which can be configured in the same way as Parsers. The ``name`` property is required. + +.. code-block:: lua + :linenos: + + parser:argument "input" + +:: + + $ lua script.lua foo + +.. code-block:: lua + + { + input = "foo" + } + +The data passed to the argument is stored in the result table at index ``input`` because it is the argument's name. The index can be changed using ``target`` property. + +Setting number of consumed arguments +------------------------------------ + +``args`` property sets how many command line arguments the argument consumes. Its value is interpreted as follows: + +================================================= ============================= +Value Interpretation +================================================= ============================= +Number ``N`` Exactly ``N`` arguments +String ``A-B``, where ``A`` and ``B`` are numbers From ``A`` to ``B`` arguments +String ``N+``, where ``N`` is a number ``N`` or more arguments +String ``?`` An optional argument +String ``*`` Any number of arguments +String ``+`` At least one argument +================================================= ============================= + +If more than one argument can be consumed, a table is used to store the data. + +.. code-block:: lua + :linenos: + + parser:argument("pair", "A pair of arguments.") + :args(2) + parser:argument("optional", "An optional argument.") + :args "?" + +:: + + $ lua script.lua foo bar + +.. code-block:: lua + + { + pair = {"foo", "bar"} + } + +:: + + $ lua script.lua foo bar baz + +.. code-block:: lua + + { + pair = {"foo", "bar"}, + optional = "baz" + } diff --git a/docsrc/callbacks.rst b/docsrc/callbacks.rst new file mode 100644 index 0000000..10c3b93 --- /dev/null +++ b/docsrc/callbacks.rst @@ -0,0 +1,104 @@ +Callbacks +========= + +Converters +---------- + +argparse can perform automatic validation and conversion on arguments. If ``convert`` property of an element is a function, it will be applied to all the arguments passed to it. The function should return ``nil`` and, optionally, an error message if conversion failed. Standard ``tonumber`` and ``io.open`` functions work exactly like that. + +.. code-block:: lua + :linenos: + + parser:argument "input" + :convert(io.open) + parser:option "-t --times" + :convert(tonumber) + +:: + + $ lua script.lua foo.txt -t5 + +.. code-block:: lua + + { + input = file_object, + times = 5 + } + +:: + + $ lua script.lua nonexistent.txt + +:: + + Usage: script.lua [-t ] [-h] + + Error: nonexistent.txt: No such file or directory + +:: + + $ lua script.lua foo.txt --times=many + +:: + + Usage: script.lua [-t ] [-h] + + Error: malformed argument 'many' + +Table converters +^^^^^^^^^^^^^^^^ + +If convert property of an element is a table, arguments passed to it will be used as keys. If a key is missing, an error is raised. + +.. code-block:: lua + :linenos: + + parser:argument "choice" + :convert { + foo = "Something foo-related", + bar = "Something bar-related" + } + +:: + + $ lua script.lua bar + +.. code-block:: lua + + { + choice = "Something bar-related" + } + +:: + + $ lua script.lua baz + +:: + + Usage: script.lua [-h] + + Error: malformed argument 'baz' + +Actions +------- + +argparse can trigger a callback when an option or a command is encountered. The callback can be set using ``action`` property. Actions are called regardless of whether the rest of command line arguments are correct. + +.. code-block:: lua + :linenos: + + parser:argument "required_argument" + + parser:flag("-v --version", "Show version info and exit.") + :action(function() + print("script.lua v1.0.0") + os.exit(0) + end) + +:: + + $ lua script.lua -v + +:: + + script.lua v1.0.0 diff --git a/docsrc/commands.rst b/docsrc/commands.rst new file mode 100644 index 0000000..e8b0493 --- /dev/null +++ b/docsrc/commands.rst @@ -0,0 +1,119 @@ +Adding and configuring commands +=============================== + +A command is a subparser invoked when its name is passed as an argument. For example, in `git `_ CLI ``add``, ``commit``, ``push``, etc. are commands. Each command has its own set of arguments and options, but inherits options of its parent. + +Commands can be added using ``:command(name, description, epilog)`` method. Just as options, commands can have several aliases. + +.. code-block:: lua + :linenos: + + parser:command "install i" + +If a command it used, ``true`` is stored in the corresponding field of the result table. + +:: + + $ lua script.lua install + +.. code-block:: lua + + { + install = true + } + +A typo will result in an appropriate error message. + +:: + + $ lua script.lua instal + +:: + + Usage: script.lua [-h] ... + + Error: unknown command 'instal' + Did you mean 'install'? + +Adding elements to commands +--------------------------- + +The Command class is a subclass of the Parser class, so all the Parser's methods for adding elements work on commands, too. + +.. code-block:: lua + :linenos: + + local install = parser:command "install" + install:argument "rock" + install:option "-f --from" + +:: + + $ lua script.lua install foo --from=bar + + +.. code-block:: lua + + { + install = true, + rock = "foo", + from = "bar" + } + +Commands have their own usage and help messages. + +:: + + $ lua script.lua install + +:: + + Usage: script.lua install [-f ] [-h] + + Error: too few arguments + +:: + + $ lua script.lua install --help + +:: + + Usage: script.lua install [-f ] [-h] + + Arguments: + rock + + Options: + -f , --from + -h, --help Show this help message and exit. + +Making a command optional +------------------------- + +By default, if a parser has commands, using one of them is obligatory. + + +.. code-block:: lua + :linenos: + + local parser = argparse() + parser:command "install" + +:: + + $ lua script.lua + +:: + + Usage: script.lua [-h] ... + + Error: a command is required + +This can be changed using ``require_command`` property. + +.. code-block:: lua + :linenos: + + local parser = argparse() + :require_command(false) + parser:command "install" diff --git a/docsrc/conf.py b/docsrc/conf.py new file mode 100644 index 0000000..4c7edb9 --- /dev/null +++ b/docsrc/conf.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# +# argparse documentation build configuration file, created by +# sphinx-quickstart on Sat Jun 20 14:03:24 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = [] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'argparse' +copyright = u'2013 - 2015, Peter Melnichenko' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.4.0' +# The full version, including alpha/beta/rc tags. +release = '0.4.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +if on_rtd: + html_theme = 'default' +else: + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +html_title = "argparse 0.4.0 tutorial" + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = [] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'argparsetutorial' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'argparse.tex', u'argparse tutorial', + u'Peter Melnichenko', 'manual') +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'argparse', u'argparse tutorial', + [u'Peter Melnichenko'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'argparse', u'argparse tutorial', + u'Peter Melnichenko', 'argparse', 'Command line parser for Lua.', + 'Miscellaneous') +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docsrc/defaults.rst b/docsrc/defaults.rst new file mode 100644 index 0000000..3452570 --- /dev/null +++ b/docsrc/defaults.rst @@ -0,0 +1,115 @@ +Default values +============== + +For elements such as arguments and options, if ``default`` property is set, its value is stored in case the element was not used. + +.. code-block:: lua + :linenos: + + parser:option("-o --output", "Output file.", "a.out") + -- Equivalent: + parser:option "-o" "--output" + :description "Output file." + :default "a.out" + +:: + + $ lua script.lua + +.. code-block:: lua + + { + output = "a.out" + } + +The existence of a default value is reflected in help message, unless ``show_default`` property is set to ``false``. + +:: + + $ lua script.lua --help + +:: + + Usage: script.lua [-o ] [-h] + + Options: + -o , --output + Output file. (default: a.out) + -h, --help Show this help message and exit. + +Note that invocation without required arguments is still an error. + +:: + + $ lua script.lua -o + +:: + + Usage: script.lua [-o ] [-h] + + Error: too few arguments + +Default mode +------------ + +``defmode`` property regulates how argparse should use the default value of an element. + +If ``defmode`` contains ``u`` (for unused), the default value will be automatically passed to the element if it was not invoked at all. This is the default behavior. + +If ``defmode`` contains ``a`` (for argument), the default value will be automatically passed to the element if not enough arguments were passed, or not enough invocations were made. + +Consider the difference: + +.. code-block:: lua + :linenos: + + parser:option "-o" + :default "a.out" + parser:option "-p" + :default "password" + :defmode "arg" + +:: + + $ lua script.lua -h + +:: + + Usage: script.lua [-o ] [-p [

]] [-h] + + Options: + -o default: a.out + -p [

] default: password + -h, --help Show this help message and exit. + +:: + + $ lua script.lua + +.. code-block:: lua + + { + o = "a.out" + } + +:: + + $ lua script.lua -p + + +.. code-block:: lua + + { + o = "a.out", + p = "password" + } + +:: + + $ lua script.lua -o + +:: + + Usage: script.lua [-o ] [-p [

]] [-h] + + Error: too few arguments diff --git a/docsrc/index.rst b/docsrc/index.rst new file mode 100644 index 0000000..458cc48 --- /dev/null +++ b/docsrc/index.rst @@ -0,0 +1,17 @@ +Argparse tutorial +================= + +Contents: + +.. toctree:: + + parsers + arguments + options + mutexes + commands + defaults + callbacks + misc + +This is a tutorial for `argparse `_, a feature-rich command line parser for Lua. diff --git a/docsrc/misc.rst b/docsrc/misc.rst new file mode 100644 index 0000000..d06cf7d --- /dev/null +++ b/docsrc/misc.rst @@ -0,0 +1,261 @@ +Miscellaneous +============= + +Generating and overwriting help and usage messages +-------------------------------------------------- + +The usage and help messages of parsers and commands can be generated on demand using ``:get_usage()`` and ``:get_help()`` methods, and overridden using ``help`` and ``usage`` properties. + +Overwriting default help option +------------------------------- + +If the property ``add_help`` of a parser is set to ``false``, no help option will be added to it. Otherwise, the value of the field will be used to configure it. + +.. code-block:: lua + :linenos: + + local parser = argparse() + :add_help "/?" + +:: + + $ lua script.lua /? + +:: + + Usage: script.lua [/?] + + Options: + /? Show this help message and exit. + +Setting argument placeholder +---------------------------- + +For options and arguments, ``argname`` property controls the placeholder for the argument in the usage message. + +.. code-block:: lua + :linenos: + + parser:option "-f" "--from" + :argname "" + +:: + + $ lua script.lua --help + +:: + + Usage: script.lua [-f ] [-h] + + Options: + -f , --from + -h, --help Show this help message and exit. + +``argname`` can be an array of placeholders. + +.. code-block:: lua + :linenos: + + parser:option "--pair" + :args(2) + :argname {"", ""} + +:: + + $ lua script.lua --help + +:: + + Usage: script.lua [--pair ] [-h] + + Options: + --pair + -h, --help Show this help message and exit. + +Disabling option handling +------------------------- + +When ``handle_options`` property of a parser or a command is set to ``false``, all options will be passed verbatim to the argument list, as if the input included double-hyphens. + +.. code-block:: lua + :linenos: + + parser:handle_options(false) + parser:argument "input" + :args "*" + parser:option "-f" "--foo" + :args "*" + +:: + + $ lua script.lua bar -f --foo bar + +.. code-block:: lua + + { + input = {"bar", "-f", "--foo", "bar"} + } + +Prohibiting overuse of options +------------------------------ + +By default, if an option is invoked too many times, latest invocations overwrite the data passed earlier. + +.. code-block:: lua + :linenos: + + parser:option "-o --output" + +:: + + $ lua script.lua -oFOO -oBAR + +.. code-block:: lua + + { + output = "BAR" + } + +Set ``overwrite`` property to ``false`` to prohibit this behavior. + +.. code-block:: lua + :linenos: + + parser:option "-o --output" + :overwrite(false) + +:: + + $ lua script.lua -oFOO -oBAR + +:: + + Usage: script.lua [-o ] [-h] + + Error: option '-o' must be used at most 1 time + +Parsing algorithm +----------------- + +argparse interprets command line arguments in the following way: + +============= ================================================================================================================ +Argument Interpretation +============= ================================================================================================================ +``foo`` An argument of an option or a positional argument. +``--foo`` An option. +``--foo=bar`` An option and its argument. The option must be able to take arguments. +``-f`` An option. +``-abcdef`` Letters are interpreted as options. If one of them can take an argument, the rest of the string is passed to it. +``--`` The rest of the command line arguments will be interpreted as positional arguments. +============= ================================================================================================================ + +Property lists +-------------- + +Parser properties +^^^^^^^^^^^^^^^^^ + +Properties that can be set as arguments when calling or constructing a parser, in this order: + +=============== ====== +Property Type +=============== ====== +``name`` String +``description`` String +``epilog`` String +=============== ====== + +Other properties: + +=================== ========================== +Property Type +=================== ========================== +``usage`` String +``help`` String +``require_command`` Boolean +``handle_options`` Boolean +``add_help`` Boolean or string or table +=================== ========================== + +Command properties +^^^^^^^^^^^^^^^^^^ + +Properties that can be set as arguments when calling or constructing a command, in this order: + +=============== ====== +Property Type +=============== ====== +``name`` String +``description`` String +``epilog`` String +=============== ====== + +Other properties: + +=================== ========================== +Property Type +=================== ========================== +``target`` String +``usage`` String +``help`` String +``require_command`` Boolean +``handle_options`` Boolean +``action`` Function +``add_help`` Boolean or string or table +=================== ========================== + +Argument properties +^^^^^^^^^^^^^^^^^^^ + +Properties that can be set as arguments when calling or constructing an argument, in this order: + +=============== ================= +Property Type +=============== ================= +``name`` String +``description`` String +``default`` String +``convert`` Function or table +``args`` Number or string +=============== ================= + +Other properties: + +=================== =============== +Property Type +=================== =============== +``target`` String +``defmode`` String +``show_default`` Boolean +``argname`` String or table +=================== =============== + +Option and flag properties +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Properties that can be set as arguments when calling or constructing an option or a flag, in this order: + +=============== ================= +Property Type +=============== ================= +``name`` String +``description`` String +``default`` String +``convert`` Function or table +``args`` Number or string +``count`` Number or string +=============== ================= + +Other properties: + +=================== =============== +Property Type +=================== =============== +``target`` String +``defmode`` String +``show_default`` Boolean +``overwrite`` Booleans +``argname`` String or table +``action`` Function +=================== =============== diff --git a/docsrc/mutexes.rst b/docsrc/mutexes.rst new file mode 100644 index 0000000..a7b04ad --- /dev/null +++ b/docsrc/mutexes.rst @@ -0,0 +1,24 @@ +Mutually exclusive groups +========================= + +A group of options can be marked as mutually exclusive using ``:mutex(option, ...)`` method of the Parser class. + +.. code-block:: lua + :linenos: + + parser:mutex( + parser:flag "-q --quiet", + parser:flag "-v --verbose" + ) + +If more than one element of a mutually exclusive group is used, an error is raised. + +:: + + $ lua script.lua -qv + +:: + + Usage: script.lua ([-q] | [-v]) [-h] + + Error: option '-v' can not be used together with option '-q' diff --git a/docsrc/options.rst b/docsrc/options.rst new file mode 100644 index 0000000..793714d --- /dev/null +++ b/docsrc/options.rst @@ -0,0 +1,150 @@ +Adding and configuring options +============================== + +Options can be added using ``:option(name, description, default, convert, args, count)`` method. It returns an Option instance, which can be configured in the same way as Parsers. The ``name`` property is required. An option can have several aliases, which can be set as space separated substrings in its name or by continuously setting ``name`` property. + +.. code-block:: lua + :linenos: + + -- These lines are equivalent: + parser:option "-f" "--from" + parser:option "-f --from" + +:: + + $ lua script.lua --from there + $ lua script.lua --from=there + $ lua script.lua -f there + $ lua script.lua -fthere + +.. code-block:: lua + + { + from = "there" + } + +For an option, default index used to store arguments passed to it is the first "long" alias (an alias starting with two control characters, typically hyphens) or just the first alias, without control characters. Hyphens in the default index are replaced with underscores. In the following table it is assumed that ``local args = parser:parse()`` has been executed. + +======================== ============================== +Option's aliases Location of option's arguments +======================== ============================== +``-o`` ``args.o`` +``-o`` ``--output`` ``args.output`` +``-s`` ``--from-server`` ``args.from_server`` +======================== ============================== + +As with arguments, the index can be explicitly set using ``target`` property. + +Flags +----- + +Flags are almost identical to options, except that they don't take an argument by default. + +.. code-block:: lua + :linenos: + + parser:flag("-q --quiet") + +:: + + $ lua script.lua -q + +.. code-block:: lua + + { + quiet = true + } + +Control characters +------------------ + +The first characters of all aliases of all options of a parser form the set of control characters, used to distinguish options from arguments. Typically the set only consists of a hyphen. + +Setting number of consumed arguments +------------------------------------ + +Just as arguments, options can be configured to take several command line arguments. + +.. code-block:: lua + :linenos: + + parser:option "--pair" + :args(2) + parser:option "--optional" + :args "?" + +:: + + $ lua script.lua --pair foo bar + +.. code-block:: lua + + { + pair = {"foo", "bar"} + } + +:: + + $ lua script.lua --pair foo bar --optional + +.. code-block:: lua + + { + pair = {"foo", "bar"}, + optional = {} + } + +:: + + $ lua script.lua --optional=baz + +.. code-block:: lua + + { + optional = {"baz"} + } + + +Note that the data passed to ``optional`` option is stored in an array. That is necessary to distinguish whether the option was invoked without an argument or it was not invoked at all. + +Setting number of invocations +----------------------------- + +For options, it is possible to control how many times they can be used. argparse uses ``count`` property to set how many times an option can be invoked. The value of the property is interpreted in the same way ``args`` is. + +.. code-block:: lua + :linenos: + + parser:option("-e --exclude") + :count "*" + +:: + + $ lua script.lua -eFOO -eBAR + +.. code-block:: lua + + { + exclude = {"FOO", "BAR"} + } + +If an option can be used more than once and it can consume more than one argument, the data is stored as an array of invocations, each being an array of arguments. + +As a special case, if an option can be used more than once and it consumes no arguments (e.g. it's a flag), than the number of invocations is stored in the associated field of the result table. + +.. code-block:: lua + :linenos: + + parser:flag("-v --verbose", "Sets verbosity level.") + :count "0-2" + :target "verbosity" + +:: + + $ lua script.lua -vv + +.. code-block:: lua + + { + verbosity = 2 + } diff --git a/docsrc/parsers.rst b/docsrc/parsers.rst new file mode 100644 index 0000000..e56c3e2 --- /dev/null +++ b/docsrc/parsers.rst @@ -0,0 +1,123 @@ +Creating and using parsers +========================== + +The ``argparse`` module is a function which, when called, creates an instance of the Parser class. + +.. code-block:: lua + :linenos: + + -- script.lua + local argparse = require "argparse" + local parser = argparse() + +``parser`` is now an empty parser which does not recognize any command line arguments or options. + +Parsing command line arguments +------------------------------ + +``:parse([args])`` method of the Parser class returns a table with processed data from the command line or ``args`` array. + +.. code-block:: lua + :linenos: + + local args = parser:parse() + print(args) -- Assuming print is patched to handle tables nicely. + +When executed, this script prints ``{}`` because the parser is empty and no command line arguments were supplied. + +Error handling +^^^^^^^^^^^^^^ + +If the provided command line arguments are not recognized by the parser, it will print an error message and call ``os.exit(1)``. + +:: + + $ lua script.lua foo + +:: + + Usage: script.lua [-h] + + Error: too many arguments + +If halting the program is undesirable, ``:pparse([args])`` method should be used. It returns boolean flag indicating success of parsing and result or error message. + +An error can raised manually using ``:error()`` method. + +.. code-block:: lua + :linenos: + + parser:error("manual argument validation failed") + +:: + + Usage: script.lua [-h] + + Error: manual argument validation failed + +Help option +^^^^^^^^^^^ + +As the automatically generated usage message states, there is a help option ``-h`` added to any parser by default. + +When a help option is used, parser will print a help message and call ``os.exit(0)``. + +:: + + $ lua script.lua -h + +:: + + Usage: script.lua [-h] + + Options: + -h, --help Show this help message and exit. + +Typo autocorrection +^^^^^^^^^^^^^^^^^^^ + +When an option is not recognized by the parser, but there is an option with a similar name, a suggestion is automatically added to the error message. + +:: + + $ lua script.lua --hepl + +:: + + Usage: script.lua [-h] + + Error: unknown option '--hepl' + Did you mean '--help'? + +Configuring parsers +------------------- + +Parsers have several properties affecting their behavior. For example, ``description`` and ``epilog`` properties set the text to be displayed in the help message after the usage message and after the listings of options and arguments, respectively. Another is ``name``, which overwrites the name of the program which is used in the usage message (default value is inferred from command line arguments). + +There are several ways to set properties. The first is to chain setter methods of Parser object. + +.. code-block:: lua + :linenos: + + local parser = argparse() + :name "script" + :description "A testing script." + :epilog "For more info, see http://example.com" + +The second is to call a parser with a table containing some properties. + +.. code-block:: lua + :linenos: + + local parser = argparse() { + name = "script", + description = "A testing script.", + epilog "For more info, see http://example.com." + } + +Finally, ``name``. ``description`` and ``epilog`` properties can be passed as arguments when calling a parser. + +.. code-block:: lua + :linenos: + + local parser = argparse("script", "A testing script.", "For more info, see http://example.com.")