class OptionParser
inherits Reference
¶
OptionParser
is a class for command-line options processing. It supports:
- Short and long modifier style options (example:
-h
,--help
) - Passing arguments to the flags (example:
-f filename.txt
) - Subcommands
- Automatic help message generation
Run crystal
for an example of a CLI built with OptionParser
.
Short example:
require "option_parser"
upcase = false
destination = "World"
OptionParser.parse do |parser|
parser.banner = "Usage: salute [arguments]"
parser.on("-u", "--upcase", "Upcases the salute") { upcase = true }
parser.on("-t NAME", "--to=NAME", "Specifies the name to salute") { |name| destination = name }
parser.on("-h", "--help", "Show this help") do
puts parser
exit
end
parser.invalid_option do |flag|
STDERR.puts "ERROR: #{flag} is not a valid option."
STDERR.puts parser
exit(1)
end
end
destination = destination.upcase if upcase
puts "Hello #{destination}!"
Subcommands¶
OptionParser
also supports subcommands.
Short example:
require "option_parser"
verbose = false
salute = false
welcome = false
name = "World"
parser = OptionParser.new do |parser|
parser.banner = "Usage: example [subcommand] [arguments]"
parser.on("salute", "Salute a name") do
salute = true
parser.banner = "Usage: example salute [arguments]"
parser.on("-t NAME", "--to=NAME", "Specify the name to salute") { |_name| name = _name }
end
parser.on("welcome", "Print a greeting message") do
welcome = true
parser.banner = "Usage: example welcome"
end
parser.on("-v", "--verbose", "Enabled verbose output") { verbose = true }
parser.on("-h", "--help", "Show this help") do
puts parser
exit
end
end
parser.parse
if salute
STDERR.puts "Saluting #{name}" if verbose
puts "Hello #{name}"
elsif welcome
STDERR.puts "Welcoming #{name}" if verbose
puts "Welcome!"
else
puts parser
exit(1)
end
Class methods¶
.parse(args = ARGV, &) : self
¶
(args = ARGV, &) : self
Creates a new parser, with its configuration specified in the block,
and uses it to parse the passed args (defaults to ARGV
).
Methods¶
#banner=(banner : String?)
¶
(banner : String?)
Establishes the initial message for the help printout. Typically, you want to write here the name of your program, and a one-line template of its invocation.
Example:
require "option_parser"
parser = OptionParser.new
parser.banner = "Usage: crystal [command] [switches] [program file] [--] [arguments]"
#before_each(&before_each : String -> )
¶
(&before_each : String -> )
Sets a handler which runs before each argument is parsed. This callback is
not passed flag arguments. For example, --foo=foo_arg --bar bar_arg
would
pass --foo=foo_arg
and --bar
to the callback only.
You typically use this to implement advanced option parsing behaviour such
as treating all options after a filename differently (along with #stop
).
#invalid_option(&invalid_option : String -> )
¶
(&invalid_option : String -> )
Sets a handler for option arguments that didn't match any of the setup options.
You typically use this to display a help message.
The default behaviour is to raise InvalidOption
.
#missing_option(&missing_option : String -> )
¶
(&missing_option : String -> )
Sets a handler for when a option that expects an argument wasn't given any.
You typically use this to display a help message.
The default behaviour is to raise MissingOption
.
#on(short_flag : String, long_flag : String, description : String, &block : String -> )
¶
(short_flag : String, long_flag : String, description : String, &block : String -> )
Establishes a handler for a pair of short and long flags.
See the other definition of on
for examples. This method does not support
subcommands.
#on(flag : String, description : String, &block : String -> )
¶
(flag : String, description : String, &block : String -> )
Establishes a handler for a flag or subcommand.
Flags must start with a dash or double dash. They can also have an optional argument, which will get passed to the block. Each flag has a description, which will be used for the help message.
Subcommands are any flag passed which does not start with a dash. They cannot take arguments. When a subcommand is parsed, all subcommands are removed from the OptionParser, simulating a "tree" of subcommands. All flags remain valid. For a longer example, see the examples at the top of the page.
Examples of valid flags:
-a
,-B
--something-longer
-f FILE
,--file FILE
,--file=FILE
(these will yield the passed value to the block as a string)
Examples of valid subcommands:
foo
,run
#parse(args = ARGV)
¶
(args = ARGV)
Parses the passed args (defaults to ARGV
), running the handlers associated to each option.
#separator(message = "")
¶
(message = "")
Adds a separator, with an optional header message, that will be used to
print the help. The separator is placed between the flags registered (#on
)
before, and the flags registered after the call.
This way, you can group the different options in an easier to read way.
#stop
¶
Stops the current parse and returns immediately, leaving the remaining flags
unparsed. This is treated identically to --
being inserted behind the
current parsed flag.
#unknown_args(&unknown_args : Array(String), Array(String) -> )
¶
(&unknown_args : Array(String), Array(String) -> )
Sets a handler for regular arguments that didn't match any of the setup options.
You typically use this to get the main arguments (not modifiers)
that your program expects (for example, filenames). The default behaviour
is to do nothing. The arguments can also be extracted from the args array
passed to #parse
after parsing.