Class: LibCLImate::Climate

Inherits:
Object
  • Object
show all
Includes:
Xqsr3::Quality::ParameterChecking
Defined in:
lib/libclimate/climate.rb

Overview

Class used to gather together the CLI specification, and execute it

The standard usage pattern is as follows:

PROGRAM_VERSION = [ 0, 1, 2 ]

program_options = {}

climate = LibCLImate::Climate.new do |cl|

  cl.add_flag('--verbose', alias: '-v', help: 'Makes program output verbose') { program_options[:verbose] = true }

  cl.add_option('--flavour', alias: '-f', help: 'Specifies the flavour') do |o, a|

    program_options[:flavour] = check_flavour(o.value) or cl.abort "Invalid flavour '#{o.value}'; use --help for usage"
  end

  cl.usage_values = '<value-1> [ ... <value-N> ]'
  cl.constrain_values = 1..100000

  cl.info_lines = [

    'ACME CLI program (using libCLImate)',
    :version,
    'An example program',
  ]
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|_self| ... } ⇒ Climate

Creates an instance of the Climate class.

Signature

  • Parameters:

    • options: (Hash) An options hash, containing any of the following options.

  • Options:

    • :no_help_flag (boolean) Prevents the use of the CLASP::Flag.Help flag-specification

    • :no_version_flag (boolean) Prevents the use of the CLASP::Flag.Version flag-specification

    • :program_name (::String) An explicit program-name, which is inferred from $0 if this is nil

    • :version (String, [Integer], [String]) A version specification. If not specified, this is inferred

    • :version_context Object or class that defines a context for searching the version. Ignored if :version is specified

  • Block An optional block which receives the constructing instance, allowing the user to modify the attributes.

Yields:

  • (_self)

Yield Parameters:



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
# File 'lib/libclimate/climate.rb', line 284

def initialize(options={}) # :yields: climate

  check_parameter options, 'options', allow_nil: true, type: ::Hash

  options ||=  {}

  check_option options, :no_help_flag, type: :boolean, allow_nil: true
  check_option options, :no_version_flag, type: :boolean, allow_nil: true
  check_option options, :program_name, type: ::String, allow_nil: true

  pr_name    = options[:program_name]

  unless pr_name

    pr_name = File.basename($0)
    pr_name = (pr_name =~ /\.(?:bat|cmd|rb|sh)$/) ? "#$`(#$&)" : pr_name
  end

  @specifications    = []
  @ignore_unknown    = false
  @exit_on_unknown = true
  @exit_on_missing = true
  @exit_on_usage   =  true
  @info_lines      =  nil
  set_program_name pr_name
  @stdout        = $stdout
  @stderr        = $stderr
  @constrain_values  =  nil
  @flags_and_options = flags_and_options
  @usage_values    = usage_values
  @value_names   =  []
  version_context    = options[:version_context]
  @version     = options[:version] || infer_version_(version_context)

  @specifications << CLASP::Flag.Help(handle: proc { show_usage_ }) unless options[:no_help_flag]
  @specifications << CLASP::Flag.Version(handle: proc { show_version_ }) unless options[:no_version_flag]

  yield self if block_given?
end

Instance Attribute Details

#constrain_valuesObject

(Integer, Range) Optional constraint on the values that must be provided to the program



363
364
365
# File 'lib/libclimate/climate.rb', line 363

def constrain_values
  @constrain_values
end

#exit_on_missingObject

(boolean) Indicates whether exit will be called (with non-zero exit code) when a required command-line option is missing. Defaults to true



335
336
337
# File 'lib/libclimate/climate.rb', line 335

def exit_on_missing
  @exit_on_missing
end

#exit_on_unknownObject

(boolean) Indicates whether exit will be called (with non-zero exit code) when an unknown command-line flag or option is encountered. Defaults to true



339
340
341
# File 'lib/libclimate/climate.rb', line 339

def exit_on_unknown
  @exit_on_unknown
end

#exit_on_usageObject

(boolean) Indicates whether exit will be called (with zero exit code) when usage/version is requested on the command-line. Defaults to true



341
342
343
# File 'lib/libclimate/climate.rb', line 341

def exit_on_usage
  @exit_on_usage
end

#flags_and_optionsObject

(String) Optional string to describe the flags and options section. Defaults to “[ ... flags and options ... ]”



365
366
367
# File 'lib/libclimate/climate.rb', line 365

def flags_and_options
  @flags_and_options
end

#ignore_unknownObject

(boolean) Indicates whether unknown flags or options will be ignored. This overrides :exit_on_unknown. Defaults to false



337
338
339
# File 'lib/libclimate/climate.rb', line 337

def ignore_unknown
  @ignore_unknown
end

#info_linesObject

([String]) Optional array of string of program-information that will be written before the rest of the usage block when usage is requested on the command-line



343
344
345
# File 'lib/libclimate/climate.rb', line 343

def info_lines
  @info_lines
end

#program_nameObject

(String) A program name; defaults to the name of the executing script



345
346
347
348
349
350
351
352
353
354
355
# File 'lib/libclimate/climate.rb', line 345

def program_name

  name = @program_name

  if defined?(Colcon) && @stdout.tty?

    name = "#{::Colcon::Decorations::Bold}#{name}#{::Colcon::Decorations::Unbold}"
  end

  name
end

#specificationsObject (readonly)

([CLASP::Specification]) An array of specifications attached to the climate instance, whose contents should be modified by adding (or removing) CLASP specifications



331
332
333
# File 'lib/libclimate/climate.rb', line 331

def specifications
  @specifications
end

#stderr::IO

Returns The output stream for contingent output; defaults to $stderr.

Returns:

  • (::IO)

    The output stream for contingent output; defaults to $stderr



361
362
363
# File 'lib/libclimate/climate.rb', line 361

def stderr
  @stderr
end

#stdout::IO

Returns The output stream for normative output; defaults to $stdout.

Returns:

  • (::IO)

    The output stream for normative output; defaults to $stdout



359
360
361
# File 'lib/libclimate/climate.rb', line 359

def stdout
  @stdout
end

#usage_values::String

Returns Optional string to describe the program values, eg <xyz “[ { <<directory> | &lt;file> } ]”.

Returns:

  • (::String)

    Optional string to describe the program values, eg <xyz “[ { <<directory> | &lt;file> } ]”



367
368
369
# File 'lib/libclimate/climate.rb', line 367

def usage_values
  @usage_values
end

#value_namesObject

([String]) Zero-based array of names for values to be used when that value is not present (according to the :constrain_values attribute)



369
370
371
# File 'lib/libclimate/climate.rb', line 369

def value_names
  @value_names
end

#versionObject

(String, [String], [Integer]) A version string or an array of integers/strings representing the version component(s)



371
372
373
# File 'lib/libclimate/climate.rb', line 371

def version
  @version
end

Instance Method Details

#abort(message, options = {}) ⇒ Object

Calls abort() with the given message prefixed by the program_name

Signature

  • Parameters:

    • message (String) The message string

    • options (Hash) An option hash, containing any of the following options

  • Options:

    • :stream optional The output stream to use. Defaults to the value of the attribute stderr

    • :program_name (String) optional Uses the given value rather than the program_name attribute; does not prefix if the empty string

    • :exit optional The exit code. Defaults to 1. Does not exit if nil specified explicitly

Returns

The combined message string, if exit() not called.



680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# File 'lib/libclimate/climate.rb', line 680

def abort message, options={}

  prog_name  =  options[:program_name]
  prog_name  ||=  program_name
  prog_name  ||=  ''

  stream   =  options[:stream]
  stream   ||=  stderr
  stream   ||=  $stderr

  exit_code  =  options.has_key?(:exit) ? options[:exit] : 1

  if prog_name.empty?

    msg = message
  else

    msg = "#{prog_name}: #{message}"
  end


  stream.puts msg

  exit(exit_code) if exit_code

  msg
end

#add_alias(name_or_specification, *aliases) ⇒ Object

Adds an alias to specifications

Signature

  • Parameters:

    • name_or_specification (String) The flag/option name or the valued option

    • aliases (*[String]) One or more aliases

Examples

Specification(s) of a flag (single statement)

climate.add_flag('--mark-missing', alias: '-x')

climate.add_flag('--absolute-path', aliases: [ '-abs', '-p' ])

Specification(s) of a flag (multiple statements)

climate.add_flag('--mark-missing')
climate.add_alias('--mark-missing', '-x')

climate.add_flag('--absolute-path')
climate.add_alias('--absolute-path', '-abs', '-p')

Specification(s) of an option (single statement)

climate.add_option('--add-patterns', alias: '-p')

Specification(s) of an option (multiple statements)

climate.add_option('--add-patterns')
climate.add_alias('--add-patterns', '-p')

Specification of a valued option (which has to be multiple statements)

climate.add_option('--verbosity', values: [ 'succinct', 'verbose' ])
climate.add_alias('--verbosity=succinct', '-s')
climate.add_alias('--verbosity=verbose', '-v')

Raises:

  • (ArgumentError)


804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
# File 'lib/libclimate/climate.rb', line 804

def add_alias(name_or_specification, *aliases)

  check_parameter name_or_specification, 'name_or_specification', allow_nil: false, types: [ ::String, ::Symbol, ::CLASP::Flag, ::CLASP::Option ]
  raise ArgumentError, "must supply at least one alias" if aliases.empty?

  case name_or_specification
  when ::CLASP::Flag

    self.specifications << name_or_specification
  when ::CLASP::Option

    self.specifications << name_or_specification
  else

    self.specifications << CLASP.Alias(name_or_specification, aliases: aliases)
  end
end

#add_flag(name_or_flag, options = {}, &block) ⇒ Object

Adds a flag to specifications

Signature

  • Parameters:

    • name_or_flag (String, ::CLASP::FlagSpecification) The flag name or instance of CLASP::FlagSpecification

    • options (Hash) An options hash, containing any of the following options

  • Options:

    • :alias (String) A single alias

    • :aliases ([String]) An array of aliases

    • :help (String) Description string used when writing response to “--help” flag

    • :required (boolean) Indicates whether the flag is required, causing #run to fail with appropriate message if the flag is not specified in the command-line arguments

Examples

Specification(s) of a flag (single statement)



726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/libclimate/climate.rb', line 726

def add_flag(name_or_flag, options={}, &block)

  check_parameter name_or_flag, 'name_or_flag', allow_nil: false, types: [ ::String, ::Symbol, ::CLASP::Flag ]

  if ::CLASP::Flag === name_or_flag

    specifications << name_or_flag
  else

    specifications << CLASP.Flag(name_or_flag, **options, &block)
  end
end

#add_option(name_or_option, options = {}, &block) ⇒ Object

Adds an option to specifications

Signature

  • Parameters:

    • name_or_option (String, CLASP::OptionSpecification) The option name or instance of CLASP::OptionSpecification

    • options (Hash) An options hash, containing any of the following options

  • Options:

    • :alias (String) A single alias

    • :aliases ([String]) An array of aliases

    • :help (String) Description string used when writing response to “--help” flag

    • :values_range ([String]) An array of strings representing the valid/expected values used when writing response to “--help” flag. NOTE: the current version does not validate against these values, but a future version may do so

    • :default_value (String) The default version used when, say, for the option --my-opt the command-line contain the argument “--my-opt=



753
754
755
756
757
758
759
760
761
762
763
764
# File 'lib/libclimate/climate.rb', line 753

def add_option(name_or_option, options={}, &block)

  check_parameter name_or_option, 'name_or_option', allow_nil: false, types: [ ::String, ::Symbol, ::CLASP::Option ]

  if ::CLASP::Option === name_or_option

    specifications << name_or_option
  else

    specifications << CLASP.Option(name_or_option, **options, &block)
  end
end

#aliasesObject

DEPRECATED

Instead, use specifications



333
# File 'lib/libclimate/climate.rb', line 333

def aliases; specifications; end

#run(argv = ARGV) ⇒ Object

Executes the prepared Climate instance

Signature

  • Parameters:

    • argv ([String]) The array of arguments; defaults to ARGV

Returns

an instance of a type derived from ::Hash with the additional attributes flags, options, values, and argv.

Raises:

  • (ArgumentError)


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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/libclimate/climate.rb', line 384

def run argv = ARGV # :yields: customised +::Hash+

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

  arguments  =  CLASP::Arguments.new argv, specifications
  flags    = arguments.flags
  options    = arguments.options
  values   =  arguments.values.to_a

  results    = {

    flags: {

      given:   flags,
      handled: [],
      unhandled: [],
      unknown: [],
    },

    options: {

      given:   options,
      handled: [],
      unhandled: [],
      unknown: [],
    },

    values: values,

    missing_option_aliases: [],
  }

  flags.each do |f|

    al = specifications.detect do |a|

      a.kind_of?(::CLASP::Flag) && f.name == a.name
    end

    if al

      selector = :unhandled

      # see if it has an :action attribute (which will have been
      # monkey-patched to CLASP.Flag()

      if al.respond_to?(:action) && !al.action.nil?

        al.action.call(f, al)

        selector = :handled
      else

        ex = al.extras

        case ex
        when ::Hash

          if ex.has_key? :handle

            ex[:handle].call(f, al)

            selector = :handled
          end
        end
      end

      results[:flags][selector] << f
    else

      message = "unrecognised flag '#{f}'; use --help for usage"

      if false

      elsif ignore_unknown

        ;
      elsif exit_on_unknown

        self.abort message
      else

        if program_name && !program_name.empty?

          message = "#{program_name}: #{message}"
        end

        stderr.puts message
      end

      results[:flags][:unknown] << f
    end
  end

  options.each do |o|

    al = specifications.detect do |a|

      a.kind_of?(::CLASP::Option) && o.name == a.name
    end

    if al

      selector = :unhandled

      # see if it has an :action attribute (which will have been
      # monkey-patched to CLASP.Option()

      if al.respond_to?(:action) && !al.action.nil?

        al.action.call(o, al)

        selector = :handled
      else

        ex = al.extras

        case ex
        when ::Hash

          if ex.has_key? :handle

            ex[:handle].call(o, al)

            selector = :handled
          end
        end
      end

      results[:options][selector] << o
    else

      message = "unrecognised option '#{o}'; use --help for usage"

      if false

      elsif ignore_unknown

        ;
      elsif exit_on_unknown

        self.abort message
      else

        if program_name && !program_name.empty?

          message = "#{program_name}: #{message}"
        end

        stderr.puts message
      end

      results[:options][:unknown] << o
    end
  end


  # now police any required options

  required_specifications = specifications.select do |a|

    a.kind_of?(::CLASP::Option) && a.required?
  end

  required_specifications = Hash[required_specifications.map { |a| [ a.name, a ] }]

  given_options = Hash[results[:options][:given].map { |o| [ o.name, o ]}]

  required_specifications.each do |k, a|

    unless given_options.has_key? k

      message = a.required_message

      if exit_on_missing

        self.abort message
      else

        if program_name && !program_name.empty?

          message = "#{program_name}: #{message}"
        end

        stderr.puts message
      end

      results[:missing_option_aliases] << a
    end
  end

  # now police the values

  values_constraint  =  constrain_values
  values_constraint  =  values_constraint.begin if ::Range === values_constraint && values_constraint.end == values_constraint.begin
  val_names      =  ::Array === value_names ? value_names : []

  case values_constraint
  when nil

    ;
  when ::Integer

    unless values.size == values_constraint

      if name = val_names[values.size]

        message = name + ' not specified; use --help for usage'
      else

        message = "wrong number of values: #{values.size} given, #{values_constraint} required; use --help for usage"
      end

      if exit_on_unknown

        self.abort message
      else

        if program_name && !program_name.empty?

          message = "#{program_name}: #{message}"
        end

        stderr.puts message
      end
    end
  when ::Range

    unless values_constraint.include? values.size

      if name = val_names[values.size]

        message = name + ' not specified; use --help for usage'
      else

        message = "wrong number of values: #{values.size} givens, #{values_constraint.begin} - #{values_constraint.end - (values_constraint.exclude_end? ? 1 : 0)} required; use --help for usage"
      end

      if exit_on_unknown

        self.abort message
      else

        if program_name && !program_name.empty?

          message = "#{program_name}: #{message}"
        end

        stderr.puts message
      end
    end
  else

    warn "value of 'constrain_values' attribute - '#{constrain_values}' (#{constrain_values.class}) - of wrong type : must be #{::Integer}, #{::Range}, or nil"
  end



  def results.flags

    self[:flags]
  end

  def results.options

    self[:options]
  end

  def results.values

    self[:values]
  end

  results.define_singleton_method(:argv) do

    argv
  end

  results
end

#set_program_name(name) ⇒ Object

DEPRECATED

This method is now deprecated. Instead use program_name=



325
326
327
328
# File 'lib/libclimate/climate.rb', line 325

def set_program_name name

  @program_name  =  name
end