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(value_attributes: true)  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, sp|

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

cl.usage_values = '<source-path> [ <destination-path> ]'
cl.constrain_values = 1..2
cl.value_names = %w{ source-path destination-path }

cl.info_lines = [

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

r = climate.run ARGV

puts "copying from '#{r.source_path}' to '#{r.destination_path || '.'}'"

Defined Under Namespace

Modules: Climate_Constants_ Classes: ParseResults

Instance Attribute Summary collapse

Class Method 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
    • :value_attributes (boolean) Causes any possible value-names, as described in #value_names, to be applied as attributes with the given values, if any, on the command-line
    • :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 that receives the initialising Climate instance, allowing the user to modify the attributes.

Yields:

  • (_self)

Yield Parameters:



803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/libclimate/climate.rb', line 803

def initialize(options={}, &blk) # :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

  given_specs         = options[Climate_Constants_::GIVEN_SPECS_]

  @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_help_suffix  = 'use --help for usage'
  @usage_values       = usage_values
  @value_names        = []
  version_context     = options[:version_context]
  @version            = options[:version] || infer_version_(version_context)

  @value_attributes   = options[:value_attributes]

  unless options[:no_help_flag]

    f = CLASP::Flag.Help()

    unless f.respond_to?(:action)

      class << f

        attr_accessor :action
      end
    end

    f.action = Proc.new { show_usage_ }

    @specifications << f
  end

  unless options[:no_version_flag]

    f = CLASP::Flag.Version()

    unless f.respond_to?(:action)

      class << f

        attr_accessor :action
      end
    end

    f.action = Proc.new { show_version_ }

    @specifications << f
  end

  @specifications = @specifications + given_specs if given_specs

  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



920
921
922
# File 'lib/libclimate/climate.rb', line 920

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



892
893
894
# File 'lib/libclimate/climate.rb', line 892

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



896
897
898
# File 'lib/libclimate/climate.rb', line 896

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



898
899
900
# File 'lib/libclimate/climate.rb', line 898

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



922
923
924
# File 'lib/libclimate/climate.rb', line 922

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



894
895
896
# File 'lib/libclimate/climate.rb', line 894

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



900
901
902
# File 'lib/libclimate/climate.rb', line 900

def info_lines
  @info_lines
end

#program_nameObject

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



902
903
904
905
906
907
908
909
910
911
912
# File 'lib/libclimate/climate.rb', line 902

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



888
889
890
# File 'lib/libclimate/climate.rb', line 888

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



918
919
920
# File 'lib/libclimate/climate.rb', line 918

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



916
917
918
# File 'lib/libclimate/climate.rb', line 916

def stdout
  @stdout
end

#usage_help_suffixObject

(String) The string that is appended to #abort calls made during #run. Defaults to "use --help for usage"



924
925
926
# File 'lib/libclimate/climate.rb', line 924

def usage_help_suffix
  @usage_help_suffix
end

#usage_values::String

Returns Optional string to describe the program values, eg <xyz "[ { < | <file> } ]".

Returns:

  • (::String)

    Optional string to describe the program values, eg <xyz "[ { < | <file> } ]"



926
927
928
# File 'lib/libclimate/climate.rb', line 926

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)



928
929
930
# File 'lib/libclimate/climate.rb', line 928

def value_names
  @value_names
end

#versionObject

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



930
931
932
# File 'lib/libclimate/climate.rb', line 930

def version
  @version
end

Class Method Details

.check_type_(v, types) ⇒ Object



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

def self.check_type_(v, types)

  return true if v.nil?

  types = [ types ] unless Array === types

  return true if types.empty?

  types.each do |type|

    if false

      ;
    elsif :boolean == type

      return true if [ TrueClass, FalseClass ].include? v.class
    elsif type.is_a?(Class)

      return true if v.is_a?(type)
    elsif type.is_a?(Array)

      t0 = type[0]

      if t0

        #return true if v.is_a?
      else

        # Can be array of anything

        return true if v.is_a?(Array)
      end
    else

      warn "Cannot validate type of '#{v}' (#{v.class}) against type specification '#{type}'"
    end
  end

  false
end

.load(source, options = (options_defaulted_ = {}), &blk) ⇒ Object

Loads an instance of the class, 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

  • 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 that receives the initialising Climate instance, allowing the user to modify the attributes.



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/libclimate/climate.rb', line 729

def self.load(source, options = (options_defaulted_ = {}), &blk) # :yields: climate

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

  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

  _libclimate         = require_element_(h, Hash, 'libclimate', nil)
  _exit_on_missing    = lookup_element_(_libclimate, :boolean, 'exit_on_missing', 'libclimate')
  _ignore_unknown     = lookup_element_(_libclimate, :boolean, 'ignore_unknown', 'libclimate')
  _exit_on_unknown    = lookup_element_(_libclimate, :boolean, 'exit_on_unknown', 'libclimate')
  _exit_on_usage      = lookup_element_(_libclimate, :boolean, 'exit_on_usage', 'libclimate')
  _info_lines         = lookup_element_(_libclimate, Array, 'info_lines', 'libclimate')
  _program_name       = lookup_element_(_libclimate, String, 'program_name', 'libclimate')
  _constrain_values   = lookup_element_(_libclimate, [ Integer, Range ], 'constrain_values', 'libclimate')
  _flags_and_options  = lookup_element_(_libclimate, String, 'flags_and_options', 'libclimate')
  _usage_values       = lookup_element_(_libclimate, String, 'usage_values', 'libclimate')
  _value_names        = lookup_element_(_libclimate, Array, 'value_names', 'libclimate')
  _version            = lookup_element_(_libclimate, [ String, [] ], 'version', 'libclimate')

  specs = CLASP::Arguments.load_specifications _libclimate, options

  cl    = Climate.new(options.merge(Climate_Constants_::GIVEN_SPECS_ => specs), &blk)

  cl.exit_on_missing    = _exit_on_missing unless _exit_on_missing.nil?
  cl.ignore_unknown     = _ignore_unknown unless _ignore_unknown.nil?
  cl.exit_on_unknown    = _exit_on_unknown unless _exit_on_unknown.nil?
  cl.exit_on_usage      = _exit_on_usage unless _exit_on_usage.nil?
  cl.info_lines         = _info_lines unless _info_lines.nil?
  cl.program_name       = _program_name unless _program_name.nil?
  cl.constrain_values   = _constrain_values unless _constrain_values.nil?
  cl.flags_and_options  = _flags_and_options unless _flags_and_options.nil?
  cl.usage_values       = _usage_values unless _usage_values.nil?
  cl.value_names        = _value_names unless _value_names.nil?
  cl.version            = _version unless _version.nil?

  cl
end

.lookup_element_(h, types, name, path) ⇒ Object



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/libclimate/climate.rb', line 531

def self.lookup_element_(h, types, name, path)

  if h.has_key?(name)

    r = h[name]

    unless self.check_type_(r, types)

      raise TypeError, "element '#{name}' is of type '#{r.class}' and '#{types}' is required"
    end

    return r
  end

  nil
end

.require_element_(h, types, name, path) ⇒ Object



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/libclimate/climate.rb', line 548

def self.require_element_(h, types, name, path)

  unless h.has_key?(name)

    if (path || '').empty?

      raise ArgumentError, "missing top-level element '#{name}' in load configuration"
    else

      raise ArgumentError, "missing element '#{path}/#{name}' in load configuration"
    end
  else

    r = h[name]

    unless self.check_type_(r, types)

      raise TypeError, "element '#{name}' is of type '#{r.class}' and '#{types}' is required"
    end

    return r
  end
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.



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
# File 'lib/libclimate/climate.rb', line 1210

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)


1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
# File 'lib/libclimate/climate.rb', line 1339

def add_alias(name_or_specification, *aliases)

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

  case name_or_specification
  when ::CLASP::FlagSpecification

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

    self.specifications << name_or_specification
  else

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

#add_flag(name_or_flag, options = {}, &blk) ⇒ 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
  • Block An optional block that is invoked when the parsed command-line contains the given flag, receiving the argument and the alias

Examples

Specification(s) of a flag (single statement)



1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# File 'lib/libclimate/climate.rb', line 1258

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

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

  if ::CLASP::FlagSpecification === name_or_flag

    specifications << name_or_flag
  else

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

#add_option(name_or_option, options = {}, &blk) ⇒ 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=+"
  • Block An optional block that is invoked when the parsed command-line contains the given option, receiving the argument and the alias



1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'lib/libclimate/climate.rb', line 1288

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

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

  if ::CLASP::OptionSpecification === name_or_option

    specifications << name_or_option
  else

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

#aliasesObject

[DEPRECATED] Instead, use specifications



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

def aliases; specifications; end

#check_required_options_(specifications, options, missing, raise_on_required) ⇒ Object



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

def check_required_options_(specifications, options, missing, raise_on_required)

  required_specifications = specifications.select do |sp|

    sp.kind_of?(::CLASP::OptionSpecification) && sp.required?
  end

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

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

  required_specifications.each do |k, sp|

    unless given_options.has_key? k

      message = sp.required_message

      if false

        ;
      elsif raise_on_required

        if raise_on_required.is_a?(Class)

          raise raise_on_required, message
        else

          raise RuntimeError, message
        end
      elsif exit_on_missing

        self.abort message
      else

        if program_name && !program_name.empty?

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

        stderr.puts message
      end

      missing << sp
      #results[:missing_option_aliases] << sp
    end
  end
end

#check_value_constraints_(values) ⇒ Object



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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
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
707
708
# File 'lib/libclimate/climate.rb', line 621

def check_value_constraints_(values)

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

    warn "value of 'constrain_values' attribute, if an #{::Array}, must not be empty and all elements must be of type #{::Integer}" if values_constraint.empty? || !values_constraint.all? { |v| ::Integer === v }

    unless values_constraint.include? values.size

      message = make_abort_message_("wrong number of values: #{values.size} given, #{values_constraint} required")

      if exit_on_missing

        self.abort message
      else

        if program_name && !program_name.empty?

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

        stderr.puts message
      end
    end
  when ::Integer

    unless values.size == values_constraint

      if name = val_names[values.size]

        message = make_abort_message_(name + ' not specified')
      else

        message = make_abort_message_("wrong number of values: #{values.size} given, #{values_constraint} required")
      end

      if exit_on_missing

        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 = make_abort_message_(name + ' not specified')
      else

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

      if exit_on_missing

        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 #{::Array}, #{::Integer}, #{::Range}, or nil"
  end
end

#infer_version_(ctxt) ⇒ Object



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

def infer_version_(ctxt)

  # algorithm:
  #
  # 1. PROGRAM_VERSION: loaded from ctxt / global
  # 2. PROGRAM_VER(SION)_(MAJOR|MINOR|(PATCH|REVISION)|BUILD): loaded from
  #    ctxt / global

  if ctxt

    ctxt = ctxt.class unless ::Class === ctxt

    return ctxt.const_get(:PROGRAM_VERSION) if ctxt.const_defined? :PROGRAM_VERSION

    ver = []

    if ctxt.const_defined? :PROGRAM_VER_MAJOR

      ver << ctxt.const_get(:PROGRAM_VER_MAJOR)

      if ctxt.const_defined? :PROGRAM_VER_MINOR

        ver << ctxt.const_get(:PROGRAM_VER_MINOR)

        if ctxt.const_defined?(:PROGRAM_VER_REVISION) || ctxt.const_defined?(:PROGRAM_VER_PATCH)

          if ctxt.const_defined?(:PROGRAM_VER_PATCH)

            ver << ctxt.const_get(:PROGRAM_VER_PATCH)
          else

            ver << ctxt.const_get(:PROGRAM_VER_REVISION)
          end

          if ctxt.const_defined? :PROGRAM_VER_BUILD

            ver << ctxt.const_get(:PROGRAM_VER_BUILD)
          end
        end
      end

      return ver
    end
  else

    return PROGRAM_VERSION if defined? PROGRAM_VERSION

    ver = []

    if defined? PROGRAM_VER_MAJOR

      ver << PROGRAM_VER_MAJOR

      if defined? PROGRAM_VER_MINOR

        ver << PROGRAM_VER_MINOR

        if defined?(PROGRAM_VER_REVISION) || defined?(PROGRAM_VER_PATCH)

          if defined?(PROGRAM_VER_PATCH)

            ver << PROGRAM_VER_PATCH
          else

            ver << PROGRAM_VER_REVISION
          end

          if defined? PROGRAM_VER_BUILD

            ver << PROGRAM_VER_BUILD
          end
        end
      end

      return ver
    end
  end

  nil
end

#make_abort_message_(msg) ⇒ Object



382
383
384
385
386
387
388
389
390
391
# File 'lib/libclimate/climate.rb', line 382

def make_abort_message_(msg)

  if 0 != (usage_help_suffix || 0).size

    "#{msg}; #{usage_help_suffix}"
  else

    msg
  end
end

#on_flag(name_or_flag, options = {}, &blk) ⇒ Object

Attaches a block to an already-registered flag

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. No options are recognised currently
  • Options:

  • Block A required block that is invoked when the parsed command-line contains the given flag, receiving the argument and the alias

Raises:

  • (ArgumentError)


1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
# File 'lib/libclimate/climate.rb', line 1369

def on_flag(name_or_flag, options={}, &blk)

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

  raise ArgumentError, "on_flag() requires a block to be given" unless block_given?

  specifications.each do |spec|

    case spec
    when CLASP::FlagSpecification

      if spec == name_or_flag

        spec.action = blk

        return true
      end
    end
  end

  warn "The Climate instance does not contain a FlagSpecification matching '#{name_or_flag}' (#{name_or_flag.class})"

  false
end

#on_option(name_or_option, options = {}, &blk) ⇒ Object

Attaches a block to an already-registered option

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. No options are recognised currently
  • Options:

  • Block A required block that is invoked when the parsed command-line contains the given option, receiving the argument and the alias

Raises:

  • (ArgumentError)


1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
# File 'lib/libclimate/climate.rb', line 1406

def on_option(name_or_option, options={}, &blk)

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

  raise ArgumentError, "on_option() requires a block to be given" unless block_given?

  specifications.each do |spec|

    case spec
    when CLASP::OptionSpecification

      if spec == name_or_option

        spec.action = blk

        return true
      end
    end
  end

  warn "The Climate instance does not contain an OptionSpecification matching '#{name_or_option}' (#{name_or_option.class})"

  false
end

#parse(argv = ARGV, **options) ⇒ Object

Parse the given command-line (passed as argv) by the given instance

Signature

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

Returns

(ParseResults) Results

Raises:

  • (ArgumentError)


941
942
943
944
945
946
947
948
# File 'lib/libclimate/climate.rb', line 941

def parse(argv = ARGV, **options) # :yields: ParseResults

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

  arguments = CLASP::Arguments.new argv, specifications

  ParseResults.new(self, arguments, argv)
end

#parse_and_verify(argv = ARGV, **options) ⇒ Object

Parse the given command-line (passed as argv) by the given instance, and verifies it

Signature

  • Parameters:

    • argv ([String]) The array of arguments; defaults to ARGV
    • options (Hash) Options
  • Options:

    • :raise_on_required (boolean, Exception) Causes an/the given exception to be raised if any required options are not specified in the command-line
    • :raise_on_unrecognised (boolean, Exception) Causes an/the given exception to be raised if any unrecognised flags/options are specified in the command-line
    • :raise_on_unused (boolean, Exception) Causes an/the given exception to be raised if any given flags/options are not used
    • :raise (boolean, Exception) Causes an/the given exception to be raised in all conditions

Returns

(ParseResults) Results



967
968
969
970
971
972
973
974
# File 'lib/libclimate/climate.rb', line 967

def parse_and_verify(argv = ARGV, **options) # :yields: ParseResults

  r = parse argv, **options

  r.verify(**options)

  r
end

#run(argv = ARGV, **options) ⇒ Object

[DEPRECATED] Use Climate#parse_and_verify() (but be aware that the returned result is of a different type

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, double_slash_index and argv.

Raises:

  • (ArgumentError)


988
989
990
991
992
993
994
995
# File 'lib/libclimate/climate.rb', line 988

def run(argv = ARGV, **options) # :yields: customised +::Hash+

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

  arguments = CLASP::Arguments.new argv, specifications

  run_ argv, arguments, **options
end

#set_program_name(name) ⇒ Object

[DEPRECATED] This method is now deprecated. Instead use program_name=



882
883
884
885
# File 'lib/libclimate/climate.rb', line 882

def set_program_name(name)

  @program_name = name
end

#show_usage_Object



393
394
395
396
397
398
399
400
401
402
# File 'lib/libclimate/climate.rb', line 393

def show_usage_()

  options = {}
  options.merge! stream: stdout, program_name: program_name, version: version, exit: exit_on_usage ? 0 : nil
  options[:info_lines] = info_lines if info_lines
  options[:values] = usage_values if usage_values
  options[:flags_and_options] = flags_and_options if flags_and_options

  CLASP.show_usage specifications, options
end

#show_version_Object



404
405
406
407
# File 'lib/libclimate/climate.rb', line 404

def show_version_()

  CLASP.show_version specifications, stream: stdout, program_name: program_name, version: version, exit: exit_on_usage ? 0 : nil
end