Class: Puppet::Util::CommandLine::Trollop::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/puppet/util/command_line/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

FLAG_TYPES =

The set of values that indicate a flag option when passed as the :type parameter of #opt.

[:flag, :bool, :boolean]
SINGLE_ARG_TYPES =

The set of values that indicate a single-parameter (normal) option when passed as the :type parameter of #opt.

A value of io corresponds to a readable IO resource, including a filename, URI, or the strings ‘stdin’ or ‘-’.

[:int, :integer, :string, :double, :float, :io, :date]
MULTI_ARG_TYPES =

The set of values that indicate a multiple-parameter option (i.e., that takes multiple space-separated values on the commandline) when passed as the :type parameter of #opt.

[:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
TYPES =

The complete set of legal values for the :type parameter of #opt.

FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
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.



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/puppet/util/command_line/trollop.rb', line 93

def initialize *a, &b
  @version = nil
  @leftovers = []
  @specs = {}
  @long = {}
  @short = {}
  @order = []
  @constraints = []
  @stop_words = []
  @stop_on_unknown = false

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

Instance Attribute Details

#create_default_short_optionsObject

A flag that determines whether or not to attempt to automatically generate “short” options if they are not

explicitly specified.


81
82
83
# File 'lib/puppet/util/command_line/trollop.rb', line 81

def create_default_short_options
  @create_default_short_options
end

#handle_help_and_versionObject

A flag indicating whether or not the parser should attempt to handle “–help” and

"--version" specially.  If 'false', it will treat them just like any other option.


90
91
92
# File 'lib/puppet/util/command_line/trollop.rb', line 90

def handle_help_and_version
  @handle_help_and_version
end

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


86
87
88
# File 'lib/puppet/util/command_line/trollop.rb', line 86

def ignore_invalid_options
  @ignore_invalid_options
end

#leftoversObject (readonly)

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



73
74
75
# File 'lib/puppet/util/command_line/trollop.rb', line 73

def leftovers
  @leftovers
end

#specsObject (readonly)

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



77
78
79
# File 'lib/puppet/util/command_line/trollop.rb', line 77

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.



270
# File 'lib/puppet/util/command_line/trollop.rb', line 270

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

#conflicts(*syms) ⇒ Object

Marks two (or more!) options as conflicting.



282
283
284
285
# File 'lib/puppet/util/command_line/trollop.rb', line 282

def conflicts *syms
  syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: 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.



276
277
278
279
# File 'lib/puppet/util/command_line/trollop.rb', line 276

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

#die(arg, msg) ⇒ Object

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



574
575
576
577
578
579
580
581
582
# File 'lib/puppet/util/command_line/trollop.rb', line 574

def die arg, msg
  if msg
    $stderr.puts _("Error: argument --%{value0} %{msg}.") % { value0: @specs[arg][:long], msg: msg }
  else
    $stderr.puts _("Error: %{arg}.") % { arg: arg }
  end
  $stderr.puts _("Try --help for help.")
  exit(-1)
end

#educate(stream = $stdout) ⇒ Object

Print the help message to stream.



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
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
# File 'lib/puppet/util/command_line/trollop.rb', line 485

def educate stream = $stdout
  width # just 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[:long]}" +
                 (spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
                 case spec[:type]
                 when :flag; ""
                 when :int; " <i>"
                 when :ints; " <i+>"
                 when :string; " <s>"
                 when :strings; " <s+>"
                 when :float; " <f>"
                 when :floats; " <f+>"
                 when :io; " <filename/uri>"
                 when :ios; " <filename/uri+>"
                 when :date; " <date>"
                 when :dates; " <date+>"
                 end
  end

  leftcol_width = left.values.map(&:length).max || 0
  rightcol_start = leftcol_width + 6 # spaces

  unless @order.size > 0 && @order.first.first == :text
    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; "<stdout>"
                  when $stdin; "<stdin>"
                  when $stderr; "<stderr>"
                  when Array
                    spec[:default].join(", ")
                  else
                    spec[:default].to_s
                  end

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

#opt(name, desc = "", opts = {}) ⇒ 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.

: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 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 this 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)


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
# File 'lib/puppet/util/command_line/trollop.rb', line 148

def opt name, desc = "", opts = {}
  raise ArgumentError, _("you already have an argument named '%{name}'") % { name: name } if @specs.member? name

  ## fill in :type
  opts[:type] = # normalize
    case opts[:type]
    when :boolean, :bool; :flag
    when :integer; :int
    when :integers; :ints
    when :double; :float
    when :doubles; :floats
    when Class
      case opts[:type].name
      when 'TrueClass', 'FalseClass'; :flag
      when 'String'; :string
      when 'Integer'; :int
      when 'Float'; :float
      when 'IO'; :io
      when 'Date'; :date
      else
        raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type].class.name }
      end
    when nil; nil
    else
      raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type] } unless TYPES.include?(opts[:type])

      opts[:type]
    end

  ## for options with :multi => true, an array default doesn't imply
  ## a multi-valued argument. for that you have to specify a :type
  ## as well. (this is how we disambiguate an ambiguous situation;
  ## see the docs for Parser#opt for details.)
  disambiguated_default =
    if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
      opts[:default].first
    else
      opts[:default]
    end

  type_from_default =
    case disambiguated_default
    when Integer; :int
    when Numeric; :float
    when TrueClass, FalseClass; :flag
    when String; :string
    when IO; :io
    when Date; :date
    when Array
      if opts[:default].empty?
        raise ArgumentError, _("multiple argument type cannot be deduced from an empty array for '%{value0}'") % { value0: opts[:default][0].class.name }
      end

      case opts[:default][0] # the first element determines the types
      when Integer; :ints
      when Numeric; :floats
      when String; :strings
      when IO; :ios
      when Date; :dates
      else
        raise ArgumentError, _("unsupported multiple argument type '%{value0}'") % { value0: opts[:default][0].class.name }
      end
    when nil; nil
    else
      raise ArgumentError, _("unsupported argument type '%{value0}'") % { value0: opts[:default].class.name }
    end

  raise ArgumentError, _(":type specification and default type don't match (default type is %{type_from_default})") % { type_from_default: type_from_default } if opts[:type] && type_from_default && opts[:type] != type_from_default

  opts[:type] = opts[:type] || type_from_default || :flag

  ## fill in :long
  opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.tr("_", "-")
  opts[:long] =
    case opts[:long]
    when /^--([^-].*)$/
      ::Regexp.last_match(1)
    when /^[^-]/
      opts[:long]
    else
      raise ArgumentError, _("invalid long option name %{name}") % { name: opts[:long].inspect }
    end
  raise ArgumentError, _("long option name %{value0} is already taken; please specify a (different) :long") % { value0: opts[:long].inspect } if @long[opts[:long]]

  ## fill in :short
  unless opts[:short] == :none
    opts[:short] = opts[:short].to_s if opts[:short]
  end
  opts[:short] = case opts[:short]
                 when /^-(.)$/; ::Regexp.last_match(1)
                 when nil, :none, /^.$/; opts[:short]
                 else raise ArgumentError, _("invalid short option name '%{name}'") % { name: opts[:short].inspect }
                 end

  if opts[:short]
    raise ArgumentError, _("short option name %{value0} is already taken; please specify a (different) :short") % { value0: opts[:short].inspect } if @short[opts[:short]]
    raise ArgumentError, _("a short option name can't be a number or a dash") if opts[:short] =~ INVALID_SHORT_ARG_REGEX
  end

  ## fill in :default for flags
  opts[:default] = false if opts[:type] == :flag && opts[:default].nil?

  ## autobox :default for :multi (multi-occurrence) arguments
  opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)

  ## fill in :multi
  opts[:multi] ||= false

  opts[:desc] ||= desc
  @long[opts[:long]] = name
  @short[opts[:short]] = name if opts[:short] && opts[:short] != :none
  @specs[name] = opts
  @order << [:opt, 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.



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
351
352
353
354
355
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
# File 'lib/puppet/util/command_line/trollop.rb', line 312

def parse cmdline = ARGV
  vals = {}
  required = {}

  if handle_help_and_version
    unless @specs[:version] || @long["version"]
      opt :version, _("Print version and exit") if @version
    end
    opt :help, _("Show this message") unless @specs[:help] || @long["help"]
  end

  @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 if create_default_short_options

  ## resolve symbols
  given_args = {}
  @leftovers = each_arg cmdline do |arg, params|
    sym = case arg
          when /^-([^-])$/
            @short[::Regexp.last_match(1)]
          when /^--no-([^-]\S*)$/
            possible_match = @long["[no-]#{::Regexp.last_match(1)}"]
            if !possible_match
              partial_match = @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"]
              if partial_match
                Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match }
              end
              partial_match
            else
              possible_match
            end
          when /^--([^-]\S*)$/
            possible_match = @long[::Regexp.last_match(1)] || @long["[no-]#{::Regexp.last_match(1)}"]
            if !possible_match
              partial_match = @long[::Regexp.last_match(1).tr('-', '_')] || @long[::Regexp.last_match(1).tr('_', '-')] || @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"]
              if partial_match
                Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match }
              end
              partial_match
            else
              possible_match
            end
          else
            raise CommandlineError, _("invalid argument syntax: '%{arg}'") % { arg: arg }
          end

    unless sym
      next 0 if ignore_invalid_options
      raise CommandlineError, _("unknown argument '%{arg}'") % { arg: arg } unless sym
    end

    if given_args.include?(sym) && !@specs[sym][:multi]
      raise CommandlineError, _("option '%{arg}' specified multiple times") % { arg: arg }
    end

    given_args[sym] ||= {}

    given_args[sym][:arg] = arg
    given_args[sym][:params] ||= []

    # The block returns the number of parameters taken.
    num_params_taken = 0

    unless params.nil?
      if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
        given_args[sym][:params] << params[0, 1]  # take the first parameter
        num_params_taken = 1
      elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
        given_args[sym][:params] << params        # take all the parameters
        num_params_taken = params.size
      end
    end

    num_params_taken
  end

  if handle_help_and_version
    ## check for version and help args
    raise VersionNeeded if given_args.include? :version
    raise HelpNeeded if given_args.include? :help
  end

  ## 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, _("--%{value0} requires --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } unless given_args.include? sym }
    when :conflicts
      syms.each { |sym| raise CommandlineError, _("--%{value0} conflicts with --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } if given_args.include?(sym) && (sym != constraint_sym) }
    end
  end

  required.each do |sym, _val|
    raise CommandlineError, _("option --%{opt} must be specified") % { opt: @specs[sym][:long] } unless given_args.include? sym
  end

  ## parse parameters
  given_args.each do |sym, given_data|
    arg = given_data[:arg]
    params = given_data[:params]

    opts = @specs[sym]
    raise CommandlineError, _("option '%{arg}' needs a parameter") % { arg: arg } if params.empty? && opts[:type] != :flag

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

    case opts[:type]
    when :flag
      if arg =~ /^--no-/ and sym.to_s =~ /^--\[no-\]/
        vals[sym] = opts[:default]
      else
        vals[sym] = !opts[:default]
      end
    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 SINGLE_ARG_TYPES.include?(opts[:type])
      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 MULTI_ARG_TYPES.include?(opts[:type]) && !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.has_key?(: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:



473
474
475
476
477
478
479
480
481
482
# File 'lib/puppet/util/command_line/trollop.rb', line 473

def parse_date_parameter param, arg # :nodoc:
  begin
    time = Chronic.parse(param)
  rescue NameError
    # chronic is not available
  end
  time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError => e
  raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, e.backtrace
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.



296
297
298
# File 'lib/puppet/util/command_line/trollop.rb', line 296

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.



304
305
306
# File 'lib/puppet/util/command_line/trollop.rb', line 304

def stop_on_unknown
  @stop_on_unknown = true
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>”.



266
# File 'lib/puppet/util/command_line/trollop.rb', line 266

def version s = nil; @version = s if s; @version end

#widthObject

:nodoc:



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/puppet/util/command_line/trollop.rb', line 549

def width # :nodoc:
  @width ||= if $stdout.tty?
               begin
                 require 'curses'
                 Curses.init_screen
                 x = Curses.cols
                 Curses.close_screen
                 x
               rescue Exception
                 80
               end
             else
               80
             end
end

#wrap(str, opts = {}) ⇒ Object

:nodoc:



565
566
567
568
569
570
571
# File 'lib/puppet/util/command_line/trollop.rb', line 565

def wrap str, opts = {} # :nodoc:
  if str == ""
    [""]
  else
    str.split("\n").map { |s| wrap_line s, opts }.flatten
  end
end