Class: HaveAPI::CLI::Cli

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/haveapi/cli/cli.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils

#param_option, #read_param

Constructor Details

#initializeCli

Returns a new instance of Cli.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
104
105
106
107
108
109
110
111
112
113
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
# File 'lib/haveapi/cli/cli.rb', line 33

def initialize
  @config = read_config || {}
  args, @opts = options

  connect_api unless @api

  if @action
    method(@action.first).call(* @action[1..])
    exit
  end

  if (@opts[:help] && args.empty?) || args.empty?
    show_help do
      puts "\nAvailable resources:"
      list_resources
    end
  end

  resources = args[0].split('.')

  if (cmd = find_command(resources, args[1]))
    authenticate if @auth
    c = cmd.new(@opts, HaveAPI::Client::Client.new(nil, communicator: @api))

    cmd_opt = OptionParser.new do |opts|
      opts.banner = "\nCommand options:"
      c.options(opts)

      opts.on('-h', '--help', 'Show this message') do
        show_help do
          puts cmd_opt.help
        end
      end
    end

    if @opts[:help]
      show_help do
        puts cmd_opt.help
      end
    end

    if (sep = ARGV.index('--'))
      cmd_opt.parse!(ARGV[sep + 1..])
    end

    c.exec(args[2..] || [])

    exit
  end

  if args.count == 1
    describe_resource(resources)
    exit
  end

  action = @api.get_action(resources, args[1].to_sym, args[2..])

  unless action
    warn "Resource or action '#{args[0]} #{args[1]}' not found"
    puts
    show_help(false)
  end

  if authenticate(action) && !action.unresolved_args?
    begin
      action.update_description(@api.describe_action(action))
    rescue RestClient::ResourceNotFound => e
      format_errors(action, 'Object not found', {})
      exit(false)
    end
  end

  @selected_params = if @opts[:output]
                       @opts[:output].split(',').uniq
                     end

  @input_params = parameters(action)

  includes = build_includes(action) if @selected_params
  @input_params[:meta] = { includes: includes } if includes

  begin
    ret = action.execute(@input_params, raw: @opts[:raw])
  rescue HaveAPI::Client::ValidationError => e
    format_errors(action, 'input parameters not valid', e.errors)
    exit(false)
  end

  if ret[:status]
    format_output(action, ret[:response])

  else
    format_errors(action, ret[:message], ret[:errors])
    exit(false)
  end

  return unless action.blocking?

  res = HaveAPI::Client::Response.new(action, ret)

  return unless res.meta[:action_state_id]

  state = ActionState.new(
    @opts,
    HaveAPI::Client::Client.new(@api.url, communicator: @api, block: false),
    res.meta[:action_state_id]
  )

  puts

  if @opts[:block]
    action_ret = state.wait_for_completion(timeout: @opts[:timeout])

    if action_ret.nil?
      warn 'Timeout'
      exit(false)
    end

  else
    state.print_help
  end
end

Class Attribute Details

.auth_methodsObject

Returns the value of attribute auth_methods.



11
12
13
# File 'lib/haveapi/cli/cli.rb', line 11

def auth_methods
  @auth_methods
end

.commandsObject

Returns the value of attribute commands.



11
12
13
# File 'lib/haveapi/cli/cli.rb', line 11

def commands
  @commands
end

Class Method Details

.register_auth_method(name, klass) ⇒ Object



20
21
22
23
# File 'lib/haveapi/cli/cli.rb', line 20

def register_auth_method(name, klass)
  @auth_methods ||= {}
  @auth_methods[name] = klass
end

.register_command(cmd) ⇒ Object



25
26
27
28
# File 'lib/haveapi/cli/cli.rb', line 25

def register_command(cmd)
  @commands ||= []
  @commands << cmd
end

.runObject



13
14
15
16
17
18
# File 'lib/haveapi/cli/cli.rb', line 13

def run
  c = new
rescue Interrupt
  warn 'Interrupted'
  exit(false)
end

Instance Method Details

#api_urlObject



156
157
158
# File 'lib/haveapi/cli/cli.rb', line 156

def api_url
  @opts[:client]
end

#authenticate(action = nil) ⇒ Object



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/haveapi/cli/cli.rb', line 618

def authenticate(action = nil)
  raise 'auth is needed and has not been selected' unless @auth

  @auth.validate
  @auth.authenticate

  if @opts[:save]
    cfg = server_config(api_url)
    cfg[:auth][@opts[:auth]] = @auth.save
    cfg[:last_auth] = @opts[:auth]
    write_config
  end

  true
end

#check_compatObject



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/haveapi/cli/cli.rb', line 426

def check_compat
  case @api.compatible?
  when :compatible
    puts 'compatible'
    exit

  when :imperfect
    puts 'imperfect'
    exit(1)

  else
    puts 'incompatible'
    exit(2)
  end
end

#describe_resource(path) ⇒ Object



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/haveapi/cli/cli.rb', line 442

def describe_resource(path)
  desc = @api.describe_resource(path)

  unless desc
    warn "Resource #{path.join('.')} does not exist"
    exit(false)
  end

  unless desc[:resources].empty?
    puts 'Resources:'

    desc[:resources].keys.sort.each do |r|
      puts "  #{r}"
    end
  end

  puts '' if !desc[:resources].empty? && !desc[:actions].empty?

  return if desc[:actions].empty?

  puts 'Actions:'

  desc[:actions].keys.sort.each do |a|
    puts "  #{a}"
  end
end

#format_output(action, response, out = $>) ⇒ Object



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/haveapi/cli/cli.rb', line 509

def format_output(action, response, out = $>)
  if @opts[:raw]
    puts JSON.generate(response)
    return
  end

  return if response.empty? || action.output.nil?

  namespace = action.namespace(:output).to_sym

  if action.output_layout.to_sym == :custom
    return PP.pp(response[namespace], out)
  end

  cols = []

  (@selected_params || action.params.keys).each do |raw_name|
    col = {}
    name = nil
    param = nil

    # Fetching an associated attribute
    if raw_name.to_s.index('.')
      parts = raw_name.to_s.split('.').map!(&:to_sym)
      name = parts.first.to_sym

      top = action.params

      parts.each do |part|
        raise "'#{part}' not found" unless top.has_key?(part)

        param = top[part]

        break if param[:type] != 'Resource'

        top = @api.get_action(param[:resource], :show, []).params
      end

      col[:display] = proc do |r|
        next '' unless r

        top = r
        parts[1..].each do |part|
          raise "'#{part}' not found" unless top.has_key?(part)
          break if top[part].nil?

          top = top[part]
        end

        case param[:type]
        when 'Resource'
          "#{top[param[:value_label].to_sym]} (##{top[param[:value_id].to_sym]})"

        when 'Datetime'
          format_date(top)

        else
          top
        end
      end

      col[:label] = raw_name

    else # directly accessible parameter
      name = raw_name.to_sym
      param = action.params[name]
      raise "parameter '#{name}' does not exist" if param.nil?

      if param[:type] == 'Resource'
        col[:display] = proc do |r|
          next '' unless r

          "#{r[param[:value_label].to_sym]} (##{r[param[:value_id].to_sym]})"
        end

      elsif param[:type] == 'Datetime'
        col[:display] = ->(date) { format_date(date) }
      end
    end

    col.update({
        name: name,
        align: %w[Integer Float].include?(param[:type]) ? 'right' : 'left'
    })

    col[:label] ||= param[:label] && !param[:label].empty? ? param[:label] : name.upcase

    cols << col
  end

  OutputFormatter.print(
    response[namespace],
    cols,
    header: @opts[:header].nil?,
    sort: @opts[:sort] && @opts[:sort].to_sym,
    layout: @opts[:layout]
  )
end

#header_for(action, param) ⇒ Object



608
609
610
611
612
613
614
615
616
# File 'lib/haveapi/cli/cli.rb', line 608

def header_for(action, param)
  params = action.params

  if params.has_key?(param) && params[param][:label]
    params[param][:label]
  else
    param.to_s.upcase
  end
end

#list_actions(v = nil) ⇒ Object



410
411
412
413
414
415
416
# File 'lib/haveapi/cli/cli.rb', line 410

def list_actions(v = nil)
  desc = @api.describe_api(v)

  sort_by_key(desc[:resources]).each do |resource, children|
    nested_resource(resource, children, true)
  end
end

#list_auth(v = nil) ⇒ Object



394
395
396
397
398
399
400
# File 'lib/haveapi/cli/cli.rb', line 394

def list_auth(v = nil)
  desc = @api.describe_api(v)

  desc[:authentication].each_key do |auth|
    puts auth if Cli.auth_methods.has_key?(auth)
  end
end

#list_resources(v = nil) ⇒ Object



402
403
404
405
406
407
408
# File 'lib/haveapi/cli/cli.rb', line 402

def list_resources(v = nil)
  desc = @api.describe_api(v)

  sort_by_key(desc[:resources]).each do |resource, children|
    nested_resource(resource, children, false)
  end
end

#list_versionsObject



382
383
384
385
386
387
388
389
390
391
392
# File 'lib/haveapi/cli/cli.rb', line 382

def list_versions
  desc = @api.available_versions

  desc[:versions].each_key do |v|
    next if v == :default

    v_int = v.to_s.to_i

    puts "#{v_int == desc[:default] ? '*' : ' '} v#{v}"
  end
end

#nested_resource(prefix, children, actions = false) ⇒ Object



469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/haveapi/cli/cli.rb', line 469

def nested_resource(prefix, children, actions = false)
  if actions
    children[:actions].keys.sort.each do |action|
      puts "#{prefix}##{action}"
    end
  else
    puts prefix
  end

  sort_by_key(children[:resources]).each do |resource, grandchildren|
    nested_resource("#{prefix}.#{resource}", grandchildren, actions)
  end
end

#optionsObject



160
161
162
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/haveapi/cli/cli.rb', line 160

def options
  options = {
      client: default_url,
      raw_values: false,
      block: true,
      verbose: false
  }

  @global_opt = OptionParser.new do |opts|
    opts.banner = "Usage: #{$0} [options] <resource> <action> [objects ids] [-- [parameters]]"

    opts.on('-u', '--api URL', 'API URL') do |url|
      options[:client] = url
    end

    opts.on('-a', '--auth METHOD', Cli.auth_methods.keys, 'Authentication method') do |m|
      options[:auth] = m
      connect_api(url: options[:client], version: options[:version], verify_ssl: options[:verify_ssl])

      @auth = Cli.auth_methods[m].new(
        @api,
        @api.describe_api(options[:version])[:authentication][m],
        server_config(options[:client])[:auth][m]
      )

      opts.separator "\nAuthentication options:"
      @auth.options(opts)
    end

    opts.on('--list-versions', 'List all available API versions') do
      @action = [:list_versions]
    end

    opts.on('--list-auth-methods [VERSION]', 'List available authentication methods') do |v|
      @action = [:list_auth, v && v.sub(/^v/, '')]
    end

    opts.on('--list-resources [VERSION]', 'List all resource in API version') do |v|
      @action = [:list_resources, v && v.sub(/^v/, '')]
    end

    opts.on('--list-actions [VERSION]', 'List all resources and actions in API version') do |v|
      @action = [:list_actions, v && v.sub(/^v/, '')]
    end

    opts.on('--version VERSION', 'Use specified API version') do |v|
      options[:version] = v
    end

    opts.on('-c', '--columns', 'Print output in columns') do
      options[:layout] = :columns
    end

    opts.on('-H', '--no-header', 'Hide header row') do |_h|
      options[:header] = false
    end

    opts.on('-L', '--list-parameters', 'List output parameters') do |_l|
      options[:list_output] = true
    end

    opts.on('-o', '--output PARAMETERS', 'Parameters to display, separated by a comma') do |o|
      options[:output] = o
    end

    opts.on('-r', '--rows', 'Print output in rows') do
      options[:layout] = :rows
    end

    opts.on('-s', '--sort PARAMETER', 'Sort output by parameter') do |p|
      options[:sort] = p
    end

    opts.on('--save', 'Save credentials to config file for later use') do
      options[:save] = true
    end

    opts.on('--raw', 'Print raw response as is') do
      options[:raw] = true
    end

    opts.on('--[no-]raw-values', 'Toggle parameter processing') do |v|
      options[:raw_values] = v
    end

    opts.on('--timestamp', 'Display Datetime parameters as timestamp') do
      options[:datetime] = :timestamp
    end

    opts.on('--utc', 'Display Datetime parameters in UTC') do
      options[:datetime] = :utc
    end

    opts.on('--localtime', 'Display Datetime parameters in local timezone') do
      options[:datetime] = :local
    end

    opts.on('--date-format FORMAT', 'Display Datetime in custom format') do |f|
      options[:date_format] = f
    end

    opts.on('--[no-]block', 'Toggle action blocking mode') do |v|
      options[:block] = v
    end

    opts.on(
      '--timeout SEC',
      Float,
      'Fail when the action does not finish within the timeout'
    ) do |v|
      options[:timeout] = v.to_f
    end

    opts.on('-v', '--[no-]verbose', 'Run verbosely') do |v|
      options[:verbose] = v
    end

    opts.on('--client-version', 'Show client version') do
      @action = [:show_version]
    end

    opts.on('--protocol-version', 'Show protocol version') do
      @action = [:protocol_version]
    end

    opts.on('--check-compatibility', 'Check compatibility with API server') do
      @action = [:check_compat]
    end

    opts.on('--[no-]verify-ssl', 'Toggle SSL peer verification') do |v|
      options[:verify_ssl] = v
    end

    opts.on('-h', '--help', 'Show this message') do
      options[:help] = true
    end
  end

  args = []

  ARGV.each do |arg|
    break if arg == '--'

    args << arg
  end

  @global_opt.parse!(args)

  unless options[:auth]
    cfg = server_config(options[:client])

    unless @api
      connect_api(url: options[:client], version: options[:version], verify_ssl: options[:verify_ssl])
    end

    if (m = cfg[:last_auth])
      @auth = Cli.auth_methods[m].new(
        @api,
        @api.describe_api(options[:version])[:authentication][m],
        cfg[:auth][m]
      )
    end
  end

  [args, options]
end

#parameters(action) ⇒ Object



327
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/haveapi/cli/cli.rb', line 327

def parameters(action)
  options = {}
  sep = ARGV.index('--')

  @action_opt = OptionParser.new do |opts|
    opts.banner = ''

    if action.input
      action.input[:parameters].each do |name, p|
        opts.on(param_option(name, p), p[:description] || p[:label] || ' ') do |*args|
          arg = args.first

          options[name] = if arg.nil?
                            read_param(name, p)
                          else
                            parse_action_param(name, args.first)
                          end
        end
      end
    end

    opts.on('-h', '--help', 'Show this message') do
      @opts[:help] = true
    end
  end

  if @opts[:help]
    show_help do
      puts 'Action description:'
      puts action.description, "\n"
      print 'Input parameters:'
      puts @action_opt.help
      puts
      puts 'Output parameters:'

      action.params.each do |name, param|
        puts format('    %-32s %s', name, param[:description])
      end

      print_examples(action)
    end
  end

  if @opts[:list_output]
    action.params.each_key { |name| puts name }
    exit
  end

  return {} unless sep

  @action_opt.parse!(ARGV[sep + 1..])

  options
end


502
503
504
505
506
507
# File 'lib/haveapi/cli/cli.rb', line 502

def print_examples(action)
  return if action.examples.empty?

  puts "\nExamples:\n"
  ExampleFormatter.format_examples(self, action)
end

#protocol_versionObject



422
423
424
# File 'lib/haveapi/cli/cli.rb', line 422

def protocol_version
  puts HaveAPI::Client::PROTOCOL_VERSION
end

#show_help(exit_code = true) ⇒ Object



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/haveapi/cli/cli.rb', line 483

def show_help(exit_code = true)
  puts @global_opt.help

  if Cli.commands
    puts
    puts 'Commands:'
    Cli.commands.each do |cmd|
      puts format(
        '%-36s %s',
        "#{cmd.resource.join('.')} #{cmd.action} #{cmd.args}",
        cmd.desc
      )
    end
  end

  yield if block_given?
  exit(exit_code)
end

#show_versionObject



418
419
420
# File 'lib/haveapi/cli/cli.rb', line 418

def show_version
  puts HaveAPI::Client::VERSION
end