pax_global_header00006660000000000000000000000064143731756410014525gustar00rootroot0000000000000052 comment=be972fda6bc71e5f1bea3c48d620ecbedcb85a53 raku-getopt-long-0.4.2/000077500000000000000000000000001437317564100147275ustar00rootroot00000000000000raku-getopt-long-0.4.2/.gitignore000066400000000000000000000000231437317564100167120ustar00rootroot00000000000000*.sw[poq] .precomp raku-getopt-long-0.4.2/.travis.yml000066400000000000000000000001661437317564100170430ustar00rootroot00000000000000branches: sudo: false language: perl6 perl6: - latest install: - rakudobrew build-zef - zef install --verbose . raku-getopt-long-0.4.2/Changes000066400000000000000000000053421437317564100162260ustar00rootroot00000000000000Revision history for Getopt-Long {{$NEXT}} 0.4.2 2023-02-15T16:34:42+01:00 - Add basic usage generator to Getopt::Long - Add «Parameter is option(Hash)» - Make converter traits check for definedness - Make options and positionals public methods - Restore :auto-help option 0.4.1 2022-12-12T15:49:16+01:00 - Make FormattableException a Getopt::Long::Exception - Add Custom role for argument type customization - Allow Options in get-options{,-from} 0.4.0 2022-12-01T15:26:25+01:00 - Add Argument classes - Improve getopt trait on subs 0.3.5 2022-09-26T18:25:31+02:00 - Allow enum values to be converted to enums 0.3.4 2022-08-31T21:23:46+02:00 - Correctly handle invalid value exceptions in enums and coercions - Remove compatability with Raku <2018.06 0.3.3 2021-02-25T00:00:26+01:00 - Added compat-space option 0.3.2 2020-12-20T18:41:16+01:00 - Add support for Numeric arguments - Make bundling and compat-single compatible with each other 0.3.1 2020-12-15T02:24:46+01:00 - Add support for Version objects 0.3.0 2020-12-12T17:47:08+01:00 - Add auto-help option - Replaced custom argument types with coercion types - Add custom converter support - Eliminate :$overwrite from call-with-getopt - Abolish Exceptional 0.2.0 2020-11-15T00:00:06+01:00 - Add auto-abbreviate option - Add support for custom argument types - Enable permute by default 0.1.8 2020-10-25T20:07:39+01:00 - Fix compatibility with rakudo 2019.07 0.1.7 2020-10-25T13:47:29+01:00 - Don't throw away positional arguments beyond the tenth 0.1.6 2020-03-02T00:41:33+01:00 - Add support for enum types - Add IO::Path argument support - Add DateTime and Date argument support - Add type conversions for positional arguments - Reject values failing argument constraints - Add compat-positional option 0.1.5 2020-02-23T18:27:21+01:00 - Add compat-builtin option - Add compat-negation option - Only catch Exceptional in ARGS-TO-CAPTURE 0.1.4 2020-02-11T00:13:46+01:00 - Add compat-single option 0.1.3 2019-10-09T21:38:41+02:00 - Parse explicit parameter formats early - Don't allow proto subs to be pre-parsed - Only throw Getopt::Long::Exceptionals 0.1.2 2019-06-08T15:32:25+02:00 - Add support for Complex parameters - Make f format Num instead of Real 0.1.1 2019-05-26T15:11:45+02:00 - Add support for Real parameters - Add getopt sub trait - Eliminate the extended integer parsing type 0.1.0 2019-02-03T01:43:46+01:00 - Eliminate Capture in pair syntax - Add compound inference to pair syntax 0.0.3 2019-01-26T21:15:05+01:00 - Added pair syntax - Implemented new perl6.d getopt hooks raku-getopt-long-0.4.2/META6.json000066400000000000000000000007261437317564100164430ustar00rootroot00000000000000{ "authors": [ "Leon Timmermans" ], "build-depends": [ ], "depends": [ ], "description": "A powerful getopt implementation", "license": "Artistic-2.0", "name": "Getopt::Long", "perl": "6.*", "provides": { "Getopt::Long": "lib/Getopt/Long.rakumod" }, "resources": [ ], "source-url": "https://github.com/Leont/getopt-long6.git", "tags": [ "command", "getopt", "main" ], "test-depends": [ ], "version": "0.4.2" } raku-getopt-long-0.4.2/README.md000066400000000000000000000447421437317564100162210ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/Leont/getopt-long6.svg?branch=master)](https://travis-ci.org/Leont/getopt-long6) NAME ==== Getopt::Long SYNOPSIS ======== use Getopt::Long; get-options("length=i" => my $length, # numeric "file=s" => my $file, # string "verbose" => my $verbose); # flag use Getopt::Long; my $options = get-options("length=i", # numeric "file=s", # string "verbose"); # flag or use Getopt::Long; sub MAIN(Int :$length, Str :$file, Bool :$verbose) { ... } DESCRIPTION =========== The Getopt::Long module implements extended getopt functions called `get-options()` and `get-options-from`, as well as automatic argument parsing for a `MAIN` sub. This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is also provided. Command Line Options, an Introduction ===================================== Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line *options* as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did. Command line options come in several flavours. Historically, they are preceded by a single dash `-`, and consist of a single letter. -l -a -c Usually, these single-character options can be bundled: -lac Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not: -s 24 -s24 Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic `-l` one could use the more descriptive `--long`. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Also, option values could be specified either like --size=24 or --size 24 Getting Started with Getopt::Long ================================= To use Getopt::Long from a Raku program, you must include the following line in your program: use Getopt::Long; This will load the core of the Getopt::Long module and prepare your program for using it. Getopt::Long as a MAIN wrapper ------------------------------ Getopt::Long can be used as a argument parsing MAIN wrapper, replacing the builtin argument parsing. It will by default offer a Unix-typical command line interface, but various options allow it to be more similar to Raku's ideosyncratic parsing. It supports the following types for named and positional arguments: * Bool * Any * Str * Int * Rat * Num * Real * Numeric * Complex * IO::Path * DateTime * Date * Version It also supports any enum type, and any coercion type that uses any of the aforementioned types as its contraint type (e.g. `Foo(Str)`). An explicit converter can also be set using an `is option` trait, e.g. sub MAIN(Foo :$foo is option(&foo-converter)) { ... } Simple options -------------- The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are: --all --verbose --quiet --debug Handling simple options is straightforward: sub MAIN(Bool :$verbose, Bool :$all) { ... } or: get-options('verbose' => my $verbose, 'all' => my $all); The call to `get-options()` parses the command line arguments that are present in `@*ARGS` and sets the option variable to the value `True` if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called *enabling* the option. The option name as specified to the `get-options()` function is called the option *specification*. Later we'll see that this specification can contain more than just the option name. `get-options()` will return a `Capture` if the command line could be processed successfully. Otherwise, it will throw an error using die(). A little bit less simple options -------------------------------- Getopt::Long supports two useful variants of simple options: *negatable* options and *incremental* options. A negatable option is specified with an exclamation mark `!` after the option name or a default value for `MAIN` argument: sub MAIN(Bool :$verbose = False) { ... } or: get-options('verbose!' => my $verbose); or: my $options = get-options('verbose!'); Now, using `--verbose` on the command line will enable `$verbose`, as expected. But it is also allowed to use `--noverbose` or `--no-verbose`, which will disable `$verbose ` by setting its value to `False`. An incremental option is specified with a plus `+` after the option name: sub MAIN(Int :$verbose is option('+')) { ... } or: get-options('verbose+' => my $verbose); or my $options = get-options('verbose+'); Using `--verbose` on the command line will increment the value of `$verbose`. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of `--verbose` could increase the verbosity level of the program. Mixing command line option with other arguments ----------------------------------------------- Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash `--` on the command line: --size 24 -- --all In this example, `--all` will *not* be treated as an option, but passed to the program unharmed, in `@*ARGS`. Options with values ------------------- For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects. Three kinds of values are supported: integer numbers, floating point numbers, and strings. If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself. sub MAIN(Str :$tag) { ... } or get-options('tag=s' => my $tag); or my %options = get-options('tag=s'); In the option specification, the option name is followed by an equals sign `=` and the letter `s`. The equals sign indicates that this option requires a value. The letter `s` indicates that this value is an arbitrary string. Other possible value types are `i` for integer values, and `f` for floating point values. Using a colon `:` instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string `''` assigned, while numeric options are set to `0`. Options with multiple values ---------------------------- Options sometimes take several values. For example, a program could use multiple directories to search for library files: --library lib/stdlib --library lib/extlib You can specify that the option can have multiple values by adding a "@" to the format, or declare the argument as positional: sub MAIN(Str :@library) { ... } or get-options('library=s@' => my @libraries); or my $options = get-options('library=s@'); Used with the example above, `@libraries`/`$options` would contain two strings upon completion: `"lib/stdlib"` and `"lib/extlib"`, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values. Warning: What follows is an experimental feature. Options can take multiple values at once, for example --coordinates 52.2 16.4 --rgbcolor 255 255 149 This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the `{...}` repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows: my $options = get-options('coordinates=f{2}', 'rgbcolor=i{3}'); or sub MAIN(Rat :@coordinates is option('f{2}'), Int :@rgbcolor is option('i{3}')) get-options('coordinates=f{2}' => my @coordinates, 'rgbcolor=i{3}' => my @rgbcolor); It is also possible to specify the minimal and maximal number of arguments an option takes. `foo=s{2,4}` indicates an option that takes at least two and at most 4 arguments. `foo=s{1,}` indicates one or more values; `foo:s{,}` indicates zero or more option values. Options with hash values ------------------------ If you specify that the option can have multiple named values by adding a "%": sub MAIN(Str :%define) { ... } or get-options("define=s%" => my %define); or my $options = get-options("define=s%"); When used with command line options: --define os=linux --define vendor=redhat the hash `%defines` or `$options ` will contain two keys, `"os"` with value `"linux"` and `"vendor"` with value `"redhat"`. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings. Options with multiple names --------------------------- Often it is user friendly to supply alternate mnemonic names for options. For example `--height` could be an alternate name for `--length`. Alternate names can be included in the option specification, separated by vertical bar `|` characters. To implement the above example: sub MAIN(:height(:$length)) { ... } or get-options('length|height=f' => my $length); or $options = get-options('length|height=f'); The first name is called the *primary* name, the other names are called *aliases*. When using a hash to store options, the key will always be the primary name. Multiple alternate names are possible. Summary of Option Specifications -------------------------------- Each option specifier consists of two parts: the name specification and the argument specification. The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters. length option name is "length" length|size|l name is "length", aliases are "size" and "l" The argument specification is optional. If omitted, the option is considered boolean, a value of `True` will be assigned when the option is used on the command line. The argument specification can be * ! The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. `"foo!"` will allow `--foo` (a value of 1 will be assigned) as well as `--nofoo` and `--no-foo` (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well. * + The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. `"more+"`, when used with `--more --more --more`, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at firs). The `+` specifier is ignored if the option destination is not a scalar. * = *type* [ *desttype* ] [ *repeat* ] The option requires an argument of the given type. Supported types are: * s String(`Str`). An arbitrary sequence of characters. It is valid for the argument to start with `-` or `--`. * i Integer (`Int`). This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (`0o`, optionally followed by '0', '1', .. '7'), or a hexadecimal string (`0x` followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (`0b` followed by a series of '0' and '1'). * r Rational number (`Rat`). For example `3.14`. * f Floating-pointer number (`Num`). For example `3.14`, `-6.23E24` and so on. * c Complex number (`Complex`). For example `1+2i`. * p Path (`IO::Path`). For example `foo/bar.txt`. * d An ISO-8601 formatted date and time (`DateTime`). For example `2019-12-30T01:23:45-0700`. * a A ISO-8601 formatted date (`Date`). For example `2019-12-30`. * v A Version (`Version`). For example `1.2.3`. The *desttype* can be `@` or `%` to specify that the option is list or a hash valued. The *repeat* specifies the number of values this option takes per occurrence on the command line. It has the format `{` [ *min* ] [ `,` [ *max* ] ] `}`. *min* denotes the minimal number of arguments. It defaults to `0`. *max* denotes the maximum number of arguments. It must be at least *min*. If *max* is omitted, *but the comma is not*, there is no upper bound to the number of argument values taken. * : *type* [ *desttype* ] Like `=`, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options. Note that if a string argument starts with `-` or `--`, it will be considered an option on itself. * : *number* [ *desttype* ] Like `:i`, but if the value is omitted, the *number* will be assigned. * : + [ *desttype* ] Like `:i`, but if the value is omitted, the current value for the option will be incremented. Advanced Possibilities ====================== Object oriented interface ------------------------- Getopt::Long can be used in an object oriented way as well: use Getopt::Long; my $p = Getopt::Long.new-from-patterns(@options); my $o = $p.get-options(@args) ... Configuration options can be passed to the constructor as named arguments: $p = Getopt::Long.new-from-patterns(@options, :!permute); Parsing options from an arbitrary array --------------------------------------- By default, get-options parses the options that are present in the global array `@*ARGS`. A special entry `get-options-from` can be used to parse options from an arbitrary array. use Getopt::Long; $ret = get-options-from(@myargs, ...); The following two calls behave identically: $ret = get-options( ... ); $ret = get-options-from(@*ARGS, :overwrite, ... ); Configuring Getopt::Long ======================== `get-options` and `get-options-from` take the following named options to configure. When using Getopt::Long as a `MAIN` wrapper, you can set them using the `%*SUB-MAIN-OPTS` variable: * auto-abbreviate (default: `False`) Enabling this allows option names to be abbreviated to uniqueness (e.g. `--foo` can be written as `--f` if no other option starts with an `f`). * compat-builtin (default: `False`) Enable all compatibility options that make argument parsing more like the builtin argument parsing. Currently that means disabling `bundling` and `permute`, and enabling `compat-singles`, `compat-negation`, `compat-positional` and `auto-help`) * bundling (default: `!$compat-builtin`) Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options *must* be introduced with `--` and bundles with `-`. Note that, if you have options `a`, `l` and `all`, possible arguments and option settings are: using argument sets option(s) ------------------------------- -a, --a a -l, --l l -all a, l --all all * permute (default: `!$compat-builtin`) Whether command line arguments are allowed to be mixed with options. Default is enabled unless `$compat-builtin` is set. If `permute` is enabled, this means that --foo arg1 --bar arg2 arg3 is equivalent to --foo --bar arg1 arg2 arg3 * compat-singles (default: `$compat-builtin`) Enabling this will allow single letter arguments with an `=` between the letter and its argument. E.g. `-j=2` instead of `-j2`. This is for compatibility with raku's built-in argument parsing. * compat-negation (default: `$compat-builtin`) Enabling this will allow one to one to use `--/foo` as an alias for `--no-foo`, for compatibility with raku's built-in argument parsing. Note that this still requires the presence of a `--no-foo` handler, typically by using the `!` modifier. * compat-positional (default: `$compat-builtin`) Enabling this will turn all positional arguments into allomorphs, if possible. * compat-space (default: `$compat-builtin`) By default, an option with an optional argument will take that as a separate argument unless that argument starts with `--`; e.g. `--foo bar`. If this option is enabled, no such separate arguments are allowed, and the only way to express such an argument is in the same argument: `--foo=bar`. * auto-help (default: `$compat-builtin`) This adds an extra --help option, that can hook into Raku's built-in usage message generator. Return values and Errors ======================== `get-options` returns a capture to indicate success, or throws an `Getopt::Long::Exception` otherwise. Troubleshooting =============== `get-options` does not fail when an option is not supplied ---------------------------------------------------------- That's why they're called 'options'. `get-options` does not split the command line correctly ------------------------------------------------------- The command line is not split by get-options, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is CMD.EXE. Other operating systems have other CLIs. It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (`'`) and double quotes (`"`) to group words together. The following alternatives are equivalent on Unix: "two words" 'two words' two\ words In case of doubt, insert the following statement in front of your Perl program: note @*ARGS.join('|'); to verify how your CLI passes the arguments to the program. AUTHOR ====== Leon Timmermans raku-getopt-long-0.4.2/lib/000077500000000000000000000000001437317564100154755ustar00rootroot00000000000000raku-getopt-long-0.4.2/lib/Getopt/000077500000000000000000000000001437317564100167375ustar00rootroot00000000000000raku-getopt-long-0.4.2/lib/Getopt/Long.rakumod000066400000000000000000001251071437317564100212300ustar00rootroot00000000000000use v6; use fatal; unit class Getopt::Long:ver<0.4.2>; class Exception is CORE::Exception { has Str:D $.message is required; method new(Str $message) { return self.bless(:$message); } } role FormattableException is Exception { has Str:D $.format is required; method new(Str $format) { my $message = $format.sprintf('some'); return self.bless(:$format, :$message); } method rethrow-with(Str $name) { die Exception.new($!format.sprintf($name)); } } class ValueInvalid does FormattableException { } class ConverterInvalid does FormattableException { } sub convert(Any:D $value, Code:D $converter) { return $converter($value); CATCH { when X::Str::Numeric { die ValueInvalid.new(qq{Cannot convert %s argument "$value" to number: $_.reason()}); } when X::Numeric::CannotConvert { die ValueInvalid.new("Cannot convert %s argument $_.source() to {$_.target // $_.target.perl}: $_.reason()"); } when X::Temporal { die ValueInvalid.new(.message.subst(/'string ' ( \' .* \' ) <.before ';'> /, { "$0 given as %s argument" })); } when FormattableException { .rethrow; } default { die ValueInvalid.new("Can not convert %s argument \"$value\": {.message}"); } } } sub convert-with(Any:D $value, Code:D $converter, Str:D $name) { CATCH { when ValueInvalid { .rethrow-with($name) } } return convert($value, $converter); } my role Store { has Str:D $.key is required; has Code:D $.converter = *.self; has Junction:D $.constraints = all(); has Hash $.values is required; method check-constraints(Any:D $value) { die ValueInvalid.new(qq{Can't accept %s argument "$value" because it fails its constraints}) unless $value ~~ $!constraints; } method store-convert(Str:D $value) { self.store-direct(convert($value, $!converter)); } method store-direct(Any:D $value) { ... } } my class ScalarStore does Store { method store-direct(Any:D $value) { self.check-constraints($value); $!values{$!key} = $value; } } my class CountStore does Store { method store-direct(Int:D $value) { $!values{$!key} += $value; } } my class ArrayStore does Store { has Any:U $.type = Str; method store-direct(Any:D $value) { self.check-constraints($value); $!values{$!key} //= $!type === Any ?? Array !! Array[$!type].new; $!values{$!key}.push($value); } } my class HashStore does Store { has Any:U $.type = Str; method store-convert(Any:D $pair) { my ($key, $value) = $pair.split('=', 2); my $converted-value = convert($value, $!converter); self.check-constraints($converted-value); $!values{$!key} //= $!type === Any ?? Hash !! Hash[$!type].new; $!values{$!key}{$key} = $converted-value; } method store-direct(Any:D $pair) { !!! } } my class Receiver { has Range:D $.arity is required; has Store:D $.store is required; has Any $.default; method store(Any:D $raw) { $!store.store-convert($raw); } method store-default() { $!store.store-direct($!default); } } sub get-converter(Any:U $type) { state %converter-for-type{Any:U} = ( Pair.new(Int, *.Int), Pair.new(Rat, *.Rat), Pair.new(Num, *.Num), Pair.new(Real, *.Real), Pair.new(Numeric, *.Numeric), Pair.new(Complex, *.Complex), Pair.new(Str, *.Str), Pair.new(IO::Path, *.IO), Pair.new(IO, *.IO), Pair.new(DateTime, *.DateTime), Pair.new(Date, *.Date), Pair.new(Version, *.Version), Pair.new(Any, &val), ); state $coercion-how = try ::("Metamodel::CoercionHOW"); if %converter-for-type{$type} -> &converter { return &converter; } elsif $type.HOW ~~ $coercion-how { my &primary = get-converter($type.^constraint_type()); return %converter-for-type{$type} = sub coercion-converter(Any $input) { my $primary = primary($input); return $primary ~~ $type.^target_type ?? $primary !! $type.^coerce($primary); } } elsif $type.HOW ~~ Metamodel::EnumHOW { sub valid-values() { my @keys = $type.WHO.keys.sort({ $type.WHO{$^value} }); my @pairs = @keys.map: { sprintf('%s(%s)', $^key, $type.WHO{$^key}.value) }; return @pairs.join(', '); } return %converter-for-type{$type} = sub enum-converter(Any $value) { return $type.WHO{$value} // $type.^enum_from_value($value) // die ValueInvalid.new(qq{Can't convert %s argument "$value" to $type.^name(), valid values are: &valid-values()}); } } else { die ConverterInvalid.new("No argument conversion known for %s argument (type {$type.^name})"); } } role Argument { has Junction:D $.constraints = all(); } multi get-transformer(Argument $) { return Nil; } role Argument::Valued does Argument { has Any:U $.type = Str; has Code:D $.converter = get-converter($!type); } class Argument::Boolean does Argument { has Bool:D $.negatable = False; } multi make-receivers(Argument::Boolean $arg, Str:D $key, @names, %values) { my $store = ScalarStore.new(:$key, :constraints($arg.constraints), :%values); gather for @names -> $name { take $name => Receiver.new(:$store, :arity(0..0), :default); if $arg.negatable { take "no$name" => Receiver.new(:$store, :arity(0..0), :!default); take "no-$name" => Receiver.new(:$store, :arity(0..0), :!default); } } } class Argument::Scalar does Argument::Valued { has Any $.default; } multi make-receivers(Argument::Scalar $arg, Str:D $key, @names, %values) { my $store = ScalarStore.new(:$key, :converter($arg.converter), :constraints($arg.constraints), :%values); my $arity = $arg.default.defined ?? 0..1 !! 1..1; return @names.map: { $^name => Receiver.new(:$store, :$arity, :default($arg.default)) } } role Argument::Composite does Argument::Valued { has Code $.transformer; } multi get-transformer(Argument::Composite $arg) { return $arg.transformer; } class Argument::Array does Argument::Composite { has Range:D $.arity = 1..1; } multi make-receivers(Argument::Array $arg, Str:D $key, @names, %values) { my $store = ArrayStore.new(:$key, :type($arg.type), :converter($arg.converter), :constraints($arg.constraints), :%values); return @names.map: { $^name => Receiver.new(:$store, :arity($arg.arity)) } } class Argument::Hash does Argument::Composite { } multi make-receivers(Argument::Hash $arg, Str:D $key, @names, %values) { my $store = HashStore.new(:$key, :type($arg.type), :converter($arg.converter), :constraints($arg.constraints), :%values); return @names.map: { $^name => Receiver.new(:$store, :arity(1..1)) } } class Argument::Counter does Argument { has Any:U $.type = Int; has Code:D $.converter = get-converter($!type); has Bool:D $.argumented = False; } multi make-receivers(Argument::Counter $arg, Str:D $key, @names, %values) { my $store = CountStore.new(:$key, :converter($arg.converter), :constraints($arg.constraints), :%values); my $arity = $arg.argumented ?? 0..1 !! 0..0; return @names.map: { $^name => Receiver.new(:$store, :$arity, :1default) } } multi get-transformer(Argument::Counter $arg) { return $arg.converter; } my rule name { [\w+]+ % '-' | '?' } class Option { has Str @.names is required; has Str:D $.key is required; has Argument $.argument; has Str $.why; submethod TWEAK(:@names) { die Exception.new('No name given for option') if @names < 1; die Exception.new("Invalid name(s): @names[]") if any(@names) !~~ &name; } multi method new(:@names!, :$argument!, Str :$key = @names[0], Str :$why) { return self.bless(:@names, :$key, :$argument, :$why); } multi method new(:$name!, :$argument!, Str :$why) { return self.bless(:names[$name], :key($name), :$argument, :$why); } } class Ordered { has Str:D $.name = 'some'; has Any:U $.type = Str; has Code:D $.converter = get-converter($!type); has Str $.why; method type-name() { $!type.^name } } has Option:D @.options is required; has Ordered:D @.positionals; has Str $.slurpy; method new-from-objects(Getopt::Long:U: @options, @positionals?) { return self.bless(:@options, :@positionals); } my %argument-for = ( '%' => Argument::Hash, '@' => Argument::Array, '$' => Argument::Scalar, '' => Argument::Scalar, ); my sub type-for-format(Str:D $format) { state %type-for-format = i => Int, o => Int, # compatability with p5 s => Str, f => Num, r => Rat, c => Complex, p => IO::Path, d => DateTime, a => Date, v => Version; die ConverterInvalid.new("No such format $format for %s") if not %type-for-format{$format}:exists; return %type-for-format{$format}; }; my grammar Parser { token TOP { { make Option.new(:names($.ast), :argument($.ast)); } } token names { + % '|' { make @».Str.list } } token argument { [ | | | | | | ] { make $/.values[0].made } } token boolean { $=['!'?] { make Argument::Boolean.new(:negatable(?$)) } } token counter { '+' { make Argument::Counter.new } } token type { { make type-for-format(~$/) } } token equals { '=' $=[<[%@]>?] { make %argument-for{~$}.new(:type($.ast)) } } rule range { | $=\d* ',' $=\d* { make ( +$ ) .. ($ ?? +$ !! *) } | $=\d+ { make $/.Int..$/.Int } } token equals-more { '=' '{' '}' { make Argument::Array.new(:type($.ast), :arity($.ast)) } } token colon-type { ':' { make Argument::Scalar.new(:type($.ast), :default($.ast.new)) } } token colon-int { ':' $=[<[0..9]>+] { make Argument::Scalar.new(:type(Int), :default($.Int)) } } token colon-count { ':+' { make Argument::Counter.new(:argumented) } } } our sub parse-option(Str $pattern) { CATCH { when ConverterInvalid { .rethrow-with("pattern $pattern") }} with Parser.parse($pattern) -> $match { return $match.ast; } else { die Exception.new("Couldn't parse argument specification '$pattern'"); } } sub make-positional(Any:U $type, Str $name, Str $why) { CATCH { when ConverterInvalid { .rethrow-with($name); }} my $converter = get-converter($type); return Ordered.new(:$name, :$type, :$converter, :$why); } my Str @ordinals = ... *; method new-from-patterns(Getopt::Long:U: @patterns, Str:D :$positionals = "") { my @options = @patterns.map(&parse-option); my @positional-types = $positionals.comb.map(&type-for-format); my @positionals = @positional-types Z[&make-positional] @ordinals; return self.bless(:@options, :@positionals); } my role Formatted::Named { has Argument $.argument is required; } multi sub trait_mod:(Parameter $param, Argument :option($argument)!) is export(:DEFAULT, :traits) { return $param does Formatted::Named(:$argument); } our sub parse-argument(Str $pattern, Str $name) { CATCH { when ConverterInvalid { .rethrow-with("parameter {$name}") }} with Parser.parse($pattern, :rule('argument')) -> $match { return $match.ast; } else { die Exception.new("Couldn't parse parameter $name\'s argument specification '$pattern'"); } } multi sub trait_mod:(Parameter $param where $param.named, Str:D :getopt(:$option)!) is export(:DEFAULT, :traits) { my $argument = parse-argument($option, $param.named_names[0]); return $param does Formatted::Named(:$argument); } multi sub trait_mod:(Parameter $param where $param.named, Code:D :$option!) is export(:DEFAULT, :traits) { my $element-type = $param.sigil eq '@'|'%' ?? $param.type.of !! $param.type; my $type = $element-type ~~ Any ?? $element-type !! Any; my $converter = sub ($value) { $option($value) orelse die ValueInvalid("Can't convert %s argument") }; my $argument = %argument-for{$param.sigil}.new(:$type, :$converter); return $param does Formatted::Named(:$argument); } multi sub trait_mod:(Parameter $param where $param.named, :%option!) is export(:DEFAULT, :traits) { %option //= %option.WHAT with %option; my $argument = %argument-for{$param.sigil}.new(|%option); return $param does Formatted::Named(:$argument); } multi get-reason(Pod::Block::Declarator:D $declarator) { return $declarator.trailing // $declarator.leading; } multi get-reason(Any:U $declarator) { return Str; } my role Formatted::Positional { has Ordered $.argument is required; } multi sub trait_mod:(Parameter $param where $param.positional, Ordered:D :$option!) is export(:DEFAULT, :traits) { return $param does Formatted::Positional($option); } multi sub trait_mod:(Parameter $param where $param.positional, Str:D :$option!) is export(:DEFAULT, :traits) { CATCH { when ConverterInvalid { .rethrow-with("parameter $param.name()") }} my $argument = Ordered.new(:name($param.usage-name), :type(type-for-format($option)), :why(get-reason($param.WHY))); return $param does Formatted::Positional($argument); } multi sub trait_mod:(Parameter $param where $param.positional, Code:D :$option!) is export(:DEFAULT, :traits) { my $converter = sub ($value) { $option($value) orelse die ValueInvalid("Can't convert %s argument") }; my $argument = Ordered.new(:name($param.usage-name), :type($param.type), :$converter, :why(get-reason($param.WHY))); return $param does Formatted::Positional($argument); } role Custom { method get-argument-for(Parameter $param) { ... } } multi get-argument(Parameter $param) { if $param.sigil eq '$' { my $type = $param.type; my $constraints = $param.constraints; if $type === Bool { return Argument::Boolean.new(:$constraints, :negatable(?$param.default)); } elsif $type ~~ Custom { return $type.get-argument-for($param); } else { return Argument::Scalar.new(:$type, :$constraints); } } else { my $type = $param.type.of ~~ Any ?? $param.type.of !! Any; return %argument-for{$param.sigil}.new(:$type); } CATCH { when ConverterInvalid { .rethrow-with("parameter {$param.name}"); }} } multi get-argument(Parameter $param where Formatted::Named) { return $param.argument; } sub make-option(Parameter $param) { return Option.new(:names($param.named_names), :argument(get-argument($param)), :why(get-reason($param.WHY))); } multi get-positional-object(Parameter $parameter) { return make-positional($parameter.type, $parameter.usage-name, get-reason($parameter.WHY)); } multi get-positional-object(Parameter $param where Formatted::Positional) { return $param.argument; } my role Parsed { has Getopt::Long:D $.getopt is required; } multi get-from-sub(&candidate) { my @params = &candidate.signature.params; my @options = @params.grep(*.named).map(&make-option); my @positionals = @params.grep(*.positional).map(&get-positional-object); my ($slurpy) = @params.grep({ $^param.slurpy and not $^param.named }).map(*.usage-name)[0] // Str; return Getopt::Long.bless(:@options, :@positionals, :$slurpy); } multi get-from-sub(&candidate where Parsed) { return &candidate.getopt; } multi sub trait_mod:(Sub $sub, Bool :$getopt!) is export(:DEFAULT, :traits) { return $sub does Parsed(get-from-sub($sub)); } multi sub trait_mod:(Sub $sub, :@getopt!) is export(:DEFAULT, :traits) { return $sub does Parsed(Getopt::Long.new-from-patterns(@getopt)); } multi sub trait_mod:(Sub $sub, Getopt::Long:D :$getopt!) is export(:DEFAULT, :traits) { return $sub does Parsed($getopt); } sub merge-named-objects(@options-for) { my %unique; for @options-for -> @option-set { for @option-set -> $option { for $option.names -> $name { die "Can't merge unequal options for --$name" if %unique{$name}:exists and %unique{$name} !eqv $option; %unique{$name} = $option; } } } return %unique.values; } sub merge-positional-object(@positionals-for, $elems) { my @positionals = @positionals-for.grep(* > $elems)»[$elems]; die Exception.new("@ordinals[$elems].tc() arguments are of different types: { @positionals».type-name.join(', ') }") unless [eqv] @positionals».converter; return @positionals[0]; } sub merge-positional-objects(@positionals-for) { my $elem-max = @positionals-for».elems.max; return (^$elem-max).map: { merge-positional-object(@positionals-for, $^elem) }; } sub merge-parsers(Getopt::Long @parsers) { my @options = merge-named-objects(@parsers».options); my @positionals = merge-positional-objects(@parsers».positionals); return Getopt::Long.bless(:@options, :@positionals); } method new-from-sub(Getopt::Long:U: Sub $main) { my Getopt::Long @parsers = $main.candidates.map(&get-from-sub); return @parsers > 1 ?? merge-parsers(@parsers) !! @parsers[0]; } method get-options(Getopt::Long:D: @args is copy, :%hash, :$auto-abbreviate = False, :$compat-builtin = False, :named-anywhere(:$permute) = !$compat-builtin, :$bundling = !$compat-builtin, :$compat-singles = $compat-builtin, :$compat-negation = $compat-builtin, :$compat-positional = $compat-builtin, :$compat-space = $compat-builtin, :$auto-help = $compat-builtin, :$write-args) { my @list; sub to-receivers(Option $option) { CATCH { when ConverterInvalid { .rethrow-with("--{$option.names[0]}") }} return make-receivers($option.argument, $option.key, $option.names, %hash); } my %receivers = @!options.flatmap(&to-receivers); while @args { my $head = @args.shift; my $consumed = 0; sub get-receiver(Str:D $key, Str:D $name) { with %receivers{$key} -> $option { return $option; } elsif $key eq 'help' && $auto-help { return Receiver.new(:store(ScalarStore.new(:key, :values(%hash))), :arity(0..0), :default); } elsif $auto-abbreviate { my @names = %receivers.keys.grep(*.starts-with($key)); if @names == 1 { return %receivers{ @names[0] }; } elsif @names > 1 { die Exception.new("Ambiguous partial option $name, possible interpretations: @names[]"); } else { die Exception.new("Unknown option $name"); } } else { die Exception.new("Unknown option $name"); } } sub take-value(Receiver:D $receiver, Str:D $value, Str:D $name) { CATCH { when ValueInvalid { .rethrow-with($name) } } $receiver.store($value); $consumed++; } sub take-args(Receiver:D $receiver, Str:D $name) { while @args && $consumed < $receiver.arity.min { take-value($receiver, @args.shift, $name); } while !$compat-space && @args && $consumed < $receiver.arity.max && !@args[0].starts-with('--') { take-value($receiver, @args.shift, $name); } if $consumed == 0 && $receiver.arity.min == 0 { $receiver.store-default(); } elsif $consumed < $receiver.arity.min { die Exception.new("The option $name requires a value but none was specified"); } } if $bundling && $head ~~ / ^ '-' $=[\w .* ] $ / -> $/ { my @values = $.Str.comb; for @values.keys -> $index { my $value = @values[$index]; my $receiver = get-receiver($value, "-$value"); if $receiver.arity.max > 0 && $index + 1 < @values.elems { my $offset = $compat-singles && @values[$index + 1] eq '=' ?? 2 !! 1; take-value($receiver, $.substr($index + $offset), "-$value"); } take-args($receiver, "-$value"); last if $consumed; } } elsif $compat-singles && $head ~~ / ^ '-' '=' $=[.*] / -> $/ { my $receiver = get-receiver(~$, "-$"); die Exception.new("Option -$ doesn't take an argument") if $receiver.arity.max != 1; take-value($receiver, ~$, "-$"); } elsif $head eq '--' { @list.append: |@args; last; } elsif $head ~~ / ^ '-' ** 1..2 $ / -> $/ { take-args(get-receiver(~$, ~$/), ~$/); } elsif $head ~~ / ^ $=[ '--' ] '=' $=[.*] / -> $/ { my $receiver = get-receiver(~$, ~$); die Exception.new("Option $ doesn't take arguments") if $receiver.arity.max == 0; take-value($receiver, ~$, ~$); take-args($receiver, ~$); } elsif $compat-negation && $head ~~ / ^ $=[ '-' ** 1..2 '/' ] ['=' $=[.*]]? $ / { if $ { my $receiver = get-receiver(~$, ~$); die Exception.new("Option $ doesn't take an argument") if $receiver.arity.max != 1; take-value($receiver, ~$ but False, ~$); } else { take-args(get-receiver('no-' ~ $, ~$), ~$); } } else { if $permute { @list.push: $head; } else { @list.append: $head, |@args; last; } } } for @!options -> $option { with get-transformer($option.argument) -> $transformer { my $key = $option.key; %hash{$key} = convert-with(%hash{$key}, $transformer, "--$key") if %hash{$key}:exists; } } my &fallback-converter = $compat-positional ?? &val !! *.self; my @positionals = @list.kv.map: -> $index, $value { with @!positionals[$index] -> $positional { convert-with($value, $positional.converter, $positional.name); } else { convert-with($value, &fallback-converter, @ordinals[$index]); } }; @$write-args = @list if $write-args; return \(|@positionals, |%hash); } our sub get-options-from(@args, *@elements, :$overwrite, *%config) is export(:DEFAULT, :functions) { my %hash := @elements && @elements[0] ~~ Hash ?? @elements.shift !! {}; my @options; for @elements { when Str { @options.push: parse-option($_); } when Pair { my $key = .key; my ($name) = .key ~~ / ^ (\w+) /[0]; %hash{$name} := .value; given .value { when Positional { $key ~= '@' unless $key.ends-with('@'|'}'); } when Associative { $key ~= '%' unless $key.ends-with('%'); } } @options.push: parse-option($key); } when Option { @options.push: $_; } default { die Exception.new("Unknown element type: " ~ .perl); } } my $getopt = Getopt::Long.new-from-objects(@options); return $getopt.get-options(@args, |%config, :%hash, :write-args($overwrite ?? @args !! Any)); } our sub get-options(|args) is export(:DEFAULT, :functions) { return get-options-from(@*ARGS, :overwrite, |args); } our sub call-with-getopt(&func, @args, %options = %*SUB-MAIN-OPTS // {}) is export(:DEFAULT, :functions) { my $capture = Getopt::Long.new-from-sub(&func).get-options(@args, |%options); return func(|$capture); } our sub ARGS-TO-CAPTURE(Sub $func, @args) is export(:DEFAULT, :MAIN) { my %options = %*SUB-MAIN-OPTS // {}; return Getopt::Long.new-from-sub($func).get-options(@args, |%options); CATCH { when Exception { note .message; &*EXIT(2) } }; } sub usage-name(@names) { if @names == 1 and @names[0].chars == 1 { return "-@names[0]"; } else { return '--' ~ @names.join('|'); } } sub describe-type(Any:U $type) { my $result = $type.^name; if $type.HOW ~~ Metamodel::EnumHOW { my $options = $type.^enum_values.keys.sort.Str; $result ~= $options.chars > 50 ?? ' (' ~ substr($options,0,50) ~ '...' !! " ($options)" } return $result; } multi description-for-argument(Argument::Scalar $argument) { with $argument.default { return "[&describe-type($argument.type)]"; } else { return describe-type($argument.type); } } multi description-for-argument(Argument::Boolean $argument) { return Str; } multi description-for-argument(Argument::Counter $argument) { return Str; } multi description-for-argument(Argument::Array $argument) { return describe-type($argument.type) ~ '...'; } multi description-for-argument(Argument::Hash $argument) { return "=" ~ describe-type($argument.type) ~ '...'; } sub usage-for-named(Option $option) { my $name = usage-name($option.names.reverse); my $description = description-for-argument($option.argument); return $description.defined ?? "$name $description" !! $name; } multi describe-options(@options) { if any(@options).why { my @pairs = gather for @options -> $option { my $lead = usage-for-named($option); my $reason = $option.why // ''; take ($lead, $reason); } my $width = max(@pairs.map(*.[0].chars)); return @pairs.map: -> ($left, $right) { sprintf '%-*s %s', $width + 1, $left, $right }; } else { return @options.map(&usage-for-named); } } our sub generate-usage(&main, :$program-name = $*PROGRAM.basename) is export(:usage, :functions) { my $getopt = Getopt::Long.new-from-sub(&main); my @positionals = $getopt.positionals; my @positional-descs = $getopt.positionals.map({ "<$^positional.name()>" }); @positional-descs.push: "<$getopt.slurpy()>..." with $getopt.slurpy; my @options = $getopt.options; my @option-descs = describe-options($getopt.options); if $program-name.chars + @option-descs.join(' ').chars > 72 or any(@options).why { my @lines = flat "Usage:", ('', $program-name, '[options...]', |@positional-descs).join(' '), '', @option-descs.map(*.indent(4)); return @lines.join("\n"); } else { my @main = ('', $program-name, |@option-descs.map({ "[$^option]" }), |@positional-descs); return "Usage:\n" ~ @main.join(' '); } } our sub GENERATE-USAGE(&main, |capture) is export(:usage) { return generate-usage(&main); } =begin pod =head1 NAME Getopt::Long =head1 SYNOPSIS use Getopt::Long; get-options("length=i" => my $length, # numeric "file=s" => my $file, # string "verbose" => my $verbose); # flag use Getopt::Long; my $options = get-options("length=i", # numeric "file=s", # string "verbose"); # flag or use Getopt::Long; sub MAIN(Int :$length, Str :$file, Bool :$verbose) { ... } =head1 DESCRIPTION The Getopt::Long module implements extended getopt functions called C and C, as well as automatic argument parsing for a C
sub. This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is also provided. =head1 Command Line Options, an Introduction Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line I as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did. Command line options come in several flavours. Historically, they are preceded by a single dash C<->, and consist of a single letter. -l -a -c Usually, these single-character options can be bundled: -lac Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not: -s 24 -s24 Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic C<-l> one could use the more descriptive C<--long>. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Also, option values could be specified either like --size=24 or --size 24 =head1 Getting Started with Getopt::Long To use Getopt::Long from a Raku program, you must include the following line in your program: use Getopt::Long; This will load the core of the Getopt::Long module and prepare your program for using it. =head2 Getopt::Long as a MAIN wrapper Getopt::Long can be used as a argument parsing MAIN wrapper, replacing the builtin argument parsing. It will by default offer a Unix-typical command line interface, but various options allow it to be more similar to Raku's ideosyncratic parsing. It supports the following types for named and positional arguments: =item Bool =item Any =item Str =item Int =item Rat =item Num =item Real =item Numeric =item Complex =item IO::Path =item DateTime =item Date =item Version It also supports any enum type, and any coercion type that uses any of the aforementioned types as its contraint type (e.g. C). An explicit converter can also be set using an `is option` trait, e.g. sub MAIN(Foo :$foo is option(&foo-converter)) { ... } =head2 Simple options The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are: --all --verbose --quiet --debug Handling simple options is straightforward: sub MAIN(Bool :$verbose, Bool :$all) { ... } or: get-options('verbose' => my $verbose, 'all' => my $all); The call to C parses the command line arguments that are present in C<@*ARGS> and sets the option variable to the value C if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called I the option. The option name as specified to the C function is called the option I. Later we'll see that this specification can contain more than just the option name. C will return a C if the command line could be processed successfully. Otherwise, it will throw an error using die(). =head2 A little bit less simple options Getopt::Long supports two useful variants of simple options: I options and I options. A negatable option is specified with an exclamation mark C after the option name or a default value for C
argument: sub MAIN(Bool :$verbose = False) { ... } or: get-options('verbose!' => my $verbose); or: my $options = get-options('verbose!'); Now, using C<--verbose> on the command line will enable C<$verbose>, as expected. But it is also allowed to use C<--noverbose> or C<--no-verbose>, which will disable C<< $verbose >> by setting its value to C. An incremental option is specified with a plus C<+> after the option name: sub MAIN(Int :$verbose is option('+')) { ... } or: get-options('verbose+' => my $verbose); or my $options = get-options('verbose+'); Using C<--verbose> on the command line will increment the value of C<$verbose>. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of C<--verbose> could increase the verbosity level of the program. =head2 Mixing command line option with other arguments Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash C<--> on the command line: --size 24 -- --all In this example, C<--all> will I be treated as an option, but passed to the program unharmed, in C<@*ARGS>. =head2 Options with values For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects. Three kinds of values are supported: integer numbers, floating point numbers, and strings. If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself. sub MAIN(Str :$tag) { ... } or get-options('tag=s' => my $tag); or my %options = get-options('tag=s'); In the option specification, the option name is followed by an equals sign C<=> and the letter C. The equals sign indicates that this option requires a value. The letter C indicates that this value is an arbitrary string. Other possible value types are C for integer values, and C for floating point values. Using a colon C<:> instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string C<''> assigned, while numeric options are set to C<0>. =head2 Options with multiple values Options sometimes take several values. For example, a program could use multiple directories to search for library files: --library lib/stdlib --library lib/extlib You can specify that the option can have multiple values by adding a "@" to the format, or declare the argument as positional: sub MAIN(Str :@library) { ... } or get-options('library=s@' => my @libraries); or my $options = get-options('library=s@'); Used with the example above, C<@libraries>/C<$options> would contain two strings upon completion: C<"lib/stdlib"> and C<"lib/extlib">, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values. Warning: What follows is an experimental feature. Options can take multiple values at once, for example --coordinates 52.2 16.4 --rgbcolor 255 255 149 This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the C<{...}> repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows: my $options = get-options('coordinates=f{2}', 'rgbcolor=i{3}'); or sub MAIN(Rat :@coordinates is option('f{2}'), Int :@rgbcolor is option('i{3}')) get-options('coordinates=f{2}' => my @coordinates, 'rgbcolor=i{3}' => my @rgbcolor); It is also possible to specify the minimal and maximal number of arguments an option takes. C indicates an option that takes at least two and at most 4 arguments. C indicates one or more values; C indicates zero or more option values. =head2 Options with hash values If you specify that the option can have multiple named values by adding a "%": sub MAIN(Str :%define) { ... } or get-options("define=s%" => my %define); or my $options = get-options("define=s%"); When used with command line options: --define os=linux --define vendor=redhat the hash C<%defines> or C<< $options >> will contain two keys, C<"os"> with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings. =head2 Options with multiple names Often it is user friendly to supply alternate mnemonic names for options. For example C<--height> could be an alternate name for C<--length>. Alternate names can be included in the option specification, separated by vertical bar C<|> characters. To implement the above example: sub MAIN(:height(:$length)) { ... } or get-options('length|height=f' => my $length); or $options = get-options('length|height=f'); The first name is called the I name, the other names are called I. When using a hash to store options, the key will always be the primary name. Multiple alternate names are possible. =head2 Summary of Option Specifications Each option specifier consists of two parts: the name specification and the argument specification. The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters. length option name is "length" length|size|l name is "length", aliases are "size" and "l" The argument specification is optional. If omitted, the option is considered boolean, a value of C will be assigned when the option is used on the command line. The argument specification can be =begin item ! The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well. =end item =begin item + The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. C<"more+">, when used with C<--more --more --more>, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at firs). The C<+> specifier is ignored if the option destination is not a scalar. =end item =begin item = I [ I ] [ I ] The option requires an argument of the given type. Supported types are: =begin item2 s String(C). An arbitrary sequence of characters. It is valid for the argument to start with C<-> or C<-->. =end item2 =begin item2 i Integer (C). This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (C<0o>, optionally followed by '0', '1', .. '7'), or a hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (C<0b> followed by a series of '0' and '1'). =end item2 =begin item2 r Rational number (C). For example C<3.14>. =end item2 =begin item2 f Floating-pointer number (C). For example C<3.14>, C<-6.23E24> and so on. =end item2 =begin item2 c Complex number (C). For example C<1+2i>. =end item2 =begin item2 p Path (C). For example C. =end item2 =begin item2 d An ISO-8601 formatted date and time (C). For example C<2019-12-30T01:23:45-0700>. =end item2 =begin item2 a A ISO-8601 formatted date (C). For example C<2019-12-30>. =end item2 =begin item2 v A Version (C). For example C<1.2.3>. =end item2 The I can be C<@> or C<%> to specify that the option is list or a hash valued. The I specifies the number of values this option takes per occurrence on the command line. It has the format C<{> [ I ] [ C<,> [ I ] ] C<}>. I denotes the minimal number of arguments. It defaults to C<0>. I denotes the maximum number of arguments. It must be at least I. If I is omitted, I, there is no upper bound to the number of argument values taken. =end item =begin item : I [ I ] Like C<=>, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options. Note that if a string argument starts with C<-> or C<-->, it will be considered an option on itself. =end item =begin item : I [ I ] Like C<:i>, but if the value is omitted, the I will be assigned. =end item =begin item : + [ I ] Like C<:i>, but if the value is omitted, the current value for the option will be incremented. =end item =head1 Advanced Possibilities =head2 Object oriented interface Getopt::Long can be used in an object oriented way as well: use Getopt::Long; my $p = Getopt::Long.new-from-patterns(@options); my $o = $p.get-options(@args) ... Configuration options can be passed to the constructor as named arguments: $p = Getopt::Long.new-from-patterns(@options, :!permute); =head2 Parsing options from an arbitrary array By default, get-options parses the options that are present in the global array C<@*ARGS>. A special entry C can be used to parse options from an arbitrary array. use Getopt::Long; $ret = get-options-from(@myargs, ...); The following two calls behave identically: $ret = get-options( ... ); $ret = get-options-from(@*ARGS, :overwrite, ... ); =head1 Configuring Getopt::Long C and C take the following named options to configure. When using Getopt::Long as a C
wrapper, you can set them using the C<%*SUB-MAIN-OPTS> variable: =begin item auto-abbreviate (default: C) Enabling this allows option names to be abbreviated to uniqueness (e.g. `--foo` can be written as `--f` if no other option starts with an `f`). =end item =begin item compat-builtin (default: C) Enable all compatibility options that make argument parsing more like the builtin argument parsing. Currently that means disabling C and C, and enabling C, C, C and C) =end item =begin item bundling (default: C) Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options I be introduced with C<--> and bundles with C<->. Note that, if you have options C, C and C, possible arguments and option settings are: using argument sets option(s) ------------------------------- -a, --a a -l, --l l -all a, l --all all =end item =begin item permute (default: C) Whether command line arguments are allowed to be mixed with options. Default is enabled unless C<$compat-builtin> is set. If C is enabled, this means that --foo arg1 --bar arg2 arg3 is equivalent to --foo --bar arg1 arg2 arg3 =end item =begin item compat-singles (default: C<$compat-builtin>) Enabling this will allow single letter arguments with an C<=> between the letter and its argument. E.g. C<-j=2> instead of C<-j2>. This is for compatibility with raku's built-in argument parsing. =end item =begin item compat-negation (default: C<$compat-builtin>) Enabling this will allow one to one to use C<--/foo> as an alias for C<--no-foo>, for compatibility with raku's built-in argument parsing. Note that this still requires the presence of a C<--no-foo> handler, typically by using the C modifier. =end item =begin item compat-positional (default: C<$compat-builtin>) Enabling this will turn all positional arguments into allomorphs, if possible. =end item =begin item compat-space (default: C<$compat-builtin>) By default, an option with an optional argument will take that as a separate argument unless that argument starts with C<-->; e.g. C<--foo bar>. If this option is enabled, no such separate arguments are allowed, and the only way to express such an argument is in the same argument: C<--foo=bar>. =end item =begin item auto-help (default: C<$compat-builtin>) This adds an extra --help option, that can hook into Raku's built-in usage message generator. =end item =head1 Return values and Errors C returns a capture to indicate success, or throws an C otherwise. =head1 Troubleshooting =head2 C does not fail when an option is not supplied That's why they're called 'options'. =head2 C does not split the command line correctly The command line is not split by get-options, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is CMD.EXE. Other operating systems have other CLIs. It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (C<'>) and double quotes (C<">) to group words together. The following alternatives are equivalent on Unix: "two words" 'two words' two\ words In case of doubt, insert the following statement in front of your Perl program: note @*ARGS.join('|'); to verify how your CLI passes the arguments to the program. =head1 AUTHOR Leon Timmermans =end pod raku-getopt-long-0.4.2/t/000077500000000000000000000000001437317564100151725ustar00rootroot00000000000000raku-getopt-long-0.4.2/t/basic.rakutest000066400000000000000000000151401437317564100200400ustar00rootroot00000000000000use v6; use Test; use Getopt::Long; my $capture = get-options-from(<--foo bar --fooo bar2 -f bar3 -ac --bar baz>, 'foo|f|fooo=s@', 'bar', 'a', 'c'); is-deeply($capture, \('baz', :bar, :a, :c, :foo(Array[Str].new())), 'Common argument mix works'); multi main(*@, Str :fooo(:f(:@foo)), Bool :$bar) is getopt { } multi main(*@, Bool :$a!, Bool :$c!, Bool :$d) { } my $getopt = Getopt::Long.new-from-sub(&main); my $capture2 = $getopt.get-options(<--foo bar --fooo bar2 --bar baz>); is-deeply($capture2, \('baz', :bar, :foo(Array[Str].new())), 'Common argument mix works (2)'); lives-ok( { main(|$capture2) }, 'Calling main (1) works'); my $capture3 = $getopt.get-options(<-ac -dfbar3>); is-deeply($capture3, \(:a, :c, :d, :foo(Array[Str].new())), 'Short options work'); my $capture4 = $getopt.get-options(<--foo bar --fooo bar2 -f bar3 -ac --bar baz>); dies-ok( { main(|$capture4) }, 'Calling main (1) works'); my $capture5 = $getopt.get-options(<--bar -- -a>); is-deeply($capture5, \('-a', :bar), '"--" terminates argument handling'); my $capture6 = get-options-from([<--quz=2.5>], 'quz=f'); is-deeply($capture6, \(:quz(2.5e0)), 'Floating point arguments work'); my $capture7 = get-options-from(['--quz'], 'quz:i'); is-deeply($capture7, \(:0quz), ':i without argument works'); my $capture8 = get-options-from(<--quz 2>, 'quz:i'); is-deeply($capture8, \(:2quz), ':i with argument works'); my $capture9 = get-options-from(['--quz'], 'quz:1'); is-deeply($capture9, \(:1quz), ':1 without argument works'); my $capture10 = get-options-from(<--quz 2>, 'quz:1'); is-deeply($capture10, \(:2quz), ':1 with argument works'); my $capture11 = get-options-from(<--foo --foo>, 'foo+'); is-deeply($capture11, \(:2foo), 'Counter adds up'); my $capture12 = get-options-from(['--foo'], 'foo:+'); is-deeply($capture12, \(:1foo), 'Colon singles fine'); my $capture13 = get-options-from(<--foo 2 --foo>, 'foo:+'); is-deeply($capture13, \(:3foo), 'Colon counter adds up'); my $capture14 = get-options-from(<--bar 0o12>, 'bar=i'); is-deeply($capture14, \(:10bar), 'Parsing octal argument with "i"'); my $capture15 = get-options-from(<--bar -0o12>, 'bar=i'); is-deeply($capture15, \(:bar(-10)), 'Parsing negative octal argument with "i"'); my $capture16 = get-options-from(<--bar 12>, 'bar=i'); is-deeply($capture16, \(:12bar), 'Parsing decimal argument with "i"'); my $capture17 = get-options-from(['--no-bar'], 'bar!'); is-deeply($capture17, \(:!bar), 'Negated arguments produce False'); my $capture18 = get-options-from(['-abc'], , :!bundling); is-deeply($capture18, \(:abc), 'Bundling can be disabled'); my $capture19 = get-options-from(['--foo', '1', '2', '3'], ); is-deeply($capture19, \('3', :foo(Array[Int].new(1, 2))), 'Repeat specifier works'); my $capture20 = get-options-from(['--foo', '1', '2', '3'], ); is-deeply($capture20, \('3', :foo(Array[Int].new(1, 2))), 'Repeat specifier works with range'); my sub main1(:$foo is option("=s%")) is getopt {}; ok(&main1.WHAT !=== Sub, 'sub main1 is not quite a Sub'); ok(&main1.WHAT.^name.contains('Parsed'), 'sub main1 is parsed'); my $getopt2 = Getopt::Long.new-from-sub(&main1); my $capture21 = $getopt2.get-options(<--foo bar=buz --foo qaz=quz>); my Str %expected = :bar('buz'), :qaz('quz'); is-deeply($capture21, \(:foo(%expected)), 'getopt trait works'); my $getopt3 = Getopt::Long.new-from-sub(sub (Bool :$foo = True) { }); my $capture22 = $getopt3.get-options(['--no-foo']); is-deeply($capture22, \(:!foo), 'negative argument detected'); get-options-from([<--foo>], 'foo' => my $foo); is-deeply($foo, True, 'Pair arguments'); get-options-from(<--foo 1 --foo 2>, 'foo=i@' => my @foo); is-deeply(@foo, [1, 2], 'Pair arguments'); my $capture23 = get-options-from(['--foo', '1+2i'], ); is-deeply($capture23, \(:foo(1+2i)), 'Repeat specifier works'); my $capture24 = get-options-from(['-f=1'], , :compat-singles); is-deeply($capture24, \(:f(1)), ':compat-singles appears to work'); my $capture25 = get-options-from(['-/f'], , :compat-negation); is-deeply($capture25, \(:!f), ':compat-negation works'); my $capture26 = get-options-from(['--/f=foo'], , :compat-negation); ok(!$capture26, 'compat negation delivers a false value'); is($capture26, 'foo', 'compat negation delivers the correct string'); my $getopt4 = Getopt::Long.new-from-sub(sub (Order :$order) { }); my $capture27 = $getopt4.get-options(<--order Same>); is($capture27, \(:order(Same)), 'Correctly parsed enum'); my $capture27b = $getopt4.get-options(<--order 0>); is($capture27b, \(:order(Same)), 'Correctly parsed enum'); my $getopt5 = Getopt::Long.new-from-sub(sub (Int $foo, Rat $bar) { }); my $capture28 = $getopt5.get-options(["1", "2.5"]); is($capture28, \(1, 2.5), 'Typed positionals work'); multi main2(Int $foo) { } multi main2(Int $foo, Rat $bar) { } my $getopt6 = Getopt::Long.new-from-sub(&main2); my $capture29 = $getopt5.get-options(["1", "2.5"]); is($capture29, \(1, 2.5), 'Typed positionals work on multis as well'); my $getopt7 = Getopt::Long.new-from-sub(sub (DateTime :$datetime) { }); my $capture30 = $getopt7.get-options(<--datetime 2015-11-21T08:01:00+0100 >); is($capture30, \(:datetime(DateTime.new(:2015year, :11month, :21day, :8hour, :1minute, :3600timezone))), 'Can parse DateTime'); my $capture31 = get-options-from(<--date 2015-11-21>, ); is-deeply($capture31, \(:date(Date.new(:2015year, :11month, :21day))), 'Can parse Date'); my $capture32 = get-options-from(<--lo --lon>, , :auto-abbreviate); is-deeply($capture32, \(:2long), 'Can auto-abbreviate'); class Foo { has Int:D $.value is required; method COERCE(Int(Str) $value) { return Foo.new(:$value); } } if $*RAKU.compiler.version after 2020.10 { my $getopt8 = Getopt::Long.new-from-sub(sub (Foo(Str) :$foo) { }); my $capture33 = $getopt8.get-options(['--foo', '1']); is-deeply($capture33, Foo.new(:value(1)), 'Parse a custom parseable type'); throws-like({ call-with-getopt(sub (Signature(Str) :$bar) { dd $bar }, ['--bar', '1']); }, Getopt::Long::Exception, 'No conversion known for type Signature'); } my $capture34 = get-options-from(['-vjb'], ); is-deeply($capture34, \(:v, :j), 'Bundled options with arguments work'); my $capture35 = get-options-from(<--foo baz --bar>, , :!permute); is-deeply($capture35, \(:foo, 'baz', '--bar'), ':!permute works'); my $getopt9 = Getopt::Long.new-from-sub(sub (Str :$foo is option(*.flip)) {}); my $capture36 = $getopt9.get-options(<--foo bar>); is-deeply($capture36, \(:foo), 'Custom converter works'); my $capture37 = get-options-from(['--foo', '2'], , :compat-space); is-deeply($capture37, \('2', :1foo), ''); done-testing;