Class: Aspera::Cli::Plugin

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/cli/plugin.rb

Overview

base class for plugins modules

Constant Summary collapse

GLOBAL_OPS =

operations without id

i[create list].freeze
INSTANCE_OPS =

operations with id

i[modify delete show].freeze
ALL_OPS =

all standard operations

[GLOBAL_OPS, INSTANCE_OPS].flatten.freeze
MAX_ITEMS =

special query parameter: max number of items for list command

'max'
MAX_PAGES =

special query parameter: max number of pages for list command

'pmax'
VAL_ALL =

used when all resources are selected

'ALL'
REGEX_LOOKUP_ID_BY_FIELD =

special identifier format: look for this name to find where supported

/^%([^:]+):(.*)$/.freeze
@@options_created =

global for inherited classes

false

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ Plugin

rubocop:disable Style/ClassVars

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/aspera/cli/plugin.rb', line 27

def initialize(env)
  raise 'must be Hash' unless env.is_a?(Hash)
  # env.each_key {|k| raise "wrong agent key #{k}" unless AGENTS.include?(k)}
  @agents = env
  # check presence in descendant of mandatory method and constant
  raise StandardError, "Missing method 'execute_action' in #{self.class}" unless respond_to?(:execute_action)
  raise StandardError, 'ACTIONS shall be redefined by subclass' unless self.class.constants.include?(:ACTIONS)
  options.parser.separator('')
  options.parser.separator("COMMAND: #{self.class.name.split('::').last.downcase}")
  options.parser.separator("SUBCOMMANDS: #{self.class.const_get(:ACTIONS).map(&:to_s).sort.join(' ')}")
  options.parser.separator('OPTIONS:')
  return if @@options_created
  options.declare(:query, 'Additional filter for for some commands (list/delete)', types: Hash)
  options.declare(
    :value, 'Value for create, update, list filter', types: Hash,
    deprecation: 'Use positional value for create/modify or option: query for list/delete')
  options.declare(:property, 'Name of property to set (modify operation)')
  options.declare(:id, 'Resource identifier', deprecation: "Use identifier after verb (#{INSTANCE_OPS.join(',')})")
  options.declare(:bulk, 'Bulk operation (only some)', values: :bool, default: :no)
  options.declare(:bfail, 'Bulk operation error handling', values: :bool, default: :yes)
  options.parse_options!
  @@options_created = true # rubocop:disable Style/ClassVars
end

Instance Method Details

#do_bulk_operation(single_or_array, success_msg, id_result: 'id', fields: :default) ⇒ Object

For create and delete operations: execute one actin or multiple if bulk is yes

Parameters:

  • single hash, or array of hash for bulk

  • deleted or created

  • (defaults to: 'id')

    key in result hash to use as identifier

  • (defaults to: :default)

    fields to display



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/aspera/cli/plugin.rb', line 74

def do_bulk_operation(single_or_array, success_msg, id_result: 'id', fields: :default)
  raise 'programming error: missing block' unless block_given?
  params = options.get_option(:bulk) ? single_or_array : [single_or_array]
  raise 'expecting Array for bulk operation' unless params.is_a?(Array)
  Log.log.warn('Empty list given for bulk operation') if params.empty?
  Log.dump(:bulk_operation, params)
  result_list = []
  params.each do |param|
    # init for delete
    result = {id_result => param}
    begin
      # execute custom code
      res = yield(param)
      # if block returns a hash, let's use this (create)
      result = res if param.is_a?(Hash)
      result['status'] = success_msg
    rescue StandardError => e
      raise e if options.get_option(:bfail)
      result['status'] = e.to_s
    end
    result_list.push(result)
  end
  display_fields = [id_result, 'status']
  if options.get_option(:bulk)
    return {type: :object_list, data: result_list, fields: display_fields}
  else
    display_fields = fields unless fields.eql?(:default)
    return {type: :single_object, data: result_list.first, fields: display_fields}
  end
end

#entity_action(rest_api, res_class_path, **opts) ⇒ Object

implement generic rest operations on given resource path



178
179
180
181
182
# File 'lib/aspera/cli/plugin.rb', line 178

def entity_action(rest_api, res_class_path, **opts)
  # res_name=res_class_path.gsub(%r{^.*/},'').gsub(%r{s$},'').gsub('_',' ')
  command = options.get_next_command(ALL_OPS)
  return entity_command(command, rest_api, res_class_path, **opts)
end

#entity_command(command, rest_api, res_class_path, display_fields: nil, id_default: nil, item_list_key: false, id_as_arg: false, is_singleton: false, &block) ⇒ Object

Returns result suitable for CLI result.

Parameters:

  • command to execute: create show list modify delete

  • api to use

  • sub path in URL to resource relative to base url

  • (defaults to: nil)

    fields to display by default

  • (defaults to: nil)

    default identifier to use for existing entity commands (show, modify)

  • (defaults to: false)

    result is in a sub key of the json

  • (defaults to: false)

    if set, the id is provided as url argument ?<id_as_arg>=<id>

  • (defaults to: false)

    if true, res_class_path is the full path to the resource

Returns:

  • result suitable for CLI result



114
115
116
117
118
119
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/aspera/cli/plugin.rb', line 114

def entity_command(command, rest_api, res_class_path, display_fields: nil, id_default: nil, item_list_key: false, id_as_arg: false, is_singleton: false, &block)
  if is_singleton
    one_res_path = res_class_path
  elsif INSTANCE_OPS.include?(command)
    begin
      one_res_id = instance_identifier(&block)
    rescue StandardError => e
      raise e if id_default.nil?
      one_res_id = id_default
    end
    one_res_path = "#{res_class_path}/#{one_res_id}"
    one_res_path = "#{res_class_path}?#{id_as_arg}=#{one_res_id}" if id_as_arg
  end

  case command
  when :create
    raise 'cannot create singleton' if is_singleton
    return do_bulk_operation(value_create_modify(command: command, type: :bulk_hash), 'created', fields: display_fields) do |params|
      raise 'expecting Hash' unless params.is_a?(Hash)
      rest_api.create(res_class_path, params)[:data]
    end
  when :delete
    raise 'cannot delete singleton' if is_singleton
    return do_bulk_operation(one_res_id, 'deleted') do |one_id|
      rest_api.delete("#{res_class_path}/#{one_id}", old_query_read_delete)
      {'id' => one_id}
    end
  when :show
    return {type: :single_object, data: rest_api.read(one_res_path)[:data], fields: display_fields}
  when :list
    resp = rest_api.read(res_class_path, old_query_read_delete)
    data = resp[:data]
    # TODO: not generic : which application is this for ?
    if resp[:http]['Content-Type'].start_with?('application/vnd.api+json')
      Log.log.debug{'is vnd.api'}
      data = data[res_class_path]
    end
    if item_list_key
      item_list = data[item_list_key]
      total_count = data['total_count']
      formatter.display_item_count(item_list.length, total_count) unless total_count.nil?
      data = item_list
    end
    case data
    when Hash
      return {type: :single_object, data: data, fields: display_fields}
    when Array
      return {type: :object_list, data: data, fields: display_fields} if data.empty? || data.first.is_a?(Hash)
      return {type: :value_list, data: data, name: 'id'}
    else
      raise "An error occurred: unexpected result type for list: #{data.class}"
    end
  when :modify
    parameters = value_create_modify(command: command, type: Hash)
    property = options.get_option(:property)
    parameters = {property => parameters} unless property.nil?
    rest_api.update(one_res_path, parameters)
    return Main.result_status('modified')
  else
    raise "unknown action: #{command}"
  end
end

#instance_identifier(description: 'identifier', &block) ⇒ String

must be called AFTER the instance action, … folder browse <call instance_identifier>

Parameters:

  • (defaults to: 'identifier')

    description of the identifier

  • block to search for identifier based on attribute value

Returns:

  • identifier



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/aspera/cli/plugin.rb', line 55

def instance_identifier(description: 'identifier', &block)
  res_id = options.get_option(:id)
  res_id = options.get_next_argument(description) if res_id.nil?
  # cab be an Array
  if res_id.is_a?(String) && (m = res_id.match(REGEX_LOOKUP_ID_BY_FIELD))
    if block
      res_id = yield(m[1], ExtendedValue.instance.evaluate(m[2]))
    else
      raise CliBadArgument, "Percent syntax for #{description} not supported in this context"
    end
  end
  return res_id
end

#old_query_read_deleteObject

TODO: when deprecation of value is completed: remove this method, replace with query_read_delete



200
201
202
203
204
# File 'lib/aspera/cli/plugin.rb', line 200

def old_query_read_delete
  query = options.get_option(:value) # legacy, deprecated, remove, one day...
  query = query_read_delete if query.nil?
  return query
end

#query_read_delete(default: nil) ⇒ Object

query parameters in URL suitable for REST list/GET and delete/DELETE



185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/aspera/cli/plugin.rb', line 185

def query_read_delete(default: nil)
  query = options.get_option(:query)
  # dup default, as it could be frozen
  query = default.dup if query.nil?
  Log.log.debug{"Query=#{query}".bg_red}
  begin
    # check it is suitable
    URI.encode_www_form(query) unless query.nil?
  rescue StandardError => e
    raise CliBadArgument, "Query must be an extended value which can be encoded with URI.encode_www_form. Refer to manual. (#{e.message})"
  end
  return query
end

#value_create_modify(default: nil, command: 'command', type: nil) ⇒ Object

Retrieves an extended value from command line, used for creation or modification of entities TODO: when deprecation of value is completed: remove line with :value

Parameters:

  • (defaults to: nil)

    default value if not provided

  • (defaults to: 'command')

    command name for error message

  • (defaults to: nil)

    expected type of value



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/aspera/cli/plugin.rb', line 218

def value_create_modify(default: nil, command: 'command', type: nil)
  value = options.get_option(:value)
  value = options.get_next_argument("parameters for #{command}", mandatory: default.nil?) if value.nil?
  value = default if value.nil?
  if type.nil?
    # nothing to do
  elsif type.is_a?(Class)
    raise CliBadArgument, "Value must be a #{type}" unless value.is_a?(type)
  elsif type.is_a?(Array)
    raise CliBadArgument, "Value must be one of #{type.join(', ')}" unless type.any?{|t| value.is_a?(t)}
  elsif type.eql?(:bulk_hash)
    raise CliBadArgument, 'Value must be a Hash or Array of Hash' unless value.is_a?(Hash) || (value.is_a?(Array) && value.all?(Hash))
  else
    raise "Internal error: #{type}"
  end
  return value
end

#value_or_query(mandatory: false, allowed_types: nil) ⇒ Object

TODO: when deprecation of value is completed: remove this method, replace with options.get_option(:query)



207
208
209
210
211
# File 'lib/aspera/cli/plugin.rb', line 207

def value_or_query(mandatory: false, allowed_types: nil)
  value = options.get_option(:value, mandatory: false, allowed_types: allowed_types)
  value = options.get_option(:query, mandatory: mandatory, allowed_types: allowed_types) if value.nil?
  return value
end