Class: Aspera::Cli::Plugins::Config

Inherits:
Base
  • Object
show all
Includes:
CompletionActions, GemChecker, Aspera::Cli::PresetActions, VaultActions
Defined in:
lib/aspera/cli/plugins/config.rb

Overview

Manage the CLI config file

Constant Summary collapse

DEPRECATED_LAST =

Last released version with config transferd, config ascp install and config transfer not deprecated

'4.28.0'

Constants included from Aspera::Cli::PresetActions

Aspera::Cli::PresetActions::CONF_OVERVIEW_KEYS, Aspera::Cli::PresetActions::GLOBAL_DEFAULT_KEYWORD, Aspera::Cli::PresetActions::LOOKUP_KEYS, Aspera::Cli::PresetActions::NOT_GIVEN, Aspera::Cli::PresetActions::PRESET_DEPRECATED_LAST

Constants included from GemChecker

GemChecker::GEM_CHECK_DATE_FMT

Constants inherited from Base

Base::FILTER_ARGS

Instance Attribute Summary collapse

Attributes inherited from Base

#context, #help_path

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CompletionActions

#action_completion_candidates, #action_completion_words

Methods included from Aspera::Cli::PresetActions

#action_preset_ask, #action_preset_delete, #action_preset_get, #action_preset_initialize, #action_preset_lookup, #action_preset_overview, #action_preset_secure, #action_preset_set, #action_preset_show, #action_preset_unset, #action_preset_update

Methods included from GemChecker

#check_gem_version, #periodic_check_newer_gem_version

Methods included from VaultActions

#action_vault_check, #action_vault_delete, #action_vault_import, #vault, #vault_required

Methods inherited from Base

#action_for, application_name, #bulk_result, #check_argument_access, command, command_registry, commands_under, #config, #crud_api, crud_commands, declare_options, define_action_method, #dispatch_child, #dispatch_from_registry, #dispatch_leaf, #dispatch_mount, #entity_create, #entity_delete, #entity_list, #entity_modify, entity_noun, #entity_res_path, #entity_show, #execute_action, #execute_leaf, file_matcher, #formatter, #generate_help, #http_config, include_mounts, #invoke_action, operation_description, option_sources, option_specs, #options, #persistency, #poll_result, #presets, #progress_bar, #query_read_delete, register_option_spec, #resolve_argument, #resolve_arguments, #transfer, use_options, used_option_sources, #validate_registry

Methods included from Option::Declarator

#declare_options, #option, #option_specs, #register_option_spec

Constructor Details

#initialize(**_) ⇒ Config

Returns a new instance of Config.



84
85
86
87
88
89
90
91
92
# File 'lib/aspera/cli/plugins/config.rb', line 84

def initialize(**_)
  super
  @sdk_default_location = false
  @wizard = Wizard.new(self, context.main_folder)
  # Values set through `on_set` callbacks are used below (sdk_folder)
  options.parse_options!
  # Method of the module `AscpActions` mounted by bundle `xfer`: config still works if this mount failed (see `include_mounts`)
  set_sdk_dir if respond_to?(:set_sdk_dir)
end

Instance Attribute Details

#gem_url ⇒ Object (readonly)

Returns the value of attribute gem_url.



399
400
401
# File 'lib/aspera/cli/plugins/config.rb', line 399

def gem_url
  @gem_url
end

Class Method Details

.default_app_main_folder(app_name:) ⇒ String

Returns Product config folder (~/.aspera/).

Returns:

  • (String) —

    Product config folder (~/.aspera/)



72
73
74
75
76
# File 'lib/aspera/cli/plugins/config.rb', line 72

def default_app_main_folder(app_name:)
  Aspera.assert_type(app_name, String)
  Aspera.assert(!app_name.empty?, 'app_name must not be empty')
  return File.join(module_family_folder, app_name)
end

.gem_plugins_folder ⇒ Object

Folder containing plugins in the gem's main folder



53
54
55
# File 'lib/aspera/cli/plugins/config.rb', line 53

def gem_plugins_folder
  File.dirname(File.expand_path(__FILE__))
end

.gem_src_root ⇒ String

Go up as many times as englobing modules (not counting class, as it is a file)

Returns:

  • (String) —

    main folder where code is, i.e. .../lib



59
60
61
62
# File 'lib/aspera/cli/plugins/config.rb', line 59

def gem_src_root
  # Module.nesting[2] is Cli::Plugins
  File.expand_path(Module.nesting[2].to_s.gsub('::', '/').gsub(%r{[^/]+}, '..'), gem_plugins_folder)
end

.module_family_folder ⇒ String

Returns product family folder (~/.aspera).

Returns:

  • (String) —

    product family folder (~/.aspera)



65
66
67
68
69
# File 'lib/aspera/cli/plugins/config.rb', line 65

def module_family_folder
  user_home_folder = Dir.home
  Aspera.assert(Dir.exist?(user_home_folder), type: Cli::Error) { "Home folder does not exist: #{user_home_folder}. Check your user environment." }
  return File.join(user_home_folder, ASPERA_HOME_FOLDER_NAME)
end

Instance Method Details

#action_commands(plugin_name: nil, command_path: nil) ⇒ Object



590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/aspera/cli/plugins/config.rb', line 590

def action_commands(plugin_name: nil, command_path: nil, **)
  plugin_names = Plugins::Factory.instance.plugin_list
  unless plugin_name.nil?
    Aspera.assert_values(plugin_name.to_sym, plugin_names, type: Cli::BadArgument)
    plugin_names = [plugin_name.to_sym]
  end
  words = Array(command_path).map(&:to_sym)
  Aspera.assert(words.empty? || plugin_names.length.eql?(1), type: Cli::BadArgument) { 'command path requires a plugin name' }
  expand_mounts = options.get_option(:expand_mounts)
  commands = plugin_names.flat_map do |name|
    begin
      reg = Plugins::Factory.instance.plugin_class(name).command_registry
    rescue Cli::Error => e
      # Named plugin: the error; else the plugin is left out
      raise if plugin_name
      Log.log.warn(e.message)
      next []
    end
    prefix = listed_command_path(name, reg, words)
    paths = prefix.empty? || reg.children_of(prefix).any? ? reg.leaf_paths(prefix, expand_mounts: expand_mounts) : [prefix]
    # Commands refused by security level are not proposed
    paths = paths.select { |path| path.each_index.all? { |i| Security.instance.allowed?(reg[path[0, i + 1]]&.security) } }
    paths.map do |path|
      mount = expand_mounts ? nil : reg.mount_at(path)
      description = reg[path]&.description.to_s
      if mount
        target = mount.plugin.plugin_name
        description = "#{description} (see: #{command_syntax(target, mount.registry, mount.at)})"
      end
      {
        syntax:      command_syntax(name, reg, path) + (mount ? ' <command...>' : ''),
        description: description
      }
    end
  end
  Result::ObjectList.new(commands, fields: %w[syntax description])
end

#action_documentation(location: :github, section: nil) ⇒ Object



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
# File 'lib/aspera/cli/plugins/config.rb', line 436

def action_documentation(location: :github, section: nil, **)
  case location
  when :github
    section = "##{section}" unless section.nil?
    Environment.instance.open_uri("#{Info::DOC_URL}#{section}")
    return Result::Nothing.new
  when :toc, :local
    require_relative '../../markdown'
    local_doc = File.join(self.class.gem_src_root, '..', 'docs', 'README.md')
    Aspera.assert(File.exist?(local_doc), type: Cli::Error) { "Local documentation not found: #{local_doc}" }
    content = File.read(local_doc)
    if location == :toc
      entries = Markdown.toc(content)
      return Result::ObjectList.new(entries, fields: %w[level title anchor])
    end
    # :local
    if section
      text = Markdown.extract_section(content, section)
      Aspera.assert(!text.nil?, type: Cli::Error) { "Section not found: #{section}" }
      return Result::Text.new(text)
    end
    if Environment.instance.url_method.eql?(:graphical)
      Environment.instance.open_uri("file://#{local_doc}")
      return Result::Nothing.new
    end
    return Result::Text.new(content)
  end
end

#action_download(file_url:, file_dest: nil) ⇒ Object



497
498
499
500
501
502
503
504
505
# File 'lib/aspera/cli/plugins/config.rb', line 497

def action_download(file_url:, file_dest: nil, **)
  file_url = file_url.chomp
  # Default: destination folder of downloads of the service `transfer` (option `to_folder`)
  file_dest = File.join(transfer.destination_folder(:receive), file_url.rpartition('/').last) if file_dest.nil?
  file_dest = Security.instance.writable_path(file_dest)
  Log.log.info("Downloading: #{file_url}")
  Rest::Client.new(base_url: file_url).call(operation: 'GET', save_to: file_dest)
  Result::Status.new("Saved to: #{file_dest}")
end

#action_initdemo ⇒ Object



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/aspera/cli/plugins/config.rb', line 564

def action_initdemo(**)
  cp = presets.config_presets
  if cp.key?(DEMO_PRESET)
    Log.log.warn { "Demo server preset already present: #{DEMO_PRESET}" }
  else
    Log.log.info { "Creating Demo server preset: #{DEMO_PRESET}" }
    cp[DEMO_PRESET] = {
      'url'                                    => "ssh://#{DEMO_SERVER}.asperasoft.com:33001",
      'username'                               => ASPERA,
      'ssAP'.downcase.reverse + 'drow'.reverse => DEMO_SERVER + ASPERA,
      # The demo server offers only host key `ssh-rsa` (SHA-1), not enabled by default in `Net::SSH` (browse, delete...)
      'ssh_options'                            => {'host_key' => DEMO_SERVER_HOST_KEYS}
    }
  end
  cp[PresetManager::Key::DEFAULTS] ||= {}
  if cp[PresetManager::Key::DEFAULTS].key?(SERVER_COMMAND)
    Log.log.warn { "Server default preset already set to: #{cp[PresetManager::Key::DEFAULTS][SERVER_COMMAND]}" }
    Log.log.warn { "Use #{DEMO_PRESET} for demo: -P#{DEMO_PRESET}" } unless
      DEMO_PRESET.eql?(cp[PresetManager::Key::DEFAULTS][SERVER_COMMAND])
  else
    cp[PresetManager::Key::DEFAULTS][SERVER_COMMAND] = DEMO_PRESET
    Log.log.info { "Setting server default preset to : #{DEMO_PRESET}" }
  end
  Result::Status.new('Done')
end

#action_options(plugin_name:) ⇒ Object



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/aspera/cli/plugins/config.rb', line 655

def action_options(plugin_name:, **)
  # Instantiate the plugin so that it registers all its options in context.options
  Plugins::Factory.instance.create(plugin_name.to_sym, context: context)
  rows = context.options.declared_options.map do |sym, opt|
    row = {
      'option'      => "--#{sym.to_s.tr('_', '-')}",
      'description' => opt.description.to_s
    }
    row['allowed']     = opt.allowed_info unless opt.allowed_info.nil?
    row['deprecated']  = opt.deprecation.last if opt.deprecation
    row['replacement'] = opt.deprecation.message if opt.deprecation
    row
  end
  Result::ObjectList.new(rows, fields: %w[option description allowed deprecated replacement])
end

#action_plugins_create(name:, folder: nil) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/aspera/cli/plugins/config.rb', line 542

def action_plugins_create(name:, folder: nil, **)
  plugin_name = name.downcase
  # The name is inserted in Ruby code and in a file name
  Aspera.assert(plugin_name.match?(/\A[a-z][a-z0-9_]*\z/), type: BadArgument) { "plugin name must be lowercase letters, digits and underscores: #{name}" }
  destination_folder = folder || File.join(context.main_folder, ASPERA_PLUGINS_FOLDERNAME)
  plugin_file = File.join(destination_folder, "#{plugin_name}.rb")
  content = <<~END_OF_PLUGIN_CODE
    require 'aspera/cli/plugins/base'
    module Aspera
      module Cli
        module Plugins
          class #{plugin_name.snake_to_capital} < Base
            command :example, description: 'example command', action: ->(**) { Result::Status.new('You called plugin #{plugin_name}') }
          end
        end
      end
    end
  END_OF_PLUGIN_CODE
  File.write(plugin_file, content)
  Result::Status.new("Created #{plugin_file}")
end

#action_plugins_list ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/aspera/cli/plugins/config.rb', line 513

def action_plugins_list(**)
  factory = Plugins::Factory.instance
  result = factory.listed_plugins.map do |name|
    status = factory.status(name)
    loaded =
      if status.eql?('available')
        begin
          factory.plugin_class(name)
        rescue Cli::Error => e
          # Broken code: the reason replaces the status
          status = e.message
          nil
        end
      end
    {
      plugin: name,
      detect: loaded.nil? ? nil : TerminalFormatter.tick(loaded.respond_to?(:detect)),
      wizard: loaded.nil? ? nil : TerminalFormatter.tick(loaded.method_defined?(:wizard)),
      status: status,
      path:   factory.registry[name].path
    }
  end
  Result::ObjectList.new(result, fields: %w[plugin detect wizard status path])
end

#action_plugins_show(name:) ⇒ Object



538
539
540
# File 'lib/aspera/cli/plugins/config.rb', line 538

def action_plugins_show(name:, **)
  Result::SingleObject.new(Plugins::Factory.instance.describe(name.to_sym))
end

#action_tokens_show(token_id:) ⇒ Object



507
508
509
510
511
# File 'lib/aspera/cli/plugins/config.rb', line 507

def action_tokens_show(token_id:, **)
  data = OAuth::Factory.instance.get_token_info(token_id)
  Aspera.assert(!data.nil?, type: Cli::Error) { 'Unknown identifier' }
  Result::SingleObject.new(data)
end

#action_web_login(code:) ⇒ Object

Web login for ascli that runs on another host, started with --ui.web_auth=paste. The code comes from another host, or from a message: the host of the login page is confirmed by the user the first time.

Parameters:

  • code (String) —

    Code of type login, given by the remote ascli



468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/aspera/cli/plugins/config.rb', line 468

def (code:, **)
  data = SealedHash.unseal(code, base_key: Cli::Info::CMD_NAME)
  raise BadArgument, 'This code is for ascli that waits for the login: run this command with the code that ascli gives' unless data.is_a?(Hash) && data.key?('login_url')
   = WebAuth::Relay.parse(data)
  (.host)
  Log.log.debug { "Redirection to #{.redirect_uri}" }
  WebAuth::Relay.run()
  Result::Status.new('Login done: paste the code shown by the browser in the terminal of ascli that waits for it')
rescue ParameterError => e
  raise BadArgument, e.message
rescue Errno::EADDRINUSE
  raise Cli::Error, "Cannot listen on #{.redirect_uri}: the port is used. The URL is registered for the login, it cannot be changed: free the port, and retry."
end

#add_plugin_lookup_folders ⇒ nil

Add the folders of option plugin_folder to the plugin lookup: DEF is the folder plugins of the configuration folder. Called once options are final, before plugins are looked up: the last folder has priority.

Returns:

  • (nil)


404
405
406
407
408
409
410
411
412
# File 'lib/aspera/cli/plugins/config.rb', line 404

def add_plugin_lookup_folders
  home_plugins = File.join(context.main_folder, ASPERA_PLUGINS_FOLDERNAME)
  folders = options.get_option(:plugin_folder)
  # Before 4.30, this folder was always used: plugins there would silently stop working
  unused_home = !folders.include?(SpecialValues::DEF) && Dir.glob(["*#{Environment::RB_EXT}", "*/#{BundleRegistry::MANIFEST}"], base: home_plugins).any?
  Log.log.warn { "Plugins of #{home_plugins} are not used: add #{SpecialValues::DEF} to option plugin_folder" } if unused_home
  folders.each { |f| Plugins::Factory.instance.add_lookup_folder(f.eql?(SpecialValues::DEF) ? home_plugins : f, security: :low) }
  nil
end

#ask_url(params) ⇒ String

URL of the application to detect or configure: from params, else asked to the user

Parameters:

  • params (Hash) —

    parameters of detect or wizard

Returns:



432
433
434
# File 'lib/aspera/cli/plugins/config.rb', line 432

def ask_url(params)
  params['url'] || options.with_interactive { options.get_interactive('url') }
end

#command_syntax(name, reg, path) ⇒ String

Build syntax by interleaving each path segment with the arguments declared on that node

Parameters:

  • name (String, Symbol) —

    plugin name

  • reg (Command::Registry) —

    registry of plugin

  • path (Array<Symbol>) —

    command path

Returns:

  • (String) —

    e.g. node access_keys do <access_key_id> ls <path>



646
647
648
649
650
651
652
653
# File 'lib/aspera/cli/plugins/config.rb', line 646

def command_syntax(name, reg, path)
  tokens = [name.to_s]
  path.each_index do |i|
    tokens << path[i].to_s
    reg.arguments_at(path[0, i + 1]).each { |a| tokens << a.syntax }
  end
  tokens.join(' ')
end

#confirm_web_login_host(host) ⇒ Object

The login page opened by web_login comes from a code given by another host (or in a message): ask the user to accept its host the first time. Accepted hosts are kept in persistency. Without a terminal, an unknown host is refused.

Parameters:

  • host (String) —

    Host of the login page

Raises:



486
487
488
489
490
491
492
493
494
495
# File 'lib/aspera/cli/plugins/config.rb', line 486

def (host)
  persist = context.persistency
  hosts = persist.get(WEB_LOGIN_HOSTS_ID).to_s.split("\n")
  return if hosts.include?(host)
  raise BadArgument, "Host of the login page is not known: #{host}. Run this command in a terminal to accept it." unless $stdin.tty?
  Log.log.warn { "This code opens the login page of: #{host}" }
  answer = Prompt.prompt_user_input("Open it, and trust this host for next logins? (yes/no)")
  raise BadArgument, "Host of the login page refused: #{host}" unless %w[y yes].include?(answer.strip.downcase)
  persist.put(WEB_LOGIN_HOSTS_ID, (hosts + [host]).join("\n"))
end

#listed_command_path(name, reg, words) ⇒ Array<Symbol>

Command path to list, from words that may include positional arguments, as on a command line. e.g. faspex5 packages receive ALL lists faspex5 packages receive.

Parameters:

  • name (Symbol) —

    plugin name

  • reg (Command::Registry) —

    registry of plugin

  • words (Array<Symbol>) —

    sub-commands (or aliases), possibly mixed with their arguments

Returns:

  • (Array<Symbol>) —

    command path

Raises:

  • (Cli::BadArgument) —

    if a word is neither a sub-command nor an expected argument



635
636
637
638
639
# File 'lib/aspera/cli/plugins/config.rb', line 635

def listed_command_path(name, reg, words)
  path, unknown = reg.command_path(words)
  raise Cli::BadArgument, Parser.multi_choice_assert_msg("no such command: #{[name, *path, unknown].join(' ')}", reg.children_of(path).keys) unless unknown.nil?
  path
end

#load_preset(value) ⇒ Object

on_set callback of option preset

Parameters:

  • value (String, Hash) —

    preset name, or set of option values



416
417
418
419
420
421
422
423
424
425
# File 'lib/aspera/cli/plugins/config.rb', line 416

def load_preset(value)
  case value
  when Hash
    options.add_option_preset(value, 'set')
  when String
    options.add_option_preset(presets.by_name(value), 'set_by_name', configured: true)
  else
    raise BadArgument, 'Preset definition must be a String for preset name, or Hash for set of values'
  end
end