Class: Aspera::Cli::Parser
- Inherits:
-
Object
- Object
- Aspera::Cli::Parser
- Includes:
- Prompt
- Defined in:
- lib/aspera/cli/parser.rb
Overview
Parse command line options and positional arguments.
Options are declared incrementally (global, then plugin options).
Command line options are applied when their option is declared: explicitly with parse_options!,
or automatically on next read of an option or argument. Unknown options are kept for later.
Option values come from several sources, see Option::Source: highest priority wins, whatever the order.
Constant Summary collapse
- CREDENTIAL_OPTIONS =
Options that hold a secret sent to the server at option
url: a client must not redirect them to a host it chooses, seeSecurity#check_credential_host %i[password client_secret private_key passphrase].freeze
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.
Class Method Summary collapse
-
.get_from_list(short_value, descr, allowed_values) ⇒ Symbol, Boolean
Find shortened string value in allowed symbol list.
-
.multi_choice_assert_msg(error_msg, accept_list, aliases: nil) ⇒ Object
Generates error message with list of allowed values.
-
.option_line_to_name(name) ⇒ String
Change option name with dash to name with underscore.
-
.option_name_to_line(name) ⇒ String
Convert option symbol to CLI line flag format.
-
.percent_selector(identifier) ⇒ Hash{Symbol => String}?
Parse percent-selector string into field name and value (extended value is parsed in value).
-
.smart_convert(value, context: 'dotted expression', allowed: nil) ⇒ Boolean, ...
Using dotted hash notation, convert value to bool, int, float or extended value
trueandyesare converted totrue,falseandnotofalse.
Instance Method Summary collapse
-
#add_option_preset(preset_hash, where, override: true, configured: false) ⇒ Object
Adds each of the keys of specified hash as an option.
-
#args_as_extended(end_marker) ⇒ Hash, Array
Read remaining args and build an
ArrayorHashWhen used in an option value, only positional arguments after the option are used. -
#check_credential_host(secret_symbol) ⇒ Object
When a credential is read while a host option
urlis declared, refuse (at levels medium and high) to send a secret of the server's configuration to aurlthat is not in its configuration, e.g. -
#clear_option(option_symbol) ⇒ nil
Set option to
nil. -
#command_or_arg_empty? ⇒ Boolean
Check if there are no pending positional arguments.
-
#declare(option_symbol, description: nil, short: nil, allowed: nil, default: nil, on_set: nil, shorthand: nil, convert: nil, deprecation: nil, schema: nil, complete: nil, security: nil, &block) ⇒ Object
Declare an option.
-
#declared_options ⇒ Hash{Symbol => Option::Value}
All declared options (read-only view).
-
#final_errors(after_error: false) ⇒ Array<String>
Check for unprocessed options or arguments error messages.
-
#get_interactive(descr, multiple: false, accept_list: nil, aliases: nil, schema: nil) ⇒ String
Prompt user for missing option or argument, or raise if not interactive.
-
#get_next_argument(descr, mandatory: true, multiple: false, accept_list: nil, validation: Option::Type::STRING, aliases: nil, default: nil, schema: nil, evaluate: :extended) ⇒ Object, ...
Low-level positional argument reader.
-
#get_next_command(command_list, aliases: nil) ⇒ Symbol
Get next positional command argument from accepted list.
-
#get_option(option_symbol, mandatory: false, schema: nil, complete: false) ⇒ Object
Get an option value by name, can return nil ask interactively if requested/required.
-
#group(name) ⇒ Object
Set the current help section group name for subsequent declarations.
-
#help_text(banner: nil) ⇒ String
Generate help text for all declared options, grouped by section.
-
#initialize(program_name, argv = nil) ⇒ Parser
constructor
A new instance of Parser.
-
#instance_identifier(description: 'identifier', multiple: false, mandatory: true, default: nil, &block) {|field, value| ... } ⇒ String+
Resource identifier as positional parameter.
-
#known_options(only_defined: false) ⇒ Hash
Options as taken from config file and command line just before command execution.
-
#next_argument_in?(values) ⇒ Boolean
Check the next pending positional argument, without consuming it.
-
#next_arguments?(values) ⇒ Boolean
Check the next pending positional arguments, without consuming them.
-
#option_declared?(option_symbol) ⇒ Boolean
Check whether an option has already been declared in this manager.
-
#option_def(option_symbol) ⇒ Option::Value
Get an option definition by name.
-
#parse_options! ⇒ Object
Apply values of options declared so far: from presets, env vars and command line.
-
#set_option(option_symbol, value, source: :code, warn_deprecation: true, final: false, configured: false) ⇒ Object
Set an option value by name: store value and call the
on_setcallback String is given to extended value. -
#unprocessed_options_with_value(after_command: false) ⇒ Hash
Get long options with a value from command line, used to generate a config in config file.
-
#unshift_next_argument(argument) ⇒ nil
Allows a plugin to add an argument as next argument to process.
-
#with_interactive(enabled: true) ⇒ Object
Execute the block with interactive input of missing mandatory options and arguments, as with
--interactive=yes.
Methods included from Prompt
#prompt_user_input, #prompt_user_input_in_list
Constructor Details
#initialize(program_name, argv = nil) ⇒ Parser
Returns a new instance of Parser.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/aspera/cli/parser.rb', line 120 def initialize(program_name, argv = nil) @registry = Option::Registry.new # 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 # get_option fails if a mandatory parameter is asked @fail_on_missing_mandatory = true # Values from presets and env vars, for options not declared yet: option symbol -> [{value:, source:}] @pending_values = {} # `true` when options were declared or presets added since last parse @parse_needed = true # options can also be provided by env vars : --param-name -> ASCLI_PARAM_NAME env_prefix = program_name.upcase + CommandLine::Option::NAME_SEP_SYMBOL ENV.each do |k, v| add_pending_value(k.delete_prefix(env_prefix).downcase.to_sym, v, :env, replace: true) if k.start_with?(env_prefix) end Log.dump(:env, @pending_values) @command_line = CommandLine.new(argv || []) declare(:interactive, description: 'Use interactive input of missing params', allowed: Option::Type::BOOLEAN, default: false, on_set: method(:ask_missing_mandatory=)) declare(:ask_options, description: 'Ask even optional options', allowed: Option::Type::BOOLEAN, default: false, on_set: method(:ask_missing_optional=)) end |
Instance Attribute Details
#ask_missing_mandatory ⇒ Object
Returns the value of attribute ask_missing_mandatory.
115 116 117 |
# File 'lib/aspera/cli/parser.rb', line 115 def ask_missing_mandatory @ask_missing_mandatory end |
#ask_missing_optional ⇒ Object
Returns the value of attribute ask_missing_optional.
115 116 117 |
# File 'lib/aspera/cli/parser.rb', line 115 def ask_missing_optional @ask_missing_optional end |
#fail_on_missing_mandatory=(value) ⇒ Object (writeonly)
Sets the attribute fail_on_missing_mandatory
116 117 118 |
# File 'lib/aspera/cli/parser.rb', line 116 def fail_on_missing_mandatory=(value) @fail_on_missing_mandatory = value end |
Class Method Details
.get_from_list(short_value, descr, allowed_values) ⇒ Symbol, Boolean
Find shortened string value in allowed symbol list
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/aspera/cli/parser.rb', line 44 def get_from_list(short_value, descr, allowed_values) Aspera.assert_type(short_value, String) # we accept shortcuts matching = allowed_values.select { |i| i.to_s.eql?(short_value) } matching = allowed_values.select { |i| i.to_s.start_with?(short_value) } unless matching.length.eql?(1) raise BadArgument, "Identifier '#{short_value}' used where a #{descr} is expected: place the identifier after the command" if matching.empty? && short_value.match?(REGEX_LOOKUP_ID_BY_FIELD) Aspera.assert(!matching.empty?, multi_choice_assert_msg("unknown value for #{descr}: #{short_value}", allowed_values), type: BadArgument) Aspera.assert(matching.length.eql?(1), multi_choice_assert_msg("ambiguous shortcut for #{descr}: #{short_value}", matching), type: BadArgument) return BoolValue.true?(matching.first) if allowed_values.eql?(BoolValue::ALL) matching.first end |
.multi_choice_assert_msg(error_msg, accept_list, aliases: nil) ⇒ Object
Generates error message with list of allowed values
60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/aspera/cli/parser.rb', line 60 def multi_choice_assert_msg(error_msg, accept_list, aliases: nil) # Build reverse map: id → [alias, ...] for annotation reverse = aliases&.each_with_object({}) do |(ali, id), h| (h[id] ||= []) << ali end lines = accept_list.map do |choice| suffix = reverse&.key?(choice) ? " (alias: #{reverse[choice].join(', ')})" : '' "- #{choice}#{suffix}" end [error_msg, 'Use:', *lines.sort].join("\n") end |
.option_line_to_name(name) ⇒ String
Change option name with dash to name with underscore
75 76 77 |
# File 'lib/aspera/cli/parser.rb', line 75 def option_line_to_name(name) name.gsub(CommandLine::Option::NAME_SEP_LINE, CommandLine::Option::NAME_SEP_SYMBOL) end |
.option_name_to_line(name) ⇒ String
Convert option symbol to CLI line flag format
82 83 84 |
# File 'lib/aspera/cli/parser.rb', line 82 def option_name_to_line(name) "#{CommandLine::Option::PREFIX}#{name.to_s.gsub(CommandLine::Option::NAME_SEP_SYMBOL, CommandLine::Option::NAME_SEP_LINE)}" end |
.percent_selector(identifier) ⇒ Hash{Symbol => String}?
Parse percent-selector string into field name and value (extended value is parsed in value)
89 90 91 92 93 94 95 |
# File 'lib/aspera/cli/parser.rb', line 89 def percent_selector(identifier) Aspera.assert_type(identifier, String) if (m = identifier.match(REGEX_LOOKUP_ID_BY_FIELD)) return {field: m[1], value: ExtendedValue.instance.evaluate(m[2], context: "percent selector: #{m[1]}")} end nil end |
.smart_convert(value, context: 'dotted expression', allowed: nil) ⇒ Boolean, ...
Using dotted hash notation, convert value to bool, int, float or extended value
true and yes are converted to true, false and no to false
103 104 105 106 107 108 109 110 111 112 |
# File 'lib/aspera/cli/parser.rb', line 103 def smart_convert(value, context: 'dotted expression', allowed: nil) case value when 'true', BoolValue::YES_SYM.to_s then true when 'false', BoolValue::NO_SYM.to_s then false else Integer(value, 10, exception: false) || Float(value, exception: false) || ExtendedValue.instance.evaluate(value, context: context, allowed: allowed) end end |
Instance Method Details
#add_option_preset(preset_hash, where, override: true, configured: false) ⇒ Object
Adds each of the keys of specified hash as an option. Values are applied by the next parse, and never override a value from env or command line.
369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/aspera/cli/parser.rb', line 369 def add_option_preset(preset_hash, where, override: true, configured: false) Aspera.assert_type(preset_hash, Hash) Log.log.debug { "add_option_preset: #{preset_hash}, #{where}, #{override}" } source = override ? :preset : :plugin_preset preset_hash.each do |k, v| # Ignore comment/meta keys (e.g. _comment, _description) next if k.to_s.start_with?(PresetManager::Key::META_PREFIX) add_pending_value(k.to_sym, v, source, replace: override, configured: configured) end @parse_needed = true end |
#args_as_extended(end_marker) ⇒ Hash, Array
Read remaining args and build an Array or Hash
When used in an option value, only positional arguments after the option are used.
519 520 521 522 523 524 525 526 527 528 529 530 |
# File 'lib/aspera/cli/parser.rb', line 519 def args_as_extended(end_marker) end_marker = SpecialValues::EOA if end_marker.empty? result = nil @command_line.with_arguments_after_current_option do get_next_argument('args', multiple: end_marker).each do |argument| Aspera.assert(argument.include?(CommandLine::Option::VALUE_SEP), type: BadArgument) { "Argument collected by @: does not include #{CommandLine::Option::VALUE_SEP}: #{argument} (end marker: #{end_marker})" } path, value = argument.split(CommandLine::Option::VALUE_SEP, 2) result = DotContainer.dotted_to_container(path.split(DotContainer::SEPARATOR), Parser.smart_convert(value), result) end end result end |
#check_credential_host(secret_symbol) ⇒ Object
When a credential is read while a host option url is declared, refuse (at levels medium and high) to send a secret of the server's configuration
to a url that is not in its configuration, e.g. chosen by a client.
329 330 331 332 333 334 335 336 337 338 339 340 |
# File 'lib/aspera/cli/parser.rb', line 329 def check_credential_host(secret_symbol) return unless option_declared?(:url) secret = option_def(secret_symbol) url = option_def(:url) Security.instance.check_credential_host( what: "option #{secret_symbol}", secret: secret.value, secret_source: secret.source, url: url.value, url_source: url.source ) end |
#clear_option(option_symbol) ⇒ nil
Set option to nil
357 358 359 360 |
# File 'lib/aspera/cli/parser.rb', line 357 def clear_option(option_symbol) Aspera.assert_type(option_symbol, Symbol) option_def(option_symbol).clear end |
#command_or_arg_empty? ⇒ Boolean
Check if there are no pending positional arguments
391 392 393 394 |
# File 'lib/aspera/cli/parser.rb', line 391 def command_or_arg_empty? ensure_parsed @command_line.pending_arguments.empty? end |
#declare(option_symbol, description: nil, short: nil, allowed: nil, default: nil, on_set: nil, shorthand: nil, convert: nil, deprecation: nil, schema: nil, complete: nil, security: nil, &block) ⇒ Object
Declare an option
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 |
# File 'lib/aspera/cli/parser.rb', line 163 def declare(option_symbol, description: nil, short: nil, allowed: nil, default: nil, on_set: nil, shorthand: nil, convert: nil, deprecation: nil, schema: nil, complete: nil, security: nil, &block) Aspera.assert_type(option_symbol, Symbol) Aspera.assert(!@registry.declared?(option_symbol)) { "#{option_symbol} already declared" } if on_set && allowed.eql?(Option::Type::NONE) Aspera.assert(block.nil?) { "#{option_symbol}: flag with both on_set and block" } block = on_set on_set = nil end # An abbreviation already used on command line must stay unambiguous @command_line.abbreviated_option_tokens.each do |tok| Aspera.assert(!option_symbol.to_s.start_with?(tok.name), type: BadArgument) do "Ambiguous option #{tok.raw}: used as #{self.class.option_name_to_line(tok.abbreviation_of)}, but also matches #{self.class.option_name_to_line(option_symbol)}" end end option = @registry.add( Option::Value.new( option: option_symbol, description: description, allowed: allowed, on_set: on_set, shorthand: shorthand, convert: convert, deprecation: deprecation, schema: schema, complete: complete, security: security ), short: short ) description = option.description Aspera.assert(!description.nil?) { "#{option_symbol}: no description and no schema to derive one from" } Aspera.assert(description[-1] != '.') { "#{option_symbol} ends with dot" } Aspera.assert(description[0] == description[0].upcase) { "#{option_symbol} description does not start with an uppercase" } Aspera.assert(!['hash', 'extended value'].any? { |s| description.downcase.include?(s) }) { "#{option_symbol} shall use :allowed instead of hash/extended value in option description" } set_option(option_symbol, default, source: :default, warn_deprecation: false) unless default.nil? if option.flag? Aspera.assert(block.respond_to?(:call)) { "missing execution block for #{option_symbol}" } option.block = block end @parse_needed = true Log.log.trace1 { "declare: #{option_symbol}, group: #{option.group}, short: #{short}" } end |
#declared_options ⇒ Hash{Symbol => Option::Value}
Returns all declared options (read-only view).
283 |
# File 'lib/aspera/cli/parser.rb', line 283 def = @registry. |
#final_errors(after_error: false) ⇒ Array<String>
Check for unprocessed options or arguments error messages
415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/aspera/cli/parser.rb', line 415 def final_errors(after_error: false) begin ensure_parsed rescue StandardError => e # already in error processing: report only unprocessed tokens Log.log.debug { "final parse: #{e}" } end result = [] result.push("unprocessed options: #{@command_line.}") unless @command_line..empty? result.push("unprocessed values: #{@command_line.pending_arguments}") unless after_error || @command_line.pending_arguments.empty? result end |
#get_interactive(descr, multiple: false, accept_list: nil, aliases: nil, schema: nil) ⇒ String
Prompt user for missing option or argument, or raise if not interactive
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 |
# File 'lib/aspera/cli/parser.rb', line 490 def get_interactive(descr, multiple: false, accept_list: nil, aliases: nil, schema: nil) option = @registry.[descr.to_sym] default_prompt = "#{option ? 'option' : 'argument'}: #{descr}" if !@ask_missing_mandatory = "Missing #{default_prompt}" = self.class.multi_choice_assert_msg(, accept_list, aliases: aliases) if accept_list += "\n#{TerminalFormatter.hint}Give `#{SchemaRequest::KEYWORD}` as argument to retrieve the schema of the missing argument." if schema raise Cli::MissingArgument, end # Ask interactively result = [] $stderr.puts(' (one per line, end with empty line)') if multiple # rubocop:disable Style/StderrPuts loop do prompt = default_prompt prompt = "#{accept_list.join(' ')}\n#{default_prompt}" if accept_list entry = prompt_user_input(prompt, sensitive: option&.sensitive) break if entry.empty? && multiple entry = ExtendedValue.instance.evaluate(entry, context: 'interactive input') entry = self.class.get_from_list(entry, descr, accept_list) if accept_list return entry unless multiple result.push(entry) end result end |
#get_next_argument(descr, mandatory: true, multiple: false, accept_list: nil, validation: Option::Type::STRING, aliases: nil, default: nil, schema: nil, evaluate: :extended) ⇒ Object, ...
Low-level positional argument reader.
Prefer Base#resolve_argument from action methods.
The only direct call from outside Cli::Parser and Cli::Plugins::Base is to retrieve the list of files.
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/aspera/cli/parser.rb', line 224 def get_next_argument(descr, mandatory: true, multiple: false, accept_list: nil, validation: Option::Type::STRING, aliases: nil, default: nil, schema: nil, evaluate: :extended) ensure_parsed Aspera.assert_array_all(accept_list, Symbol) unless accept_list.nil? Aspera.assert_hash_all(aliases, Symbol, Symbol) unless aliases.nil? validation = Symbol unless accept_list.nil? validation = [validation] unless validation.is_a?(Array) || validation.nil? Aspera.assert_array_all(validation, Class) { 'validation' } unless validation.nil? descr = "#{descr}#{add_types_info(validation)}" result = if !@command_line.pending_arguments.empty? then read_arguments(descr, multiple: multiple, validation: validation, accept_list: accept_list, aliases: aliases, evaluate: evaluate) elsif !default.nil? then default elsif mandatory then get_interactive(descr, multiple: multiple, accept_list: accept_list, aliases: aliases, schema: schema) end Log.log.trace1 { "#{descr}=#{result}" } result = aliases[result] if aliases&.key?(result) result = convert_argument(result, validation) (multiple ? result : [result]).each { |value| validate_argument(value, validation: validation, descr: descr, schema: schema) } if validation && (mandatory || !result.nil?) result end |
#get_next_command(command_list, aliases: nil) ⇒ Symbol
Get next positional command argument from accepted list
269 270 271 272 273 |
# File 'lib/aspera/cli/parser.rb', line 269 def get_next_command(command_list, aliases: nil) command = get_next_argument('command', accept_list: command_list, aliases: aliases) @command_line.mark_command command end |
#get_option(option_symbol, mandatory: false, schema: nil, complete: false) ⇒ Object
Get an option value by name, can return nil ask interactively if requested/required
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/aspera/cli/parser.rb', line 300 def get_option(option_symbol, mandatory: false, schema: nil, complete: false) Aspera.assert_type(option_symbol, Symbol) ensure_parsed option = option_def(option_symbol) result = option.value # Contextual schema: raise SchemaRequest when value is 'help' raise SchemaRequest.new(:option, option_symbol.to_s, schema) if schema && result.eql?(SchemaRequest::KEYWORD) # Do not fail for manual generation if option mandatory but not set return :skip_missing_mandatory if result.nil? && mandatory && !@fail_on_missing_mandatory if result.nil? if !@ask_missing_mandatory Aspera.assert(!mandatory, type: Cli::BadArgument) { "Missing mandatory option: #{option_symbol}" } elsif @ask_missing_optional || mandatory result = get_interactive(option_symbol.to_s, accept_list: option.values, schema: option.schema) set_option(option_symbol, result, source: :interactive) end end option.validate_complete(result) if complete check_credential_host(option_symbol) if !result.nil? && CREDENTIAL_OPTIONS.include?(option_symbol) Security.instance.check_credentials_in(result, what: "option #{option_symbol}") result end |
#group(name) ⇒ Object
Set the current help section group name for subsequent declarations
208 209 210 |
# File 'lib/aspera/cli/parser.rb', line 208 def group(name) @registry.group = name end |
#help_text(banner: nil) ⇒ String
Generate help text for all declared options, grouped by section.
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
# File 'lib/aspera/cli/parser.rb', line 535 def help_text(banner: nil) rows = [] current_group = nil @registry..each do |sym, opt| if opt.group != current_group current_group = opt.group rows << [{value: "OPTIONS: #{current_group}", colspan: 2}] end short_part = opt.short ? "-#{opt.short}, " : ' ' flag = "#{short_part}#{symbol_to_option(sym, option_display_value(opt))}" desc = opt.deprecation ? "#{opt.description} (#{opt.deprecation})" : opt.description rows << [flag, desc] end table = Terminal::Table.new(rows: rows, style: {border: HELP_BORDER, padding_left: 0, padding_right: 2}) .nil? ? table.to_s : "#{}\n#{table}" end |
#instance_identifier(description: 'identifier', multiple: false, mandatory: true, default: nil, &block) {|field, value| ... } ⇒ String+
Resource identifier as positional parameter
255 256 257 258 259 260 261 262 263 |
# File 'lib/aspera/cli/parser.rb', line 255 def instance_identifier(description: 'identifier', multiple: false, mandatory: true, default: nil, &block) res_id = get_next_argument(description, multiple: multiple, mandatory: mandatory, default: default) # Can be an Array if res_id.is_a?(String) && (m = Parser.percent_selector(res_id)) Aspera.assert(block_given?, type: Cli::BadArgument) { "Percent syntax for #{description} not supported in this context" } res_id = yield(m[:field], m[:value]) end res_id end |
#known_options(only_defined: false) ⇒ Hash
Returns options as taken from config file and command line just before command execution.
446 447 448 449 450 451 452 453 454 455 |
# File 'lib/aspera/cli/parser.rb', line 446 def (only_defined: false) result = {} @registry..each_key do |option_symbol| v = get_option(option_symbol) result[option_symbol] = v unless only_defined && v.nil? rescue => e result[option_symbol] = e.to_s end result end |
#next_argument_in?(values) ⇒ Boolean
Check the next pending positional argument, without consuming it
399 400 401 402 |
# File 'lib/aspera/cli/parser.rb', line 399 def next_argument_in?(values) ensure_parsed values.include?(@command_line.pending_arguments.first) end |
#next_arguments?(values) ⇒ Boolean
Check the next pending positional arguments, without consuming them
407 408 409 410 |
# File 'lib/aspera/cli/parser.rb', line 407 def next_arguments?(values) ensure_parsed @command_line.pending_arguments.first(values.length).eql?(values) end |
#option_declared?(option_symbol) ⇒ Boolean
Check whether an option has already been declared in this manager
278 279 280 |
# File 'lib/aspera/cli/parser.rb', line 278 def option_declared?(option_symbol) @registry.declared?(option_symbol) end |
#option_def(option_symbol) ⇒ Option::Value
Get an option definition by name
289 290 291 |
# File 'lib/aspera/cli/parser.rb', line 289 def option_def(option_symbol) @registry.fetch(option_symbol) end |
#parse_options! ⇒ Object
Apply values of options declared so far: from presets, env vars and command line.
Can be called any number of times: tokens of options not declared yet are kept for a later call.
Called automatically on read of option or argument, but must be called explicitly
when values set by on_set callbacks are used.
461 462 463 464 465 466 467 468 469 |
# File 'lib/aspera/cli/parser.rb', line 461 def Log.log.trace1('parse_options!'.red) @parse_needed = false apply_pending_values @command_line.pending_option_tokens.each { |tok| apply_option_token(tok) } # Presets loaded by a command line option (e.g. `-P`) apply_pending_values Log.log.trace1 { "unprocessed options: #{@command_line.}" } end |
#set_option(option_symbol, value, source: :code, warn_deprecation: true, final: false, configured: false) ⇒ Object
Set an option value by name: store value and call the on_set callback
String is given to extended value
349 350 351 352 |
# File 'lib/aspera/cli/parser.rb', line 349 def set_option(option_symbol, value, source: :code, warn_deprecation: true, final: false, configured: false) Aspera.assert_type(option_symbol, Symbol) option_def(option_symbol).assign_value(value, source: source, warn_deprecation: warn_deprecation, final: final, configured: configured) end |
#unprocessed_options_with_value(after_command: false) ⇒ Hash
Get long options with a value from command line, used to generate a config in config file. They are marked as processed.
432 433 434 435 436 437 438 439 440 441 442 |
# File 'lib/aspera/cli/parser.rb', line 432 def (after_command: false) ensure_parsed result = {} @command_line.each_long_option_with_value(after_command: after_command) do |tok| path = [tok.name, *tok.dot_path] declare_secrets(path.last, tok.value) Log.log.debug { "option #{path.join(DotContainer::SEPARATOR)}=#{Secret::Hider.instance.hidden_copy(tok.value)}" } DotContainer.dotted_to_container(path, Parser.smart_convert(tok.value), result) end result end |
#unshift_next_argument(argument) ⇒ nil
Allows a plugin to add an argument as next argument to process
384 385 386 387 |
# File 'lib/aspera/cli/parser.rb', line 384 def unshift_next_argument(argument) @command_line.unshift_argument(argument) nil end |
#with_interactive(enabled: true) ⇒ Object
Execute the block with interactive input of missing mandatory options and arguments, as with --interactive=yes.
The previous state is restored afterwards, so that interactive input does not leak to the rest of the command.
475 476 477 478 479 480 481 |
# File 'lib/aspera/cli/parser.rb', line 475 def with_interactive(enabled: true) previous = @ask_missing_mandatory @ask_missing_mandatory = true if enabled yield ensure @ask_missing_mandatory = previous end |