Class: Optimist::Parser
- Inherits:
-
Object
- Object
- Optimist::Parser
- Defined in:
- lib/optimist.rb
Overview
The commandline parser. In typical usage, the methods in this class will be handled internally by Optimist::options. In this case, only the #opt, #banner and #version, #depends, and #conflicts methods will typically be called.
If you want to instantiate this class yourself (for more complicated argument-parsing logic), call #parse to actually produce the output hash, and consider calling it from within Optimist::with_standard_exception_handling.
Constant Summary collapse
- DEFAULT_SETTINGS =
{ exact_match: true, implicit_short_opts: true, suggestions: true }
Instance Attribute Summary collapse
-
#ignore_invalid_options ⇒ Object
A flag that determines whether or not to raise an error if the parser is passed one or more options that were not registered ahead of time.
-
#leftovers ⇒ Object
readonly
The values from the commandline that were not interpreted by #parse.
-
#specs ⇒ Object
readonly
The complete configuration hashes for each option.
Class Method Summary collapse
-
.register(lookup, klass) ⇒ Object
The Option subclasses are responsible for registering themselves using this function.
-
.registry_getopttype(type) ⇒ Object
Gets the class from the registry.
Instance Method Summary collapse
-
#banner(s) ⇒ Object
(also: #text)
Adds text to the help display.
-
#conflicts(*syms) ⇒ Object
Marks two (or more!) options as conflicting.
-
#depends(*syms) ⇒ Object
Marks two (or more!) options as requiring each other.
-
#die(arg, msg = nil, error_code = nil) ⇒ Object
The per-parser version of Optimist::die (see that for documentation).
-
#educate(stream = $stdout) ⇒ Object
Print the help message to
stream
. -
#educate_on_error ⇒ Object
Instead of displaying “Try –help for help.” on an error display the usage (via educate).
-
#either(*syms) ⇒ Object
Marks two (or more!) options as required but mutually exclusive.
-
#initialize(*a, &b) ⇒ Parser
constructor
Initializes the parser, and instance-evaluates any block given.
-
#opt(name, desc = "", opts = {}, &b) ⇒ Object
Define an option.
-
#parse(cmdline = ARGV) ⇒ Object
Parses the commandline.
-
#stop_on(*words) ⇒ Object
Defines a set of words which cause parsing to terminate when encountered, such that any options to the left of the word are parsed as usual, and options to the right of the word are left intact.
-
#stop_on_unknown ⇒ Object
Similar to #stop_on, but stops on any unknown word when encountered (unless it is a parameter for an argument).
-
#synopsis(s = nil) ⇒ Object
Adds a synopsis (command summary description) right below the usage line, or as the first line if usage isn’t specified.
-
#usage(s = nil) ⇒ Object
Sets the usage string.
-
#version(s = nil) ⇒ Object
Sets the version string.
-
#width ⇒ Object
:nodoc:.
-
#wrap(str, opts = {}) ⇒ Object
:nodoc:.
Constructor Details
#initialize(*a, &b) ⇒ Parser
Initializes the parser, and instance-evaluates any block given.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/optimist.rb', line 136 def initialize(*a, &b) @version = nil @leftovers = [] @specs = {} @long = {} @short = {} @order = [] @constraints = [] @stop_words = [] @stop_on_unknown = false @educate_on_error = false @synopsis = nil @usage = nil ## allow passing settings through Parser.new as an optional hash. ## but keep compatibility with non-hashy args, though. begin settings_hash = Hash[*a] @settings = DEFAULT_SETTINGS.merge(settings_hash) a=[] ## clear out args if using as settings-hash rescue ArgumentError @settings = DEFAULT_SETTINGS end self.instance_exec(*a, &b) if block_given? end |
Instance Attribute Details
#ignore_invalid_options ⇒ Object
A flag that determines whether or not to raise an error if the parser is passed one or more
options that were not registered ahead of time. If 'true', then the parser will simply
ignore options that it does not recognize.
127 128 129 |
# File 'lib/optimist.rb', line 127 def @ignore_invalid_options end |
#leftovers ⇒ Object (readonly)
The values from the commandline that were not interpreted by #parse.
118 119 120 |
# File 'lib/optimist.rb', line 118 def leftovers @leftovers end |
#specs ⇒ Object (readonly)
The complete configuration hashes for each option. (Mainly useful for testing.)
122 123 124 |
# File 'lib/optimist.rb', line 122 def specs @specs end |
Class Method Details
.register(lookup, klass) ⇒ Object
The Option subclasses are responsible for registering themselves using this function.
99 100 101 |
# File 'lib/optimist.rb', line 99 def self.register(lookup, klass) @registry[lookup.to_sym] = klass end |
.registry_getopttype(type) ⇒ Object
Gets the class from the registry. Can be given either a class-name, e.g. Integer, a string, e.g “integer”, or a symbol, e.g :integer
105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/optimist.rb', line 105 def self.registry_getopttype(type) return nil unless type if type.respond_to?(:name) type = type.name lookup = type.downcase.to_sym else lookup = type.to_sym end raise ArgumentError, "Unsupported argument type '#{type}', registry lookup '#{lookup}'" unless @registry.has_key?(lookup) return @registry[lookup].new end |
Instance Method Details
#banner(s) ⇒ Object Also known as: text
Adds text to the help display. Can be interspersed with calls to #opt to build a multi-section help page.
250 251 252 |
# File 'lib/optimist.rb', line 250 def (s) @order << [:text, s] end |
#conflicts(*syms) ⇒ Object
Marks two (or more!) options as conflicting.
264 265 266 267 |
# File 'lib/optimist.rb', line 264 def conflicts(*syms) syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] } @constraints << ConflictConstraint.new(syms) end |
#depends(*syms) ⇒ Object
Marks two (or more!) options as requiring each other. Only handles undirected (i.e., mutual) dependencies. Directed dependencies are better modeled with Optimist::die.
258 259 260 261 |
# File 'lib/optimist.rb', line 258 def depends(*syms) syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] } @constraints << DependConstraint.new(syms) end |
#die(arg, msg = nil, error_code = nil) ⇒ Object
The per-parser version of Optimist::die (see that for documentation).
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 |
# File 'lib/optimist.rb', line 553 def die(arg, msg = nil, error_code = nil) msg, error_code = nil, msg if msg.kind_of?(Integer) if msg $stderr.puts "Error: argument --#{@specs[arg].long.long} #{msg}." else $stderr.puts "Error: #{arg}." end if @educate_on_error $stderr.puts educate $stderr else $stderr.puts "Try --help for help." end exit(error_code || -1) end |
#educate(stream = $stdout) ⇒ Object
Print the help message to stream
.
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/optimist.rb', line 484 def educate(stream = $stdout) width # hack: calculate it now; otherwise we have to be careful not to # call this unless the cursor's at the beginning of a line. left = {} @specs.each { |name, spec| left[name] = spec.educate } leftcol_width = left.values.map(&:length).max || 0 rightcol_start = leftcol_width + 6 # spaces unless @order.size > 0 && @order.first.first == :text command_name = File.basename($0).gsub(/\.[^.]+$/, '') stream.puts "Usage: #{command_name} #{@usage}\n" if @usage stream.puts "#{@synopsis}\n" if @synopsis stream.puts if @usage || @synopsis stream.puts "#{@version}\n" if @version stream.puts "Options:" end @order.each do |what, opt| if what == :text stream.puts wrap(opt) next end spec = @specs[opt] stream.printf " %-#{leftcol_width}s ", left[opt] desc = spec.full_description stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start) end end |
#educate_on_error ⇒ Object
Instead of displaying “Try –help for help.” on an error display the usage (via educate)
298 299 300 |
# File 'lib/optimist.rb', line 298 def educate_on_error @educate_on_error = true end |
#either(*syms) ⇒ Object
Marks two (or more!) options as required but mutually exclusive.
270 271 272 273 |
# File 'lib/optimist.rb', line 270 def either(*syms) syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] } @constraints << EitherConstraint.new(syms) end |
#opt(name, desc = "", opts = {}, &b) ⇒ Object
Define an option. name
is the option name, a unique identifier for the option that you will use internally, which should be a symbol or a string. desc
is a string description which will be displayed in help messages.
Takes the following optional arguments:
:long
-
Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the
name
option into a string, and replacing any _’s by -‘s. :short
-
Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from
name
. Use :none: to not have a short value. :type
-
Require that the argument take a parameter or parameters of type
type
. For a single parameter, the value can be a member ofSINGLE_ARG_TYPES
, or a corresponding Ruby class (e.g.Integer
for:int
). For multiple-argument parameters, the value can be any member ofMULTI_ARG_TYPES
constant. If unset, the default argument type is:flag
, meaning that the argument does not take a parameter. The specification of:type
is not necessary if a:default
is given. :default
-
Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Optimist::options) will have a
nil
value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a:type
is not necessary if a:default
is given. (But see below for an important caveat when:multi
: is specified too.) If the argument is a flag, and the default is set totrue
, then if it is specified on the the commandline the value will befalse
. :required
-
If set to
true
, the argument must be provided on the commandline. :multi
-
If set to
true
, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.) :permitted
-
Specify an Array of permitted values for an option. If the user provides a value outside this list, an error is thrown.
Note that there are two types of argument multiplicity: an argument can take multiple values, e.g. “–arg 1 2 3”. An argument can also be allowed to occur multiple times, e.g. “–arg 1 –arg 2”.
Arguments that take multiple values should have a :type
parameter drawn from MULTI_ARG_TYPES
(e.g. :strings
), or a :default:
value of an array of the correct type (e.g. [String]). The value of this argument will be an array of the parameters on the commandline.
Arguments that can occur multiple times should be marked with :multi
=> true
. The value of this argument will also be an array. In contrast with regular non-multi options, if not specified on the commandline, the default value will be [], not nil.
These two attributes can be combined (e.g. :type
=> :strings
, :multi
=> true
), in which case the value of the argument will be an array of arrays.
There’s one ambiguous case to be aware of: when :multi
: is true and a :default
is set to an array (of something), it’s ambiguous whether this is a multi-value argument as well as a multi-occurrence argument. In thise case, Optimist assumes that it’s not a multi-value argument. If you want a multi-value, multi-occurrence argument with a default value, you must specify :type
as well.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/optimist.rb', line 204 def opt(name, desc = "", opts = {}, &b) opts[:callback] ||= b if block_given? opts[:desc] ||= desc o = Option.create(name, desc, opts) raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? o.name o.long.names.each do |lng| raise ArgumentError, "long option name #{lng.inspect} is already taken; please specify a (different) :long/:alt" if @long[lng] @long[lng] = o.name end o.short.chars.each do |short| raise ArgumentError, "short option name #{short.inspect} is already taken; please specify a (different) :short" if @short[short] @short[short] = o.name end raise ArgumentError, "permitted values for option #{o.long.long.inspect} must be either nil, Range, Regexp or an Array;" unless o.permitted_type_valid? @specs[o.name] = o @order << [:opt, o.name] end |
#parse(cmdline = ARGV) ⇒ Object
Parses the commandline. Typically called by Optimist::options, but you can call it directly if you need more control.
throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
# File 'lib/optimist.rb', line 356 def parse(cmdline = ARGV) vals = {} required = {} opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"]) opt :help, "Show this message" unless @specs[:help] || @long["help"] @specs.each do |sym, opts| required[sym] = true if opts.required? vals[sym] = opts.default vals[sym] = [] if opts.multi && !opts.default # multi arguments default to [], not nil end if @settings[:implicit_short_opts] ## resolve symbols given_args = {} @leftovers = each_arg cmdline do |arg, params| ## handle --no- forms arg, negative_given = if arg =~ /^--no-([^-]\S*)$/ ["--#{$1}", true] else [arg, false] end sym = case arg when /^-([^-])$/ then @short[$1] when /^--([^-]\S*)$/ then @long[$1] || @long["no-#{$1}"] else raise CommandlineError, "invalid argument syntax: '#{arg}'" end if arg.start_with?("--no-") # explicitly invalidate --no-no- arguments sym = nil ## Support inexact matching of long-arguments like perl's Getopt::Long elsif !sym && !@settings[:exact_match] && arg.match(/^--(\S+)$/) sym = perform_inexact_match(arg, $1) end next nil if && !sym handle_unknown_argument(arg, @long.keys, @settings[:suggestions]) unless sym if given_args.include?(sym) && !@specs[sym].multi? raise CommandlineError, "option '#{arg}' specified multiple times" end given_args[sym] ||= {} given_args[sym][:arg] = arg given_args[sym][:negative_given] = negative_given given_args[sym][:params] ||= [] # The block returns the number of parameters taken. num_params_taken = 0 unless params.empty? if @specs[sym].single_arg? given_args[sym][:params] << params[0, 1] # take the first parameter num_params_taken = 1 elsif @specs[sym].multi_arg? given_args[sym][:params] << params # take all the parameters num_params_taken = params.size end end num_params_taken end ## check for version and help args raise VersionNeeded if given_args.include? :version raise HelpNeeded if given_args.include? :help ## check constraint satisfaction @constraints.each do |const| const.validate(given_args: given_args, specs: @specs) end required.each do |sym, val| raise CommandlineError, "option --#{@specs[sym].long.long} must be specified" unless given_args.include? sym end ## parse parameters given_args.each do |sym, given_data| arg, params, negative_given = given_data.values_at :arg, :params, :negative_given opts = @specs[sym] if params.empty? && !opts.flag? raise CommandlineError, "option '#{arg}' needs a parameter" unless opts.default params << (opts.array_default? ? opts.default.clone : [opts.default]) end if params.first && opts.permitted params.first.each do |val| opts.validate_permitted(arg, val) end end vals["#{sym}_given".intern] = true # mark argument as specified on the commandline vals[sym] = opts.parse(params, negative_given) if opts.single_arg? if opts.multi? # multiple options, each with a single parameter vals[sym] = vals[sym].map { |p| p[0] } else # single parameter vals[sym] = vals[sym][0][0] end elsif opts.multi_arg? && !opts.multi? vals[sym] = vals[sym][0] # single option, with multiple parameters end # else: multiple options, with multiple parameters opts.callback.call(vals[sym]) if opts.callback end ## modify input in place with only those ## arguments we didn't process cmdline.clear @leftovers.each { |l| cmdline << l } ## allow openstruct-style accessors class << vals def method_missing(m, *_args) self[m] || self[m.to_s] end end vals end |
#stop_on(*words) ⇒ Object
Defines a set of words which cause parsing to terminate when encountered, such that any options to the left of the word are parsed as usual, and options to the right of the word are left intact.
A typical use case would be for subcommand support, where these would be set to the list of subcommands. A subsequent Optimist invocation would then be used to parse subcommand options, after shifting the subcommand off of ARGV.
284 285 286 |
# File 'lib/optimist.rb', line 284 def stop_on(*words) @stop_words = [*words].flatten end |
#stop_on_unknown ⇒ Object
Similar to #stop_on, but stops on any unknown word when encountered (unless it is a parameter for an argument). This is useful for cases where you don’t know the set of subcommands ahead of time, i.e., without first parsing the global options.
292 293 294 |
# File 'lib/optimist.rb', line 292 def stop_on_unknown @stop_on_unknown = true end |
#synopsis(s = nil) ⇒ Object
Adds a synopsis (command summary description) right below the usage line, or as the first line if usage isn’t specified.
244 245 246 |
# File 'lib/optimist.rb', line 244 def synopsis(s = nil) s ? @synopsis = s : @synopsis end |
#usage(s = nil) ⇒ Object
Sets the usage string. If set the message will be printed as the first line in the help (educate) output and ending in two new lines.
238 239 240 |
# File 'lib/optimist.rb', line 238 def usage(s = nil) s ? @usage = s : @usage end |
#version(s = nil) ⇒ Object
Sets the version string. If set, the user can request the version on the commandline. Should probably be of the form “<program name> <version number>”.
231 232 233 |
# File 'lib/optimist.rb', line 231 def version(s = nil) s ? @version = s : @version end |
#width ⇒ Object
:nodoc:
517 518 519 520 521 522 523 524 525 526 527 528 529 |
# File 'lib/optimist.rb', line 517 def width #:nodoc: @width ||= if $stdout.tty? begin require 'io/console' w = IO.console.winsize.last w.to_i > 0 ? w : 80 rescue LoadError, NoMethodError, Errno::ENOTTY, Errno::EBADF, Errno::EINVAL legacy_width end else 80 end end |
#wrap(str, opts = {}) ⇒ Object
:nodoc:
539 540 541 542 543 544 545 546 547 548 549 550 |
# File 'lib/optimist.rb', line 539 def wrap(str, opts = {}) # :nodoc: if str == "" [""] else inner = false str.split("\n").map do |s| line = wrap_line s, opts.merge(:inner => inner) inner = true line end.flatten end end |