Class: Aspera::Cli::Parser

Inherits:
Object
  • Object
show all
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, see Security#check_credential_host

%i[password client_secret private_key passphrase].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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.

Parameters:

  • program_name (String) —

    Name of the program

  • argv (Array<String>, nil) (defaults to: nil) —

    Command line arguments to parse



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

Parameters:

  • value —

    the value to set the attribute fail_on_missing_mandatory to.



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

Parameters:

  • short_value (String) —

    Value or prefix to find

  • descr (String) —

    Description for error messages

  • allowed_values (Array) —

    List of allowed values

Returns:

  • (Symbol, Boolean) —

    matched symbol or boolean value

Raises:



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

Parameters:

  • error_msg (String) —

    Error message

  • accept_list (Array<Symbol>) —

    List of allowed values

  • aliases (Hash{Symbol=>Symbol}, nil) (defaults to: nil) —

    alias→id map; used to annotate entries with their aliases



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

Parameters:

  • name (String) —

    option name with dash separators

Returns:

  • (String) —

    option name with underscore separators



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

Parameters:

  • name (Symbol, String) —

    option name

Returns:

  • (String) —

    option flag (e.g. "--option-name")



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)

Parameters:

  • identifier (String) —

    identifier to parse

Returns:

  • (Hash{Symbol => String}, nil) —

    {field:,value:} if identifier is a percent selector, else nil



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

Parameters:

  • value (String) —

    The value to convert to appropriate type

  • context (String) (defaults to: 'dotted expression') —

    Where the value comes from, for error messages

  • allowed (Class, Array, nil) (defaults to: nil) —

    Types accepted for an extended value

Returns:

  • (Boolean, Integer, Float, String, Array, Hash) —

    the converted value



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.

Parameters:

  • preset_hash (Hash) —

    Options to add

  • where (String) —

    Where the value comes from (for logs)

  • override (Boolean) (defaults to: true) —

    false for plugin default presets: lower priority than other presets

  • configured (Boolean) (defaults to: false) —

    true: preset read from the configuration (by its name), its values are the ones of the operator, as a client cannot change the configuration at levels medium and high: not restricted by the security level. false: e.g. a Hash given by the client



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.

Parameters:

  • end_marker (String) —

    Argument to @: extended value

Returns:

  • (Hash, Array) —

    Object representing dot-path values



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.

Parameters:

  • secret_symbol (Symbol) —

    the credential option being read



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

Parameters:

  • option_symbol (Symbol) —

    option name

Returns:

  • (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

Returns:

  • (Boolean) —

    true if 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

Parameters:

  • option_symbol (Symbol) —

    option name

  • description (String, nil) (defaults to: nil) —

    description for help; if nil, derived from schema

  • short (String) (defaults to: nil) —

    short option name

  • allowed (Object) (defaults to: nil) —

    Allowed values, see Option::Value. When schema: is provided:

    • Omit allowed: when the schema has a single type (type: object/array): it is inferred automatically.
    • Omit allowed: when the schema uses oneOf/anyOf and all branches are object: Hash is inferred.
    • Use allowed: [Hash, String] when the option additionally accepts a plain String shorthand; the schema then documents the Hash form and =help still shows it.
  • default (Object) (defaults to: nil) —

    default value

  • on_set (#call) (defaults to: nil) —

    Called with the new value each time the value is set (e.g. a Method, or a lambda). For a flag (Option::Type::NONE): called without argument when the flag is found

  • shorthand (String) (defaults to: nil) —

    For a Hash option: a String value is stored as {shorthand => value}

  • convert (#call) (defaults to: nil) —

    For a Hash option: called with a new Hash value, returns the value to store, before merge (e.g. conversion of a deprecated form)

  • deprecation (Hash, nil) (defaults to: nil) —

    deprecation: {last:, message:}, see Deprecation

  • schema (String) (defaults to: nil) —

    schema path documenting the Hash form of this option

  • complete (Symbol, nil) (defaults to: nil) —

    values proposed by shell completion, one of Complete::KINDS

  • security (Symbol, nil) (defaults to: nil) —

    most restrictive security level at which the option is available, see Security

  • block (Proc) —

    Block to execute when option is found



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).

Returns:



283
# File 'lib/aspera/cli/parser.rb', line 283

def declared_options = @registry.options

#final_errors(after_error: false) ⇒ Array<String>

Check for unprocessed options or arguments error messages

Parameters:

  • after_error (Boolean) (defaults to: false) —

    true if an error was already reported: positional arguments are then not consumed because of this error, not reported

Returns:

  • (Array<String>) —

    list of error messages for unprocessed tokens



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.pending_options}") unless @command_line.pending_options.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

Parameters:

  • descr (String) —

    option name, or argument description

  • multiple (Boolean, String) (defaults to: false) —

    true if multiple values expected

  • accept_list (Array<Symbol>, nil) (defaults to: nil) —

    List of expected values

  • aliases (Hash, nil) (defaults to: nil) —

    aliases of values, for error message

  • schema (String, nil) (defaults to: nil) —

    schema of value, for error message

Returns:



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.options[descr.to_sym]
  default_prompt = "#{option ? 'option' : 'argument'}: #{descr}"
  if !@ask_missing_mandatory
    message = "Missing #{default_prompt}"
    message = self.class.multi_choice_assert_msg(message, accept_list, aliases: aliases) if accept_list
    message += "\n#{TerminalFormatter.hint}Give `#{SchemaRequest::KEYWORD}` as argument to retrieve the schema of the missing argument." if schema
    raise Cli::MissingArgument, message
  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.

Parameters:

  • descr (String) —

    Description for help

  • mandatory (Boolean) (defaults to: true) —

    true: raise error no more argument

  • multiple (Boolean) (defaults to: false) —

    true: return all remaining arguments (Array). String: until marker

  • accept_list (Array<Symbol>, nil) (defaults to: nil) —

    list of allowed values

  • validation (Class, Array, nil) (defaults to: Option::Type::STRING) —

    Accepted value type(s) or list of Symbols

  • aliases (Hash) (defaults to: nil) —

    map of aliases: key = alias, value = real value

  • default (Object) (defaults to: nil) —

    default value

  • evaluate (Symbol) (defaults to: :extended) —

    :extended: extended value, :smart: also true, yes, false, no and numbers, :none: as typed

Returns:

  • (Object, Array, nil) —

    one value, list or nil (if optional and no default)



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

Parameters:

  • command_list (Array<Symbol>) —

    accepted command names

  • aliases (Hash, nil) (defaults to: nil) —

    command aliases

Returns:

  • (Symbol) —

    selected command



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

Parameters:

  • option_symbol (Symbol) —

    name of the option to retrieve

  • mandatory (Boolean) (defaults to: false) —

    if true, raise error if option not set

  • schema (String, nil) (defaults to: nil) —

    contextual schema path override; when set, raises SchemaRequest if the option value is 'help' (used for --query whose schema depends on the current command)

  • complete (Boolean) (defaults to: false) —

    true: the value is used as is (no other source completes it): checked against the schema of the option, with its required properties

Raises:



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

Parameters:

  • name (String) —

    group name, shown as section header in help text



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.

Parameters:

  • banner (String, nil) (defaults to: nil) —

    Optional banner text to prepend

Returns:

  • (String) —

    Formatted help text



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.options.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})
  banner.nil? ? table.to_s : "#{banner}\n#{table}"
end

#instance_identifier(description: 'identifier', multiple: false, mandatory: true, default: nil, &block) {|field, value| ... } ⇒ String+

Resource identifier as positional parameter

Parameters:

  • description (String) (defaults to: 'identifier') —

    description of the identifier

  • multiple (Boolean) (defaults to: false) —

    true: read a list of IDs (bulk operation)

  • mandatory (Boolean) (defaults to: true) —

    false: the identifier may be absent, then default is returned

  • default (Object) (defaults to: nil) —

    value when the identifier is absent and not mandatory

  • block (Proc) —

    block to search for identifier based on attribute value

Yield Parameters:

  • field (String) —

    The field name from percent selector

  • value (String) —

    The value from percent selector

Yield Returns:

  • (String) —

    Resolved identifier

Returns:

  • (String, Array<String>) —

    identifier or list of IDs (if multiple)



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.

Parameters:

  • only_defined (Boolean) (defaults to: false) —

    if true, only return options that were defined

Returns:

  • (Hash) —

    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 known_options(only_defined: false)
  result = {}
  @registry.options.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

Parameters:

  • values (Array<String>) —

    values to compare with

Returns:

  • (Boolean) —

    true if the next pending positional argument is one of values



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

Parameters:

  • values (Array<String>) —

    values to compare with, in order

Returns:

  • (Boolean) —

    true if the next pending positional arguments are values



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

Parameters:

  • option_symbol (Symbol) —

    name of the option

Returns:

  • (Boolean)


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

Parameters:

  • option_symbol (Symbol) —

    name of the option

Returns:

Raises:



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 parse_options!
  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.pending_options}" }
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

Parameters:

  • option_symbol (Symbol) —

    option name

  • value (String) —

    Value to set

  • source (Symbol) (defaults to: :code) —

    Option::Source of value

  • final (Boolean) (defaults to: false) —

    Value is final: values from a lower source (preset, environment) are ignored

  • configured (Boolean) (defaults to: false) —

    Value of a preset read from the configuration, see #add_option_preset



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.

Parameters:

  • after_command (Boolean) (defaults to: false) —

    true: only options placed after the last command word

Returns:

  • (Hash) —

    options with value, dotted notation expanded



432
433
434
435
436
437
438
439
440
441
442
# File 'lib/aspera/cli/parser.rb', line 432

def unprocessed_options_with_value(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

Parameters:

  • argument (String) —

    argument value to prepend

Returns:

  • (nil)


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.

Parameters:

  • enabled (Boolean) (defaults to: true) —

    false: execute the block with current state

Returns:

  • (Object) —

    result of the block



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