Class: MrMurano::Gateway::Resources

Inherits:
GweBase
  • Object
show all
Includes:
SyncUpDown
Defined in:
lib/MrMurano/Gateway.rb

Overview

Working with the resources on a set of Devices. (Gateway)

Defined Under Namespace

Classes: GatewayItem

Constant Summary

Constants included from Verbose

Verbose::TABULARIZE_DATA_FORMAT_ERROR

Constants included from SolutionId

SolutionId::INVALID_API_ID, SolutionId::UNEXPECTED_TYPE_OR_ERROR_MSG

Constants included from AccountBase

AccountBase::LOGIN_ADVICE, AccountBase::LOGIN_NOTICE

Instance Attribute Summary

Attributes included from SolutionId

#api_id, #sid, #valid_api_id

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SyncUpDown

#config_vars_decode, #config_vars_encode, #debug_print_localitems, #ignore?, #ignoring, #locallist, #locallist_add_item, #locallist_complain_missing, #locallist_mark_seen, #location, #match, #remove_or_clear, #resolve_config_var_usage!, #resurrect_undeletables, #searchFor, #synckey, #to_remote_items, #tolocalname, #update_mtime

Methods included from Verbose

ask_yes_no, #ask_yes_no, #assert, assert, cmd_confirm_delete!, #cmd_confirm_delete!, debug, #debug, dump_file_json, dump_file_plain, dump_file_yaml, #dump_output_file, #error, error, #error_file_format!, fancy_ticks, #fancy_ticks, #load_file_json, #load_file_plain, #load_file_yaml, #load_input_file, outf, #outf, #outformat_engine, #pluralize?, pluralize?, #prepare_hash_csv, #read_hashf!, #tabularize, tabularize, verbose, #verbose, warning, #warning, #whirly_interject, whirly_interject, #whirly_linger, whirly_linger, #whirly_msg, whirly_msg, #whirly_pause, whirly_pause, #whirly_start, whirly_start, #whirly_stop, whirly_stop, #whirly_unpause, whirly_unpause

Methods included from SyncCore

#debug_selected, #dodiff, #dodiff_build_cmd, #dodiff_cull_tempfile_paths, #dodiff_do_diff, #dodiff_download_remote, #dodiff_flexible, #dodiff_header_aware, #dodiff_local_to_tempfile, #dodiff_prepare_local_and_diff, #dodiff_resolve_localname, #dodiff_tempfile_paths, #filter_solution, #init_mods_and_chgs_arrs, #item_dirty_set_status, #item_local_there_merged, #item_merged_diff_status, #item_merged_set_status, #item_select_selected!, #items_classify_and_find_duplicates, #items_cull_clashes!, #items_lists, #items_log_duplicates, #items_log_duplicates_there_local, #items_mods_and_chgs!, #items_new_and_old!, #select_selected!, #sort_by_name, #status, #sync_update_progress, #syncable_validate_api_id, #syncdown, #syncdown_item, #syncup, #syncup_item

Methods included from SyncAllowed

#download_item_allowed, #remove_item_allowed, #removelocal_item_allowed, #sync_item_allowed, #upload_item_allowed

Methods inherited from GweBase

#endpoint, #info

Methods included from SolutionId

#affirm_valid, #api_id?, #endpoint, #init_api_id!, #valid_api_id?

Methods included from AccountBase

#add_headers, #ask_for_password!, #ask_for_user!, #cfg_clear_user_and_business, #credentials_reset, #get, #invalidate_token, #login_info, #logout, #must_prompt_if_logged_off!, #token, #token_reset, #verify_cfg_auth!, #verify_cfg_auth_persist, #verify_cfg_auth_scheme!, #verify_cfg_auth_ttl, #verify_set, warn_configfile_env_maybe

Methods included from Http

#add_headers, #curldebug, curldebug_after, curldebug_elapsed, curldebug_log, #delete, #endpoint, #get, #host, #http, #http_reset, #isJSON, #json_opts, #patch, #post, #postf, #put, #showHttpError, #user, #workit, #workit_response

Constructor Details

#initializeResources

Returns a new instance of Resources.



137
138
139
140
141
# File 'lib/MrMurano/Gateway.rb', line 137

def initialize
  super
  @itemkey = :alias
  @project_section = :resources
end

Class Method Details

.descriptionObject



143
144
145
# File 'lib/MrMurano/Gateway.rb', line 143

def self.description
  %(Resource)
end

Instance Method Details

#diff_download(tmp_path, merged, _options) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/MrMurano/Gateway.rb', line 232

def diff_download(tmp_path, merged, _options)
  @there = list if @there.nil?
  items = @there.select { |item| item[:alias] == merged[:alias] }
  if items.length > 1
    error(
      "Unexpected: more than 1 resource with the same alias: #{merged[:alias]} / #{items}"
    )
  end
  Pathname.new(tmp_path).open('wb') do |io|
    if !items.length.zero?
      diff_item_write(io, merged, nil, items.first)
    else
      io << "\n"
    end
  end
end

#diff_item_write(io, _merged, local, remote) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
# File 'lib/MrMurano/Gateway.rb', line 310

def diff_item_write(io, _merged, local, remote)
  raise 'Unexpected: please specify either local or remote, but not both' if local && remote
  item = local || remote
  raise "Unexpected: :local_path exists: #{item}" unless item[:local_path].to_s.empty?
  res = {}
  key = item[:alias]
  item = item.reject { |k, _v| i[alias synckey synctype].include? k }
  res[key] = Hash.transform_keys_to_strings(item)
  ohash = ordered_hash(res)
  io << ohash.to_yaml
end

#docmp(item_a, item_b) ⇒ Object



365
366
367
# File 'lib/MrMurano/Gateway.rb', line 365

def docmp(item_a, item_b)
  item_a != item_b
end

#download(_local, item, _options = nil) ⇒ Object



221
222
223
224
225
226
227
228
229
230
# File 'lib/MrMurano/Gateway.rb', line 221

def download(_local, item, _options=nil)
  # Not calling, e.g., `return unless download_item_allowed(item[@itemkey])`
  #   See instead: syncup_after and syncdown_after/resources_write
  @here = locallist if @here.nil?
  # needs to append/merge with file
  @here.delete_if do |i|
    i[@itemkey] == item[@itemkey]
  end
  @here << item.reject { |k, _v| i[synckey synctype].include? k }
end

#listObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/MrMurano/Gateway.rb', line 147

def list
  ret = get
  return [] unless ret.is_a?(Hash)
  return [] unless ret.key?(:resources)

  # convert hash to array.
  res = []
  ret[:resources].each_pair do |key, value|
    res << GatewayItem.new(value.merge(alias: key.to_s))
  end
  res
  # MAYBE/2017-08-17:
  #   sort_by_name(res)
end

#localitems(from) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/MrMurano/Gateway.rb', line 328

def localitems(from)
  from = Pathname.new(from) unless from.is_a?(Pathname)
  unless from.exist?
    warning "Skipping missing #{from}"
    return []
  end
  unless from.file?
    warning "Cannot read from #{from}"
    return []
  end

  here = {}
  from.open { |io| here = YAML.load(io) }
  here = {} if here == false

  # Validate file against schema.
  schema_path = Pathname.new(File.dirname(__FILE__)) + 'schema/resource-v1.0.0.yaml'
  # MAYBE/2017-07-03: Do we care if user duplicates keys in the yaml? See dup_count.
  schema = YAML.load_file(schema_path.to_s)
  begin
    JSON::Validator.validate!(schema, here)
  rescue JSON::Schema::ValidationError => err
    error("There is an error in the config file, #{from}")
    error(%("#{err.message}"))
    exit 1
  end

  res = []
  here.each_pair do |key, value|
    hash = Hash.transform_keys_to_symbols(value).merge(alias: key.to_s)
    item = GatewayItem.new(hash)
    res << item
  end

  sort_by_name(res)
end

#remove(itemkey) ⇒ Object



181
182
183
184
# File 'lib/MrMurano/Gateway.rb', line 181

def remove(itemkey)
  return unless remove_item_allowed(itemkey)
  @there.delete_if { |item| item[@itemkey] == itemkey }
end

#removelocal(_local, item) ⇒ Object



249
250
251
252
253
254
255
256
257
# File 'lib/MrMurano/Gateway.rb', line 249

def removelocal(_local, item)
  # Not calling, e.g., `return unless removelocal_item_allowed(item[@itemkey])`
  #   See instead: syncup_after and syncdown_after/resources_write
  # Append/merge with file.
  key = @itemkey.to_sym
  @here.delete_if do |it|
    it[key] == item[key]
  end
end

#resources_write(file_path) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/MrMurano/Gateway.rb', line 266

def resources_write(file_path)
  num_synced = 0
  # User can blow away specs/ directory if they want; we'll just make
  # a new one. [This code is somewhat copy-paste from make_directory.]
  basedir = file_path
  basedir = basedir.dirname unless basedir.extname.empty?
  bad_basedir = basedir.to_s.empty? || basedir == File::SEPARATOR
  raise 'Unexpected: bad basedir' if bad_basedir

  unless basedir.exist?
    if $cfg['tool.dry']
      MrMurano::Verbose.warning(
        "--dry: Not creating default directory: #{basedir}"
      )
    else
      FileUtils.mkdir_p(basedir, noop: $cfg['tool.dry'])
    end
  end

  if $cfg['tool.dry']
    MrMurano::Verbose.warning(
      "--dry: Not writing resources file: #{file_path}"
    )
    return
  end

  sync_update_progress('Updating local product resources')

  file_path.open('wb') do |io|
    # convert array to hash
    res = {}
    @here.each do |value|
      key = value[:alias]
      res[key] = Hash.transform_keys_to_strings(
        value.to_h.reject { |k, _v| k == :alias }
      )
    end
    ohash = ordered_hash(res)
    io.write ohash.to_yaml
  end

  num_synced + 1
end

#syncdown_after(local) ⇒ Object



259
260
261
262
263
264
# File 'lib/MrMurano/Gateway.rb', line 259

def syncdown_after(local)
  num_synced = super
  num_synced += resources_write(local)
  @here = nil
  num_synced
end

#syncdown_beforeObject



216
217
218
219
# File 'lib/MrMurano/Gateway.rb', line 216

def syncdown_before
  super
  @here = locallist
end

#syncup_afterObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/MrMurano/Gateway.rb', line 193

def syncup_after
  num_synced = super
  if !@there.empty?
    if !$cfg['tool.dry']
      sync_update_progress('Updating remote product resources')
      upload_all(@there)
      num_synced += 1
    else
      MrMurano::Verbose.whirly_interject do
        say('--dry: Not updating resources')
      end
    end
  elsif $cfg['tool.verbose']
    MrMurano::Verbose.whirly_interject do
      say('No resources changed')
    end
  end
  @there = nil
  num_synced
end

#syncup_beforeObject



176
177
178
179
# File 'lib/MrMurano/Gateway.rb', line 176

def syncup_before
  super
  @there = list
end

#tolocalpath(into, _item) ⇒ Object



324
325
326
# File 'lib/MrMurano/Gateway.rb', line 324

def tolocalpath(into, _item)
  into
end

#upload(_local, remote, _modify) ⇒ Object



186
187
188
189
190
191
# File 'lib/MrMurano/Gateway.rb', line 186

def upload(_local, remote, _modify)
  # Not calling, e.g., `return unless upload_item_allowed(local)`
  #   See instead: syncup_after and syncdown_after/resources_write
  @there.delete_if { |item| item[@itemkey] == remote[@itemkey] }
  @there << remote.reject { |k, _v| i[synckey synctype].include? k }
end

#upload_all(data) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
# File 'lib/MrMurano/Gateway.rb', line 162

def upload_all(data)
  # convert array to hash
  res = {}
  data.each do |value|
    key = value[:alias]
    # (lb): Item has reject method, but convert to Hash, for patch.
    res[key] = value.to_h.reject { |k, _v| k == :alias }
  end

  patch('', resources: res)
end