Class: CLASP::Arguments

Inherits:
Object
  • Object
show all
Defined in:
lib/clasp/arguments.rb

Overview

The main class for processing command-line arguments

Defined Under Namespace

Classes: FlagArgument, OptionArgument

Constant Summary collapse

Flag =

#################################################################### # backwards-compatible

FlagArgument
Option =
OptionArgument

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = ARGV, specifications = nil, options = {}) ⇒ Arguments

Constructs an instance of the class, according to the given parameters

See the documentation for the ::CLASP module for examples

Signature

  • Parameters:

    • argv

      (Array) The arguments array. May not be nil. Defaults to ARGV

    • specifications

      (Array) The specifications array. Defaults to nil. If none supplied, no aliasing will be performed

    • options

      An options hash, containing any of the following options

  • Options:

    • mutate_argv:

      (Boolean) Determines if the library should mutate argv. Defaults to true. This is essential when using CLASP in conjunction with $<



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
# File 'lib/clasp/arguments.rb', line 345

def initialize(argv = ARGV, specifications = nil, options = {})

  # have to do this name-swap, as 'options' has CLASP-specific
  # meaning
  init_opts, options = options.dup, nil

  init_opts[:mutate_argv] = true unless init_opts.has_key? :mutate_argv

  @program_name    = init_opts[:program_name] || Arguments.derive_program_name_

  @argv        = argv
  argv       =  argv.dup
  @argv_original_copy  =  argv.dup.freeze

  @specifications    = specifications
  @aliases     = @specifications

  specifications   =  nil if specifications and specifications.empty?

  flags, options, values = Arguments.parse(argv, specifications)

  [ flags, options, values ].each do |ar|

    class << ar

      undef :inspect
      undef :to_s

      def to_s

        s = ''

        s +=  '['
        s +=  self.map { |v| %Q<"#{v}"> }.join(', ')
        s +=  ']'

        s
      end

      def inspect

        s = ''

        s +=  "#<#{self.class}:0x#{(object_id << 1).to_s(16)} ["
        s +=  self.map { |v| v.inspect }.join(', ')
        s +=  "]>"

        s
      end
    end
  end

  @flags   =  flags.freeze
  @options = options.freeze
  @values    = values.freeze


  # do argv-mutation, if required
  if init_opts[:mutate_argv]

    while not argv.empty?

      argv.shift
    end

    @values.each do |v|

      argv << v
    end
  end
end

Instance Attribute Details

#aliasesObject (readonly)

DEPRECATED

Instead refer to specifications



568
569
570
# File 'lib/clasp/arguments.rb', line 568

def aliases
  @aliases
end

#argvObject (readonly)

the (possibly mutated) array of arguments instance passed to new



580
581
582
# File 'lib/clasp/arguments.rb', line 580

def argv
  @argv
end

#argv_original_copyObject (readonly)

unchanged copy of the original array of arguments passed to new



583
584
585
# File 'lib/clasp/arguments.rb', line 583

def argv_original_copy
  @argv_original_copy
end

#flagsObject (readonly)

an immutable array of flags



571
572
573
# File 'lib/clasp/arguments.rb', line 571

def flags
  @flags
end

#optionsObject (readonly)

an immutable array of options



574
575
576
# File 'lib/clasp/arguments.rb', line 574

def options
  @options
end

#program_nameObject (readonly)

Returns the value of attribute program_name.



585
586
587
# File 'lib/clasp/arguments.rb', line 585

def program_name
  @program_name
end

#specificationsObject (readonly)

an immutable array of specifications



565
566
567
# File 'lib/clasp/arguments.rb', line 565

def specifications
  @specifications
end

#valuesObject (readonly)

an immutable array of values



577
578
579
# File 'lib/clasp/arguments.rb', line 577

def values
  @values
end

Class Method Details

.derive_program_name_Object



418
419
420
421
# File 'lib/clasp/arguments.rb', line 418

def self.derive_program_name_

  $0
end

.load(argv, source, options = {}) ⇒ Object

Loads an instance of the class, as specified by source, according to the given parameters

See the documentation for the ::CLASP module for examples

Signature

  • Parameters:

    • argv

      (Array) The arguments array. May not be nil. Defaults to ARGV

    • source

      (Hash, IO) The arguments specification, either as a Hash or an instance of an IO-implementing type containing a YAML specification

    • options

      An options hash, containing any of the following options

  • Options:

    • mutate_argv:

      (Boolean) Determines if the library should mutate argv. Defaults to true. This is essential when using CLASP in conjunction with $<



205
206
207
208
209
210
211
212
# File 'lib/clasp/arguments.rb', line 205

def self.load(argv, source, options = {}) # :yields: An instance of +CLASP::Arguments+

  options ||= {}

  specs = load_specifications(source, options)

  self.new argv, specs, options
end

.load_specifications(source, options = {}) ⇒ Object

Loads the specifications as specified by source, according to the given parameters

Signature

  • Parameters:

    • source

      (Hash, IO) The arguments specification, either as a Hash or an instance of an IO-implementing type containing a YAML specification

    • options

      An options hash, containing any of the following options



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
# File 'lib/clasp/arguments.rb', line 221

def self.load_specifications(source, options = {}) # :yields: An array of specification instances

  options ||= {}

  h = nil

  case source
  when ::IO

    h = YAML.load(source.read)
  when ::Hash

    h = source
  else

    if source.respond_to?(:to_hash)

      h = source.to_hash
    else

      raise TypeError, "#{self}.#{__method__}() 'source' argument must be a #{::Hash}, or an object implementing #{::IO}, or a type implementing to_hash'"
    end
  end

  specs  =  []

  _clasp = h['clasp'] or raise ArgumentError, "missing top-level 'clasp' element in load configuration"
  ::Hash === _clasp or raise ArgumentError, "top-level 'clasp' element must be a #{::Hash}"

  _specs = (_clasp['arg-specs'] || _clasp['specifications'] || _clasp['aliases']) or raise ArgumentError, "missing element 'clasp/specifications'"
  ::Array === _specs or raise ArgumentError, "top-level 'specifications' element must be a #{::Hash}"

  _specs.each do |_spec|

    case _spec
    when ::Hash

      # TODO: make a utility function and shrink all the following

      _spec.each do |_arg_type, _details|

        case _arg_type
        when 'flag', :flag

          _name  =  _details['name']

          unless _name

            warn "flag specification missing required 'name' field"
          else

            _alias    = _details['alias']
            _aliases  =  _details['aliases']
            _help   =  _details['help'] || _details['description']

            specs << CLASP.Flag(_name, alias: _alias, aliases: _aliases, help: _help)
          end
        when 'option', :option

          _name  =  _details['name']

          unless _name

            warn "option specification missing required 'name' field"
          else

            _alias        = _details['alias']
            _aliases      =  _details['aliases']
            _default_value    = _details['default_value'] || _details['default']
            _help       =  _details['help'] || _details['description']
            _required     = _details['required']
            _required_message = _details['required_message']
            _values_range   =  _details['values_range'] || _details['values']

            specs << CLASP.Option(_name, alias: _alias, aliases: _aliases, default_value: _default_value, help: _help, required: _required, required_message: _required_message, values_range: _values_range)
          end
        when 'alias', :alias

          _resolved  =  _details['resolved']

          unless _resolved

            warn "alias specification missing required 'resolved' field"
          else

            _alias        = _details['alias']
            _aliases      =  _details['aliases']

            unless _alias || _aliases

              warn "alias specification missing required 'alias' or 'aliases' field"
            else

              specs << CLASP.Flag(_resolved, alias: _alias, aliases: _aliases)
            end
          end
        else

          warn "unknown arg-type '#{_arg_type}' specified"
        end
      end
    else

      warn "non-#{::Hash} element in 'clasp/specifications': #{_spec} (of type #{_spec.class})"
    end
  end

  specs
end

.parse(argv, specifications) ⇒ Object



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
482
483
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
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
# File 'lib/clasp/arguments.rb', line 423

def self.parse(argv, specifications)

  flags  =  []
  options  =  []
  values = []

  forced_value   =  false
  want_option_value  =  false

  argv.each_with_index do |arg, index|

    if not forced_value

      if '--' == arg

        # all subsequent arguments are values
        forced_value = true
        next
      end

      # do regex test to see if option/flag/value
      if arg =~ /^(-+)([^=]+)/

        hyphens     = $1
        given_label   =  $2
        given_name    = "#$1#$2"
        value     = ($' and not $'.empty?) ? $'[1 ... $'.size] : nil
        argument_alias  =  nil
        resolved_name = nil

        (specifications || []).each do |a|

          if a.name == given_name or a.aliases.include? given_name

            argument_alias  =  a
            resolved_name = a.name

            # need to check whether the alias is a default-option
            # and, if so, expand out its name and value, and replace
            # the name and (if none previously specified) the value
            if resolved_name =~ /^(-+)([^=]+)=/

              resolved_name  =  "#$1#$2"
              value      ||=  $'
            end

            break
          end
        end

        # Here we intercept and (potentially) cater to grouped flags
        if not argument_alias and not value and specifications and 1 == hyphens.size

          # Must match all
          flag_aliases = []
          given_label[0 ... given_label.size].each_char do |c|

            new_flag  =  "-#{c.chr}"

            flag_alias  =  nil

            # special case where the flag's actual name is short form and found here
            flag_alias  ||=  specifications.detect { |a| a.is_a?(CLASP::FlagSpecification) && a.name == new_flag }

            # if not found as a flag, look in each specifications' aliases
            flag_alias  ||=  specifications.detect { |a| a.aliases.include? new_flag }

            if not flag_alias

              flag_aliases = nil
              break
            else

              flag_aliases <<  flag_alias
            end
          end

          if flag_aliases

            # got them all, so now have to process them all
            # as normal. Note: is this susceptible to
            # infinite recursion

            # convert to argv and invoke
            flags_argv = flag_aliases.map { |a| a.name }

            grp_flags, grp_options, grp_value = Arguments.parse flags_argv, specifications

            grp_flags.map! { |f| FlagArgument.new(arg, index, given_name, f.name, f.argument_alias, hyphens.size, given_label, argument_alias ? argument_alias.extras : nil) }
            grp_options.map! { |o| OptionArgument.new(arg, index, given_name, o.name, o.argument_alias, hyphens.size, given_label, o.value, argument_alias ? argument_alias.extras : nil) }

            flags.push(*grp_flags)
            options.push(*grp_options)
            values.push(*grp_value)

            next
          end
        end

        if argument_alias and argument_alias.is_a? CLASP::OptionSpecification and not value

          want_option_value = true
          options << OptionArgument.new(arg, index, given_name, resolved_name, argument_alias, hyphens.size, given_label, nil, argument_alias ? argument_alias.extras : nil)
        elsif value

          want_option_value = false
          options << OptionArgument.new(arg, index, given_name, resolved_name, argument_alias, hyphens.size, given_label, value, argument_alias ? argument_alias.extras : nil)
        else

          want_option_value = false
          flags << FlagArgument.new(arg, index, given_name, resolved_name, argument_alias, hyphens.size, given_label, argument_alias ? argument_alias.extras : nil)
        end

        next
      end
    end

    if want_option_value and not forced_value

      option = options[-1]
      option.instance_eval("@value='#{arg}'")
      want_option_value = false
    else

      arg    = arg.dup
      arg_ix = ::Integer === index ? index : index.dup

      arg.define_singleton_method(:given_index) { arg_ix }

      values << arg
    end
  end

  return flags, options, values

end

Instance Method Details

#find_first_unknown(options = {}) ⇒ Object

finds the first unknown flag or option; nil if all used

Raises:

  • (ArgumentError)


589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
# File 'lib/clasp/arguments.rb', line 589

def find_first_unknown options = {}

  option = {} if options.nil?

  raise ArgumentError, "options must be nil or Hash - #{option.class} given" unless options.is_a? ::Hash

  specifications = options[:specifications] || options[:aliases] || @specifications

  raise ArgumentError, "specifications may not be nil" if specifications.nil?

  flags.each do |f|

    return f unless specifications.any? { |al| al.is_a?(::CLASP::FlagSpecification) && al.name == f.name }
  end

  self.options.each do |o|

    return o unless specifications.any? { |al| al.is_a?(::CLASP::OptionSpecification) && al.name == o.name }
  end

  nil
end

#find_flag(id) ⇒ Object

Searches for a flag that matches the given id, returning the flag if found; nil otherwise

Signature

  • Parameters:

  • id

    (String, CLASP::Flag) The name of a flag, or the flag itself



619
620
621
622
623
624
625
626
627
# File 'lib/clasp/arguments.rb', line 619

def find_flag(id)

  flags.each do |flag|

    return flag if flag == id
  end

  nil
end

#find_option(id) ⇒ Object

Searches for a option that matches the given id, returning the option if found; nil otherwise

Signature

  • Parameter:

  • id

    (String, CLASP::Flag) The name of a option, or the option itself



636
637
638
639
640
641
642
643
644
# File 'lib/clasp/arguments.rb', line 636

def find_option(id)

  options.each do |option|

    return option if option == id
  end

  nil
end