Class: Aspera::Cli::Manager
- Inherits:
-
Object
- Object
- Aspera::Cli::Manager
- Defined in:
- lib/aspera/cli/manager.rb
Overview
parse command line options arguments options start with ‘-’, others are commands resolves on extended value syntax
Constant Summary collapse
- BOOLEAN_SIMPLE =
boolean options are set to true/false from the following values
i[no yes].freeze
- OPTION_VALUE_SEPARATOR =
'='
- OPTION_PREFIX =
'--'
- OPTIONS_STOP =
'--'
Instance Attribute Summary collapse
-
#ask_missing_mandatory ⇒ Object
Returns the value of attribute ask_missing_mandatory.
-
#ask_missing_optional ⇒ Object
Returns the value of attribute ask_missing_optional.
-
#fail_on_missing_mandatory ⇒ Object
writeonly
Sets the attribute fail_on_missing_mandatory.
-
#parser ⇒ Object
readonly
Returns the value of attribute parser.
Class Method Summary collapse
- .enum_to_bool(enum) ⇒ Object
-
.get_from_list(short_value, descr, allowed_values) ⇒ Object
find shortened string value in allowed symbol list.
-
.multi_choice_assert(assertion, error_msg, choices) ⇒ Object
Generates error message with list of allowed values.
-
.option_line_to_name(name) ⇒ Object
change option name with dash to name with underscore.
- .option_name_to_line(name) ⇒ Object
- .time_to_string(time) ⇒ Object
- .validate_type(what, descr, value, type_list) ⇒ Object
Instance Method Summary collapse
-
#add_option_preset(preset_hash, where, override: true) ⇒ Object
Adds each of the keys of specified hash as an option.
-
#command_or_arg_empty? ⇒ Boolean
check if there were unprocessed values to generate error.
-
#declare(option_symbol, description, handler: nil, default: nil, values: nil, short: nil, coerce: nil, types: nil, deprecation: nil, &block) ⇒ Object
declare an option.
-
#final_errors ⇒ Object
unprocessed options or arguments ?.
- #get_interactive(type, descr, expected: :single) ⇒ Object
-
#get_next_argument(descr, expected: :single, mandatory: true, type: nil, aliases: nil, default: nil) ⇒ Object
Value, list or nil.
- #get_next_command(command_list, aliases: nil) ⇒ Object
-
#get_option(option_symbol, mandatory: false, default: nil) ⇒ Object
Get an option value by name either return value or calls handler, can return nil ask interactively if requested/required.
-
#initialize(program_name) ⇒ Manager
constructor
A new instance of Manager.
-
#known_options(only_defined: false) ⇒ Hash
Options as taken from config file and command line just before command execution.
- #parse_command_line(argv) ⇒ Object
-
#parse_options! ⇒ Object
removes already known options from the list.
- #prompt_user_input(prompt, sensitive) ⇒ Object
-
#prompt_user_input_in_list(prompt, sym_list) ⇒ Symbol
prompt user for input in a list of symbols.
-
#set_option(option_symbol, value, where = 'code override') ⇒ Object
set an option value by name, either store value or call handler.
-
#unprocessed_options_with_value ⇒ Object
get all original options on command line used to generate a config in config file.
Constructor Details
#initialize(program_name) ⇒ Manager
Returns a new instance of Manager.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
# File 'lib/aspera/cli/manager.rb', line 120 def initialize(program_name) # command line values *not* starting with '-' @unprocessed_cmd_line_arguments = [] # command line values starting with '-' = [] # a copy of all initial options = [] # option description: key = option symbol, value=Hash, :read_write, :accessor, :value, :accepted = {} # do we ask missing options and arguments to user ? @ask_missing_mandatory = false # STDIN.isatty # ask optional options if not provided and in interactive @ask_missing_optional = false @fail_on_missing_mandatory = true # Array of [key(sym), value] # those must be set before parse # parse consumes those defined only @option_pairs_batch = {} @option_pairs_env = {} # NOTE: was initially inherited but it is preferred to have specific methods @parser = OptionParser.new @parser.program_name = program_name # options can also be provided by env vars : --param-name -> ASCLI_PARAM_NAME env_prefix = program_name.upcase + OPTION_SEP_SYMBOL ENV.each do |k, v| if k.start_with?(env_prefix) @option_pairs_env[k[env_prefix.length..-1].downcase.to_sym] = v end end Log.log.debug{"env=#{@option_pairs_env}".red} = [] @unprocessed_cmd_line_arguments = [] end |
Instance Attribute Details
#ask_missing_mandatory ⇒ Object
Returns the value of attribute ask_missing_mandatory.
117 118 119 |
# File 'lib/aspera/cli/manager.rb', line 117 def ask_missing_mandatory @ask_missing_mandatory end |
#ask_missing_optional ⇒ Object
Returns the value of attribute ask_missing_optional.
117 118 119 |
# File 'lib/aspera/cli/manager.rb', line 117 def ask_missing_optional @ask_missing_optional end |
#fail_on_missing_mandatory=(value) ⇒ Object (writeonly)
Sets the attribute fail_on_missing_mandatory
118 119 120 |
# File 'lib/aspera/cli/manager.rb', line 118 def fail_on_missing_mandatory=(value) @fail_on_missing_mandatory = value end |
#parser ⇒ Object (readonly)
Returns the value of attribute parser.
116 117 118 |
# File 'lib/aspera/cli/manager.rb', line 116 def parser @parser end |
Class Method Details
.enum_to_bool(enum) ⇒ Object
66 67 68 69 |
# File 'lib/aspera/cli/manager.rb', line 66 def enum_to_bool(enum) Aspera.assert_values(enum, BOOLEAN_VALUES){'boolean'} return TRUE_VALUES.include?(enum) end |
.get_from_list(short_value, descr, allowed_values) ⇒ Object
find shortened string value in allowed symbol list
76 77 78 79 80 81 82 83 84 85 |
# File 'lib/aspera/cli/manager.rb', line 76 def get_from_list(short_value, descr, allowed_values) # we accept shortcuts matching_exact = allowed_values.select{|i| i.to_s.eql?(short_value)} return matching_exact.first if matching_exact.length == 1 matching = allowed_values.select{|i| i.to_s.start_with?(short_value)} multi_choice_assert(!matching.empty?, "unknown value for #{descr}: #{short_value}", allowed_values) multi_choice_assert(matching.length.eql?(1), "ambiguous shortcut for #{descr}: #{short_value}", matching) return enum_to_bool(matching.first) if allowed_values.eql?(BOOLEAN_VALUES) return matching.first end |
.multi_choice_assert(assertion, error_msg, choices) ⇒ Object
Generates error message with list of allowed values
90 91 92 |
# File 'lib/aspera/cli/manager.rb', line 90 def multi_choice_assert(assertion, error_msg, choices) raise Cli::BadArgument, [error_msg, 'Use:'].concat(choices.map{|c|"- #{c}"}.sort).join("\n") unless assertion end |
.option_line_to_name(name) ⇒ Object
change option name with dash to name with underscore
95 96 97 |
# File 'lib/aspera/cli/manager.rb', line 95 def option_line_to_name(name) return name.gsub(OPTION_SEP_LINE, OPTION_SEP_SYMBOL) end |
.option_name_to_line(name) ⇒ Object
99 100 101 |
# File 'lib/aspera/cli/manager.rb', line 99 def option_name_to_line(name) return "#{OPTION_PREFIX}#{name.to_s.gsub(OPTION_SEP_SYMBOL, OPTION_SEP_LINE)}" end |
.time_to_string(time) ⇒ Object
71 72 73 |
# File 'lib/aspera/cli/manager.rb', line 71 def time_to_string(time) return time.strftime('%Y-%m-%d %H:%M:%S') end |
.validate_type(what, descr, value, type_list) ⇒ Object
107 108 109 110 111 112 113 |
# File 'lib/aspera/cli/manager.rb', line 107 def validate_type(what, descr, value, type_list) return nil if type_list.nil? Aspera.assert(type_list.is_a?(Array) && type_list.all?(Class)){'types must be a Class Array'} raise Cli::BadArgument, "#{what.to_s.capitalize} #{descr} is a #{value.class} but must be #{type_list.length > 1 ? 'one of ' : ''}#{type_list.map(&:name).join(',')}" unless \ type_list.any?{|t|value.is_a?(t)} end |
Instance Method Details
#add_option_preset(preset_hash, where, override: true) ⇒ Object
Adds each of the keys of specified hash as an option
381 382 383 384 385 386 387 388 |
# File 'lib/aspera/cli/manager.rb', line 381 def add_option_preset(preset_hash, where, override: true) Aspera.assert_type(preset_hash, Hash) Log.log.debug{"add_option_preset: #{preset_hash}, #{where}, #{override}"} preset_hash.each do |k, v| option_symbol = k.to_sym @option_pairs_batch[option_symbol] = v if override || !@option_pairs_batch.key?(option_symbol) end end |
#command_or_arg_empty? ⇒ Boolean
check if there were unprocessed values to generate error
391 392 393 |
# File 'lib/aspera/cli/manager.rb', line 391 def command_or_arg_empty? return @unprocessed_cmd_line_arguments.empty? end |
#declare(option_symbol, description, handler: nil, default: nil, values: nil, short: nil, coerce: nil, types: nil, deprecation: nil, &block) ⇒ Object
declare an option
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 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 |
# File 'lib/aspera/cli/manager.rb', line 307 def declare(option_symbol, description, handler: nil, default: nil, values: nil, short: nil, coerce: nil, types: nil, deprecation: nil, &block) Aspera.assert_type(option_symbol, Symbol) Aspera.assert(!.key?(option_symbol)){"#{option_symbol} already declared"} Aspera.assert(description[-1] != '.'){"#{option_symbol} ends with dot"} Aspera.assert(description[0] == description[0].upcase){"#{option_symbol} description does not start with capital"} Aspera.assert(!['hash', 'extended value'].any?{|s|description.downcase.include?(s) }){"#{option_symbol} shall use :types"} opt = [option_symbol] = { read_write: handler.nil? ? :value : :accessor, # by default passwords and secrets are sensitive, else specify when declaring the option sensitive: SecretHider.secret?(option_symbol, '') } if !types.nil? types = [types] unless types.is_a?(Array) Aspera.assert(types.all?(Class)){"types must be (Array of) Class: #{types}"} opt[:types] = types description = "#{description} (#{types.map(&:name).join(', ')})" end if deprecation opt[:deprecation] = deprecation description = "#{description} (#{'deprecated'.blue}: #{deprecation})" end Log.log.debug{"declare: #{option_symbol}: #{opt[:read_write]}".green} if opt[:read_write].eql?(:accessor) Aspera.assert_type(handler, Hash) Aspera.assert(handler.keys.sort.eql?(i[m o])) Log.log.debug{"set attr obj #{option_symbol} (#{handler[:o]},#{handler[:m]})"} opt[:accessor] = AttrAccessor.new(handler[:o], handler[:m], option_symbol) end set_option(option_symbol, default, 'default') unless default.nil? on_args = [description] case values when nil on_args.push(symbol_to_option(option_symbol, 'VALUE')) on_args.push("-#{short}VALUE") unless short.nil? on_args.push(coerce) unless coerce.nil? @parser.on(*on_args) { |v| set_option(option_symbol, v, SOURCE_USER) } when Array, :bool if values.eql?(:bool) values = BOOLEAN_VALUES set_option(option_symbol, Manager.enum_to_bool(default), 'default') unless default.nil? end # this option value must be a symbol opt[:values] = values value = get_option(option_symbol) help_values = values.map{|i|i.eql?(value) ? highlight_current(i) : i}.join(', ') if values.eql?(BOOLEAN_VALUES) help_values = BOOLEAN_SIMPLE.map{|i|(i.eql?(:yes) && value) || (i.eql?(:no) && !value) ? highlight_current(i) : i}.join(', ') end on_args[0] = "#{description}: #{help_values}" on_args.push(symbol_to_option(option_symbol, 'ENUM')) on_args.push(values) @parser.on(*on_args){|v|set_option(option_symbol, self.class.get_from_list(v.to_s, description, values), SOURCE_USER)} when :date on_args.push(symbol_to_option(option_symbol, 'DATE')) @parser.on(*on_args) do |v| time_string = case v when 'now' then Manager.time_to_string(Time.now) when /^-([0-9]+)h/ then Manager.time_to_string(Time.now - (Regexp.last_match(1).to_i * 3600)) else v end set_option(option_symbol, time_string, SOURCE_USER) end when :none Aspera.assert(!block.nil?){"missing block for #{option_symbol}"} on_args.push(symbol_to_option(option_symbol)) on_args.push("-#{short}") if short.is_a?(String) @parser.on(*on_args, &block) else Aspera.error_unexpected_value(values) end Log.log.debug{"on_args=#{on_args}"} end |
#final_errors ⇒ Object
unprocessed options or arguments ?
396 397 398 399 400 401 |
# File 'lib/aspera/cli/manager.rb', line 396 def final_errors result = [] result.push("unprocessed options: #{@unprocessed_cmd_line_options}") unless .empty? result.push("unprocessed values: #{@unprocessed_cmd_line_arguments}") unless @unprocessed_cmd_line_arguments.empty? return result end |
#get_interactive(type, descr, expected: :single) ⇒ Object
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 |
# File 'lib/aspera/cli/manager.rb', line 483 def get_interactive(type, descr, expected: :single) if !@ask_missing_mandatory raise Cli::BadArgument, "missing argument (#{expected}): #{descr}" unless expected.is_a?(Array) self.class.multi_choice_assert(false, "missing: #{descr}", expected) end result = nil sensitive = type.eql?(:option) && [descr.to_sym].is_a?(Hash) && [descr.to_sym][:sensitive] default_prompt = "#{type}: #{descr}" # ask interactively case expected when :multiple result = [] puts(' (one per line, end with empty line)') loop do entry = prompt_user_input(default_prompt, sensitive) break if entry.empty? result.push(ExtendedValue.instance.evaluate(entry)) end when :single result = ExtendedValue.instance.evaluate(prompt_user_input(default_prompt, sensitive)) else # one fixed result = self.class.get_from_list(prompt_user_input("#{expected.join(' ')}\n#{default_prompt}", sensitive), descr, expected) end return result end |
#get_next_argument(descr, expected: :single, mandatory: true, type: nil, aliases: nil, default: nil) ⇒ Object
Returns value, list or nil.
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 |
# File 'lib/aspera/cli/manager.rb', line 190 def get_next_argument(descr, expected: :single, mandatory: true, type: nil, aliases: nil, default: nil) Aspera.assert(i[single multiple].include?(expected) || (expected.is_a?(Array) && expected.all?(Symbol))) do 'expected must be single, multiple, or array of symbol' end Aspera.assert(type.nil? || type.is_a?(Class) || (type.is_a?(Array) && type.all?(Class))){'type must be Class or Array of Class'} Aspera.assert(aliases.nil? || (aliases.is_a?(Hash) && aliases.keys.all?(Symbol) && aliases.values.all?(Symbol))){'aliases must be Hash'} allowed_types = type unless allowed_types.nil? allowed_types = [allowed_types] unless allowed_types.is_a?(Array) descr = "#{descr} (#{allowed_types.join(', ')})" end result = if !@unprocessed_cmd_line_arguments.empty? # there are values case expected when :single ExtendedValue.instance.evaluate(@unprocessed_cmd_line_arguments.shift) when :multiple value = @unprocessed_cmd_line_arguments.shift(@unprocessed_cmd_line_arguments.length).map{|v|ExtendedValue.instance.evaluate(v)} # if expecting list and only one arg of type array : it is the list if value.length.eql?(1) && value.first.is_a?(Array) value = value.first end value when Array allowed_values = [].concat(expected) allowed_values.concat(aliases.keys) unless aliases.nil? self.class.get_from_list(@unprocessed_cmd_line_arguments.shift, descr, allowed_values) else Aspera.error_unexpected_value(expected) end elsif !default.nil? then default # no value provided, either get value interactively, or exception elsif mandatory then get_interactive(:argument, descr, expected: expected) end if result.is_a?(String) && allowed_types.eql?(TYPE_INTEGER) int_result = Integer(result, exception: false) raise Cli::BadArgument, "Invalid integer: #{result}" if int_result.nil? result = int_result end Log.log.debug{"#{descr}=#{result}"} result = aliases[result] if aliases&.key?(result) self.class.validate_type(:argument, descr, result, allowed_types) unless result.nil? && !mandatory return result end |
#get_next_command(command_list, aliases: nil) ⇒ Object
235 |
# File 'lib/aspera/cli/manager.rb', line 235 def get_next_command(command_list, aliases: nil); return get_next_argument('command', expected: command_list, aliases: aliases); end |
#get_option(option_symbol, mandatory: false, default: nil) ⇒ Object
Get an option value by name either return value or calls handler, can return nil ask interactively if requested/required
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 |
# File 'lib/aspera/cli/manager.rb', line 241 def get_option(option_symbol, mandatory: false, default: nil) Aspera.assert_type(option_symbol, Symbol) attributes = [option_symbol] Aspera.assert(attributes){"option not declared: #{option_symbol}"} result = nil case attributes[:read_write] when :accessor result = attributes[:accessor].value when :value result = attributes[:value] else raise 'unknown type' end Log.log.debug{"(#{attributes[:read_write]}) get #{option_symbol}=#{result}"} result = default if result.nil? # do not fail for manual generation if option mandatory but not set result = '' if result.nil? && mandatory && !@fail_on_missing_mandatory # Log.log.debug{"interactive=#{@ask_missing_mandatory}"} if result.nil? if !@ask_missing_mandatory raise Cli::BadArgument, "Missing mandatory option: #{option_symbol}" if mandatory elsif @ask_missing_optional || mandatory # ask_missing_mandatory expected = :single # print "please enter: #{option_symbol.to_s}" if .key?(option_symbol) && attributes.key?(:values) expected = attributes[:values] end result = get_interactive(:option, option_symbol.to_s, expected: expected) set_option(option_symbol, result, 'interactive') end end self.class.validate_type(:option, option_symbol, result, attributes[:types]) unless result.nil? && !mandatory return result end |
#known_options(only_defined: false) ⇒ Hash
Returns options as taken from config file and command line just before command execution.
427 428 429 430 431 432 433 434 |
# File 'lib/aspera/cli/manager.rb', line 427 def (only_defined: false) result = {} .each_key do |option_symbol| v = get_option(option_symbol) result[option_symbol] = v unless only_defined && v.nil? end return result end |
#parse_command_line(argv) ⇒ Object
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/aspera/cli/manager.rb', line 154 def parse_command_line(argv) @parser.separator('') @parser.separator('OPTIONS: global') declare(:interactive, 'Use interactive input of missing params', values: :bool, handler: {o: self, m: :ask_missing_mandatory}) declare(:ask_options, 'Ask even optional options', values: :bool, handler: {o: self, m: :ask_missing_optional}) = true until argv.empty? value = argv.shift if && value.start_with?('-') Log.log.trace1{"opt: #{value}"} if value.eql?(OPTIONS_STOP) = false else .push(value) end else Log.log.trace1{"arg: #{value}"} @unprocessed_cmd_line_arguments.push(value) end end = .dup.freeze Log.log.debug{"add_cmd_line_options:commands/arguments=#{@unprocessed_cmd_line_arguments},options=#{@unprocessed_cmd_line_options}".red} end |
#parse_options! ⇒ Object
removes already known options from the list
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/aspera/cli/manager.rb', line 437 def Log.log.debug('parse_options!'.red) # first conf file, then env var consume_option_pairs(@option_pairs_batch, 'set') consume_option_pairs(@option_pairs_env, 'env') # command line override = [] begin # remove known options one by one, exception if unknown Log.log.debug('before parse'.red) @parser.parse!() Log.log.debug('After parse'.red) rescue OptionParser::InvalidOption => e Log.log.debug{"InvalidOption #{e}".red} # save for later processing .push(e.args.first) retry end Log.log.debug{"remains: #{unknown_options}"} # set unprocessed options for next time = end |
#prompt_user_input(prompt, sensitive) ⇒ Object
460 461 462 463 464 465 466 |
# File 'lib/aspera/cli/manager.rb', line 460 def prompt_user_input(prompt, sensitive) return $stdin.getpass("#{prompt}> ") if sensitive print("#{prompt}> ") line = $stdin.gets raise 'Unexpected end of standard input' if line.nil? return line.chomp end |
#prompt_user_input_in_list(prompt, sym_list) ⇒ Symbol
prompt user for input in a list of symbols
472 473 474 475 476 477 478 479 480 481 |
# File 'lib/aspera/cli/manager.rb', line 472 def prompt_user_input_in_list(prompt, sym_list) loop do input = prompt_user_input(prompt, false).to_sym if sym_list.any?{|a|a.eql?(input)} return input else $stderr.puts("No such #{prompt}: #{input}, select one of: #{sym_list.join(', ')}") end end end |
#set_option(option_symbol, value, where = 'code override') ⇒ Object
set an option value by name, either store value or call handler
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/aspera/cli/manager.rb', line 278 def set_option(option_symbol, value, where='code override') Aspera.assert_type(option_symbol, Symbol) raise Cli::BadArgument, "Unknown option: #{option_symbol}" unless .key?(option_symbol) attributes = [option_symbol] Log.log.warn("#{option_symbol}: Option is deprecated: #{attributes[:deprecation]}") if attributes[:deprecation] value = ExtendedValue.instance.evaluate(value) value = Manager.enum_to_bool(value) if attributes[:values].eql?(BOOLEAN_VALUES) Log.log.debug{"(#{attributes[:read_write]}/#{where}) set #{option_symbol}=#{value}"} self.class.validate_type(:option, option_symbol, value, attributes[:types]) case attributes[:read_write] when :accessor attributes[:accessor].value = value when :value attributes[:value] = value else # nil or other raise 'error' end end |
#unprocessed_options_with_value ⇒ Object
get all original options on command line used to generate a config in config file
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/aspera/cli/manager.rb', line 404 def result = {} .each do |option_value| case option_value when /^#{OPTION_PREFIX}([^=]+)$/o # ignore when /^#{OPTION_PREFIX}([^=]+)=(.*)$/o name = Regexp.last_match(1) value = Regexp.last_match(2) name.gsub!(OPTION_SEP_LINE, OPTION_SEP_SYMBOL) value = ExtendedValue.instance.evaluate(value) Log.log.debug{"option #{name}=#{value}"} result[name] = value .delete(option_value) else raise Cli::BadArgument, "wrong option format: #{option_value}" end end return result end |