Class: Rzo::Trollop::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/rzo/trollop.rb

Overview

The commandline parser. In typical usage, the methods in this class will be handled internally by Trollop::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 Trollop::with_standard_exception_handling.

Constant Summary collapse

INVALID_SHORT_ARG_REGEX =

:nodoc:

/[\d-]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*a, &b) ⇒ Parser

Initializes the parser, and instance-evaluates any block given.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rzo/trollop.rb', line 70

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

  # instance_eval(&b) if b # can't take arguments
  cloaker(&b).bind(self).call(*a) if b
end

Instance Attribute Details

#ignore_invalid_optionsObject

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.



67
68
69
# File 'lib/rzo/trollop.rb', line 67

def ignore_invalid_options
  @ignore_invalid_options
end

#leftoversObject (readonly)

The values from the commandline that were not interpreted by #parse.



58
59
60
# File 'lib/rzo/trollop.rb', line 58

def leftovers
  @leftovers
end

#specsObject (readonly)

The complete configuration hashes for each option. (Mainly useful for testing.)



62
63
64
# File 'lib/rzo/trollop.rb', line 62

def specs
  @specs
end

Instance Method Details

Adds text to the help display. Can be interspersed with calls to

opt to build a multi-section help page.



165
166
167
# File 'lib/rzo/trollop.rb', line 165

def banner(s)
  @order << [:text, s]
end

#cloaker(&b) ⇒ Object (private)

instance_eval but with ability to handle block arguments thanks to _why: http://redhanded.hobix.com/inspect/aBlockCostume.html



632
633
634
635
636
637
638
639
# File 'lib/rzo/trollop.rb', line 632

def cloaker(&b)
  (class << self; self; end).class_eval do
    define_method :cloaker_, &b
    meth = instance_method :cloaker_
    remove_method :cloaker_
    meth
  end
end

#collect_argument_parameters(args, start_at) ⇒ Object (private)



587
588
589
590
591
592
593
594
595
# File 'lib/rzo/trollop.rb', line 587

def collect_argument_parameters(args, start_at)
  params = []
  pos = start_at
  while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
    params << args[pos]
    pos += 1
  end
  params
end

#conflicts(*syms) ⇒ Object

Marks two (or more!) options as conflicting.



179
180
181
182
# File 'lib/rzo/trollop.rb', line 179

def conflicts(*syms)
  syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
  @constraints << [:conflicts, 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 Trollop::die.



173
174
175
176
# File 'lib/rzo/trollop.rb', line 173

def depends(*syms)
  syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
  @constraints << [:depends, syms]
end

#die(arg, msg = nil, error_code = nil) ⇒ Object

The per-parser version of Trollop::die (see that for documentation).



469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/rzo/trollop.rb', line 469

def die(arg, msg = nil, error_code = nil)
  if msg
    $stderr.puts "Error: argument --#{@specs[arg].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

#each_arg(args) ⇒ Object (private)

yield successive arg, parameter pairs



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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/rzo/trollop.rb', line 487

def each_arg(args)
  remains = []
  i = 0

  until i >= args.length
    return remains += args[i..-1] if @stop_words.member? args[i]
    case args[i]
    when /^--$/ # arg terminator
      return remains += args[(i + 1)..-1]
    when /^--(\S+?)=(.*)$/ # long argument with equals
      num_params_taken = yield "--#{$1}", [$2]
      if num_params_taken.nil?
        remains << args[i]
        if @stop_on_unknown
          return remains += args[i + 1..-1]
        end
      end
      i += 1
    when /^--(\S+)$/ # long argument
      params = collect_argument_parameters(args, i + 1)
      num_params_taken = yield args[i], params

      if num_params_taken.nil?
        remains << args[i]
        if @stop_on_unknown
          return remains += args[i + 1..-1]
        end
      else
        i += num_params_taken
      end
      i += 1
    when /^-(\S+)$/ # one or more short arguments
      short_remaining = ""
      shortargs = $1.split(//)
      shortargs.each_with_index do |a, j|
        if j == (shortargs.length - 1)
          params = collect_argument_parameters(args, i + 1)

          num_params_taken = yield "-#{a}", params
          unless num_params_taken
            short_remaining << a
            if @stop_on_unknown
              remains << "-#{short_remaining}"
              return remains += args[i + 1..-1]
            end
          else
            i += num_params_taken
          end
        else
          unless yield "-#{a}", []
            short_remaining << a
            if @stop_on_unknown
              short_remaining += shortargs[j + 1..-1].join
              remains << "-#{short_remaining}"
              return remains += args[i + 1..-1]
            end
          end
        end
      end

      unless short_remaining.empty?
        remains << "-#{short_remaining}"
      end
      i += 1
    else
      if @stop_on_unknown
        return remains += args[i..-1]
      else
        remains << args[i]
        i += 1
      end
    end
  end

  remains
end

#educate(stream = $stdout) ⇒ Object

Print the help message to +stream+.



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
# File 'lib/rzo/trollop.rb', line 365

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 do |name, spec|
    left[name] =
      (spec.short? ? "-#{spec.short}, " : "") + "--#{spec.long}" +
      case spec.type
      when :flag    then ""
      when :int     then "=<i>"
      when :ints    then "=<i+>"
      when :string  then "=<s>"
      when :strings then "=<s+>"
      when :float   then "=<f>"
      when :floats  then "=<f+>"
      when :io      then "=<filename/uri>"
      when :ios     then "=<filename/uri+>"
      when :date    then "=<date>"
      when :dates   then "=<date+>"
      end +
      (spec.flag? && spec.default ? ", --no-#{spec.long}" : "")
  end

  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.desc + begin
      default_s = case spec.default
      when $stdout   then "<stdout>"
      when $stdin    then "<stdin>"
      when $stderr   then "<stderr>"
      when Array
        spec.default.join(", ")
      else
        spec.default.to_s
      end

      if spec.default
        if spec.desc =~ /\.$/
          " (Default: #{default_s})"
        else
          " (default: #{default_s})"
        end
      else
        ""
      end
    end
    stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
  end
end

#educate_on_errorObject

Instead of displaying "Try --help for help." on an error display the usage (via educate)



207
208
209
# File 'lib/rzo/trollop.rb', line 207

def educate_on_error
  @educate_on_error = true
end

#legacy_widthObject (private)



447
448
449
450
451
452
# File 'lib/rzo/trollop.rb', line 447

def legacy_width
  # Support for older Rubies where io/console is not available
  `tput cols`.to_i
rescue Errno::ENOENT
  80
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 of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_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 Trollop::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 to +true+, then if it is specified on the the commandline the value will be +false+. [+: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.)

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, Trollop 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.

Raises:

  • (ArgumentError)


128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/rzo/trollop.rb', line 128

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
  raise ArgumentError, "long option name #{o.long.inspect} is already taken; please specify a (different) :long" if @long[o.long]
  raise ArgumentError, "short option name #{o.short.inspect} is already taken; please specify a (different) :short" if @short[o.short]
  @long[o.long] = o.name
  @short[o.short] = o.name if o.short?
  @specs[o.name] = o
  @order << [:opt, o.name]
end

#parse(cmdline = ARGV) ⇒ Object

Parses the commandline. Typically called by Trollop::options, but you can call it directly if you need more control.

throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.

Raises:



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/rzo/trollop.rb', line 215

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

  resolve_default_short_options!

  ## 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

    sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

    next nil if ignore_invalid_options && !sym
    raise CommandlineError, "unknown argument '#{arg}'" 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 |type, syms|
    constraint_sym = syms.find { |sym| given_args[sym] }
    next unless constraint_sym

    case type
    when :depends
      syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} requires --#{@specs[sym].long}" unless given_args.include? sym }
    when :conflicts
      syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} conflicts with --#{@specs[sym].long}" if given_args.include?(sym) && (sym != constraint_sym) }
    end
  end

  required.each do |sym, val|
    raise CommandlineError, "option --#{@specs[sym].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

    vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

    case opts.type
    when :flag
      vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
    when :int, :ints
      vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
    when :float, :floats
      vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
    when :string, :strings
      vals[sym] = params.map { |pg| pg.map(&:to_s) }
    when :io, :ios
      vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
    when :date, :dates
      vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
    end

    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

#parse_date_parameter(param, arg) ⇒ Object

:nodoc:



352
353
354
355
356
357
358
359
360
361
362
# File 'lib/rzo/trollop.rb', line 352

def parse_date_parameter(param, arg) #:nodoc:
  begin
    require 'chronic'
    time = Chronic.parse(param)
  rescue LoadError
    # chronic is not available
  end
  time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError
  raise CommandlineError, "option '#{arg}' needs a date"
end

#parse_float_parameter(param, arg) ⇒ Object (private)

Raises:



569
570
571
572
# File 'lib/rzo/trollop.rb', line 569

def parse_float_parameter(param, arg)
  raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
  param.to_f
end

#parse_integer_parameter(param, arg) ⇒ Object (private)

Raises:



564
565
566
567
# File 'lib/rzo/trollop.rb', line 564

def parse_integer_parameter(param, arg)
  raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^-?[\d_]+$/
  param.to_i
end

#parse_io_parameter(param, arg) ⇒ Object (private)



574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/rzo/trollop.rb', line 574

def parse_io_parameter(param, arg)
  if param =~ /^(stdin|-)$/i
    $stdin
  else
    require 'open-uri'
    begin
      open param
    rescue SystemCallError => e
      raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
    end
  end
end

#resolve_default_short_options!Object (private)



597
598
599
600
601
602
603
604
605
606
607
608
# File 'lib/rzo/trollop.rb', line 597

def resolve_default_short_options!
  @order.each do |type, name|
    opts = @specs[name]
    next if type != :opt || opts.short

    c = opts.long.split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
    if c # found a character to use
      opts.short = c
      @short[c] = name
    end
  end
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 Trollop invocation would then be used to parse subcommand options, after shifting the subcommand off of ARGV.



193
194
195
# File 'lib/rzo/trollop.rb', line 193

def stop_on(*words)
  @stop_words = [*words].flatten
end

#stop_on_unknownObject

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.



201
202
203
# File 'lib/rzo/trollop.rb', line 201

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.



159
160
161
# File 'lib/rzo/trollop.rb', line 159

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.



153
154
155
# File 'lib/rzo/trollop.rb', line 153

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 " ".



146
147
148
# File 'lib/rzo/trollop.rb', line 146

def version(s = nil)
  s ? @version = s : @version
end

#widthObject

:nodoc:



433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/rzo/trollop.rb', line 433

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:



455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/rzo/trollop.rb', line 455

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

#wrap_line(str, opts = {}) ⇒ Object (private)



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/rzo/trollop.rb', line 610

def wrap_line(str, opts = {})
  prefix = opts[:prefix] || 0
  width = opts[:width] || (self.width - 1)
  start = 0
  ret = []
  until start > str.length
    nextt =
      if start + width >= str.length
        str.length
      else
        x = str.rindex(/\s/, start + width)
        x = str.index(/\s/, start) if x && x < start
        x || str.length
      end
    ret << ((ret.empty? && !opts[:inner]) ? "" : " " * prefix) + str[start...nextt]
    start = nextt + 1
  end
  ret
end