-
Define your command line specification:
require 'ruby-getoptions' options, remaining = GetOptions.parse(ARGV, { "f|flag" => :flag, "string=s" => :string, "int=i" => :int, "float=f" => :float, "procedure" => lambda { puts 'Hello world! :-)' } "help" => lambda { print_synopsis() } "man" => lambda { launch_manpage() }, "version" => lambda { puts 'Version is 0.1' }, })
-
Pass cmdline arguments:
$ ./myscript non-option -f --string=mystring -i 7 --float 3.14 --p --version non-option2 -- --nothing
-
It will run the higher order functions that were called on the cmdline:
Hello world! Version is 0.1
-
Internally it will return an array with the arguments that are not options and anything after the
--
identifier, and a Hash with the values of the options that were passed:remaining = ['non-option', 'non-option2', '--nothing'] options = {:flag => true, :string => 'mystring', :int => 7, :float => 3.14}
require 'ruby-getoptions'
options, remaining = GetOptions.parse(ARGV, {
"alias|name" => :option_with_aliases,
"flag" => :flag,
"nflag!" => :negatable_flag,
"procedure" => lambda { puts 'Hello world! :-)' },
"string=s" => :required_string,
"int=i" => :required_int,
"float=f" => :required_float,
"o_string:s" => :optional_string,
"o_int:i" => :optional_int,
"o_float:f" => :optional_float,
"a_string=s@" => :string_array,
"a_int=i@" => :int_array,
"a_float=f@" => :float_array,
"ar_string=s@{3,5}" => :string_array_with_repeat,
"ar_int=i@{3,5}" => :int_array_with_repeat,
"ar_float=f@{3,5}" => :float_array_with_repeat,
"h_string=s%" => :string_hash,
"h_int=i%" => :int_hash,
"h_float=f%" => :float_hash,
"hr_string=s%{3,5}" => :string_hash_with_repeat,
"hr_int=i%{3,5}" => :int_hash_with_repeat,
"hr_float=f%{3,5}" => :float_hash_with_repeat
}, {fail_on_unknown: true})
- Name specification
-
Unique list of names to call the option through the command line. Each alias is separated by
|
. - Argument_specification
-
Arg specification Arg spec options Description Flag, Empty argument specification
!
Negatable Flag, Flag that can also be negated. Use with
--no
of--no-
.= type [destype] [repeat]
- type
-
s
,i
,f
- destype
-
@
,%
. - repeat
-
{ [ min ] [ , [ max ] ] }
.
Required argument, argument must be present.
: type [destype]
- type
-
s
,i
,f
- destype
-
@
- repeat
-
{ [ min ] [ , [ max ] ] }
.
Optional argument, argument will default to String
''
, Int0
, or Float0
if not present.NoteHash argument specification is not supported in this mode because there are no reasonable defaults to add.
- Options
-
fail_on_unknown
,pass_through
.
It will take an Array[String]
(normally ARGV
) and a Hash[String, Object]
(option definition) and it will return a Hash[Symbol, Object]
(options) of the given arguments and an Array[String]
(remaining) of the remaining arguments.
It will also excecute any procedures (lamba, procedure, method) in the order their corresponding options were passsed on the command line, and only if they were passed (using the call
method).
GetOptions.parse
will abort
or fail
if the command line options could not be processed successfully (input error), or if they were defined improperly. See Errors and Exceptions for details.
Each Option definition (one key value pair in the Hash) is composed of two elements, the key, referred to as option specification, and the value, referred to as option destination.
require 'ruby-getoptions'
options, remaining = GetOptions.parse(ARGV, {
key => value, # (1)
option_specification => option_destination # (2)
})
-
Each key, value pair is called an Option definition.
-
The key is the Option specification and the value is the Option destination.
Each option specification 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 or aliases separated by vertical bar characters |
.
The argument specification contains the type of option and whether or not it takes any arguments and how many.
The option destination can be either a Symbol
or a procedure (only for Flags). If a Symbol
, it will be the Symbol
used to access the resulting value of the command line parameters passed. If a procedure, it will be called if the name of the option was passed in the command line.
For example, for the following option definition:
'entry|input=s' ⇒ :data
The name specification is entry
with an alias of input
, the argument specification is =s
(required string), and the option destination is :data
. If either entry
or input
is passed on the command line, the Symbol
:data
will be set to the String
argument passed with the option.
As another example, for the following option definition:
'version' ⇒ lambda { puts 'Version is 0.1' }
The option name is version
, the option specification is empty (flag), and the option destination is lambda { puts 'Version is 0.1' }
. If version
is passed on the command line, the procedure will be called (using call
).
The full list of option specification's are defined in this section.
Note
|
No option that is not passed as an argument will be touched, meaning they will be nil .
|
- No option specification (Flag)
-
When no option specification is given, the option is considered a flag.
If the option destination is a
Symbol
, its value will be set totrue
if passed. The option won’t be touched if not called,nil
.If the option destination is a procedure (lambda, procedure, method), the procedure will be called if passed (using the
call
method). !
(Negatable Flag)-
The option is considered a flag that can be negated with
no
orno-
. E.g.foo!
can be called with--foo
(set totrue
) as well as--nofoo
and--no-foo
(set tofalse
). The option won’t be touched if not called,nil
.
= type [ desttype ] [ repeat ]
(Required argument)-
The option passed requires an argument. e.g.
--string=argument
or--string argument
. : type [ desttype ]
(Optional argument)-
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.
type
s-
s
-
String
, An arbitrary sequence of characters. It is valid for the argument to start with - or — . i
-
Integer
. An optional leading plus or minus sign, followed by a sequence of digits.
f
-
Real number. For example 3.14 , -6.23E24 and so on.
desttype
s-
@
-
Specify that the option is an Array. That means that multiple appearances of the option call will push to the option array. E.g.
'opt=i@' ⇒ :int_array
with--opt 1 --opt 3 --opt 5
will renderoptions[:int_array]
equal to[1, 3, 5]
. %
-
Specify that the option is a Hash. That means that multiple appearances of the option call will add a key=value pair to the Hash. E.g.
'define=s%' ⇒ :defines
with--define name=getoptions --define lang=ruby
will renderoptions[:defines]
equal to{'name' ⇒ 'getoptions', 'lang' ⇒ 'ruby'
.
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.max
denotes the maximum number of arguments. It must be at least min.
- Arguments
-
-
Arguments Array
Array[String]
: NormallyARGV
, but any Array of Strings will work. -
Option Definition
Hash[String, Any]
: WhereString
is the option specification andAny
, option destination can beSymbol
, or a procedure (lambda, procedure, method). See Option Definition for details.
-
- Returns
-
-
Options Hash
Map[Symbol,Any]
: whereAny
can be aString
,Integer
,Float
,Array[String]
,Array[Integer]
,Array[Float]
AndHash
ofString
,Integer
andFloat
. -
Remaining Array
Array[String]
:Array
of non-options arguments,pass_through
Options, or any argument after the--
identifier.
-
-
Supports passing
--
to stop parsing arguments (everything after will be left in theremaining
Array[String]
). -
Multiple definitions for the same option separated by
|
. e.g.help|man
. -
Defining what kind of argument you are passing. Currently supports
s
to pass strings,i
to pass integers andf
to pass float values. -
Supports both array and hash modifiers.
-
Argument type checking.
-
Supports calling a given procedure (lambda, procedure, method) if the option name if passed on the command line.
-
Supports command line options with
=
. e.g. You can use--string=mystring
and--string mystring
.
fail_on_unknown
-
if
true
, it will abort when an unknown option is passed on the commandline. Iffalse
it will WARN when an unknown option is passed. Default:false
. pass_through
-
disable warning on unknown option. Defalt:
false
.
-
For incorrect option definitions in the script itself it will
fail
withArgumentError
. -
For user input errors, it will
abort
(SystemExit
) with a description of what the user did wrong.
-
Get it from rubygems:
gem install 'ruby-getoptions'
-
Then test it in
irb
:2.1.2 :001 > require 'ruby-getoptions' => true 2.1.2 :002 > options, remaining = GetOptions.parse(['world', '-t', 'hello'], {'t=s' => :test}) => [{:test=>"hello"}, ["world"]]
-
Enjoy!
-
Support bundling
-l -a -c => -lac
-
Support passing values after the short option character
-i 24 => -i24
-
Make matching case insensitive.
-
All other Perl’s Getopt::Long goodies that seem reasonable to add!
The MIT License (MIT)
Copyright (c) 2014-2015 David Gamba
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.