Class: HaveAPI::CLI::Cli
- Inherits:
-
Object
- Object
- HaveAPI::CLI::Cli
- Includes:
- Utils
- Defined in:
- lib/haveapi/cli/cli.rb
Class Attribute Summary collapse
-
.auth_methods ⇒ Object
Returns the value of attribute auth_methods.
-
.commands ⇒ Object
Returns the value of attribute commands.
Class Method Summary collapse
Instance Method Summary collapse
- #api_url ⇒ Object
- #authenticate(action = nil) ⇒ Object
- #check_compat ⇒ Object
- #describe_resource(path) ⇒ Object
- #format_output(action, response, out = $>) ⇒ Object
- #header_for(action, param) ⇒ Object
-
#initialize ⇒ Cli
constructor
A new instance of Cli.
- #list_actions(v = nil) ⇒ Object
- #list_auth(v = nil) ⇒ Object
- #list_resources(v = nil) ⇒ Object
- #list_versions ⇒ Object
- #nested_resource(prefix, children, actions = false) ⇒ Object
- #options ⇒ Object
- #parameters(action) ⇒ Object
- #print_examples(action) ⇒ Object
- #protocol_version ⇒ Object
- #show_help(exit_code = true) ⇒ Object
- #show_version ⇒ Object
Methods included from Utils
Constructor Details
#initialize ⇒ Cli
Returns a new instance of Cli.
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 155 156 |
# File 'lib/haveapi/cli/cli.rb', line 34 def initialize @config = read_config || {} args, @opts = connect_api unless @api if @action method(@action.first).call( * @action[1..-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. = "\nCommand options:" c.(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..-1]) end c.exec(args[2..-1] || []) exit end if args.count == 1 describe_resource(resources) exit(true) end action = @api.get_action(resources, args[1].to_sym, args[2..-1]) 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 = @opts[:output] ? @opts[:output].split(',').uniq : nil @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 if action.blocking? res = HaveAPI::Client::Response.new(action, ret) if res.[:action_state_id] state = ActionState.new( @opts, HaveAPI::Client::Client.new(@api.url, communicator: @api, block: false), res.[:action_state_id] ) if @opts[:block] puts action_ret = state.wait_for_completion(timeout: @opts[:timeout]) if action_ret.nil? warn "Timeout" exit(false) end else puts state.print_help end end end end |
Class Attribute Details
.auth_methods ⇒ Object
Returns the value of attribute auth_methods.
11 12 13 |
# File 'lib/haveapi/cli/cli.rb', line 11 def auth_methods @auth_methods end |
.commands ⇒ Object
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
21 22 23 24 |
# File 'lib/haveapi/cli/cli.rb', line 21 def register_auth_method(name, klass) @auth_methods ||= {} @auth_methods[name] = klass end |
.register_command(cmd) ⇒ Object
26 27 28 29 |
# File 'lib/haveapi/cli/cli.rb', line 26 def register_command(cmd) @commands ||= [] @commands << cmd end |
.run ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/haveapi/cli/cli.rb', line 13 def run c = new rescue Interrupt warn "Interrupted" exit(false) end |
Instance Method Details
#api_url ⇒ Object
158 159 160 |
# File 'lib/haveapi/cli/cli.rb', line 158 def api_url @opts[:client] end |
#authenticate(action = nil) ⇒ Object
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 |
# File 'lib/haveapi/cli/cli.rb', line 612 def authenticate(action = nil) if @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 else # FIXME: exit as auth is needed and has not been selected end return true end |
#check_compat ⇒ Object
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/haveapi/cli/cli.rb', line 419 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
435 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 |
# File 'lib/haveapi/cli/cli.rb', line 435 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].each_key do |r| puts " #{r}" end end puts '' if !desc[:resources].empty? && !desc[:actions].empty? unless desc[:actions].empty? puts 'Actions:' desc[:actions].each_key do |a| puts " #{a}" end end end |
#format_output(action, response, out = $>) ⇒ Object
502 503 504 505 506 507 508 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 |
# File 'lib/haveapi/cli/cli.rb', line 502 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! { |v| v.to_sym } name = parts.first.to_sym top = action.params parts.each do |part| fail "'#{part}' not found" unless top.has_key?(part) if top[part][:type] == 'Resource' param = top[part] top = @api.get_action(top[part][:resource], :show, []).params else param = top[part] break end end col[:display] = Proc.new do |r| next '' unless r top = r parts[1..-1].each do |part| fail "'#{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] fail "parameter '#{name}' does not exist" if param.nil? if param[:type] == 'Resource' col[:display] = Proc.new 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
602 603 604 605 606 607 608 609 610 |
# File 'lib/haveapi/cli/cli.rb', line 602 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
403 404 405 406 407 408 409 |
# File 'lib/haveapi/cli/cli.rb', line 403 def list_actions(v=nil) desc = @api.describe_api(v) desc[:resources].each do |resource, children| nested_resource(resource, children, true) end end |
#list_auth(v = nil) ⇒ Object
387 388 389 390 391 392 393 |
# File 'lib/haveapi/cli/cli.rb', line 387 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
395 396 397 398 399 400 401 |
# File 'lib/haveapi/cli/cli.rb', line 395 def list_resources(v=nil) desc = @api.describe_api(v) desc[:resources].each do |resource, children| nested_resource(resource, children, false) end end |
#list_versions ⇒ Object
375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/haveapi/cli/cli.rb', line 375 def list_versions desc = @api.available_versions desc[:versions].each 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
462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/haveapi/cli/cli.rb', line 462 def nested_resource(prefix, children, actions=false) if actions children[:actions].each do |action, _| puts "#{prefix}##{action}" end else puts prefix end children[:resources].each do |resource, children| nested_resource("#{prefix}.#{resource}", children, actions) end end |
#options ⇒ Object
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 |
# File 'lib/haveapi/cli/cli.rb', line 162 def = { client: default_url, block: true, verbose: false, } @global_opt = OptionParser.new do |opts| opts. = "Usage: #{$0} [options] <resource> <action> [objects ids] [-- [parameters]]" opts.on('-u', '--api URL', 'API URL') do |url| [:client] = url end opts.on('-a', '--auth METHOD', Cli.auth_methods.keys, 'Authentication method') do |m| [:auth] = m connect_api(url: [:client], version: [:version]) @auth = Cli.auth_methods[m].new( @api, @api.describe_api([:version])[:authentication][m], server_config([:client])[:auth][m] ) opts.separator "\nAuthentication options:" @auth.(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| [:version] = v end opts.on('-c', '--columns', 'Print output in columns') do [:layout] = :columns end opts.on('-H', '--no-header', 'Hide header row') do |h| [:header] = false end opts.on('-L', '--list-parameters', 'List output parameters') do |l| [:list_output] = true end opts.on('-o', '--output PARAMETERS', 'Parameters to display, separated by a comma') do |o| [:output] = o end opts.on('-r', '--rows', 'Print output in rows') do [:layout] = :rows end opts.on('-s', '--sort PARAMETER', 'Sort output by parameter') do |p| [:sort] = p end opts.on('--save', 'Save credentials to config file for later use') do [:save] = true end opts.on('--raw', 'Print raw response as is') do [:raw] = true end opts.on('--timestamp', 'Display Datetime parameters as timestamp') do [:datetime] = :timestamp end opts.on('--utc', 'Display Datetime parameters in UTC') do [:datetime] = :utc end opts.on('--localtime', 'Display Datetime parameters in local timezone') do [:datetime] = :local end opts.on('--date-format FORMAT', 'Display Datetime in custom format') do |f| [:date_format] = f end opts.on('--[no-]block', 'Toggle action blocking mode') do |v| [:block] = v end opts.on( '--timeout SEC', Float, 'Fail when the action does not finish within the timeout' ) do |v| [:timeout] = v.to_f end opts.on('-v', '--[no-]verbose', 'Run verbosely') do |v| [: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('-h', '--help', 'Show this message') do [:help] = true end end args = [] ARGV.each do |arg| if arg == '--' break else args << arg end end @global_opt.parse!(args) unless [:auth] cfg = server_config([:client]) connect_api(url: [:client], version: [:version]) unless @api if m = cfg[:last_auth] @auth = Cli.auth_methods[m].new( @api, @api.describe_api([:version])[:authentication][m], cfg[:auth][m], ) end end [args, ] end |
#parameters(action) ⇒ Object
319 320 321 322 323 324 325 326 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 |
# File 'lib/haveapi/cli/cli.rb', line 319 def parameters(action) = {} sep = ARGV.index('--') @action_opt = OptionParser.new do |opts| opts. = '' 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 if arg.nil? [name] = read_param(name, p) else [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 sprintf(" %-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..-1]) end |
#print_examples(action) ⇒ Object
495 496 497 498 499 500 |
# File 'lib/haveapi/cli/cli.rb', line 495 def print_examples(action) unless action.examples.empty? puts "\nExamples:\n" ExampleFormatter.format_examples(self, action) end end |
#protocol_version ⇒ Object
415 416 417 |
# File 'lib/haveapi/cli/cli.rb', line 415 def protocol_version puts HaveAPI::Client::PROTOCOL_VERSION end |
#show_help(exit_code = true) ⇒ Object
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
# File 'lib/haveapi/cli/cli.rb', line 476 def show_help(exit_code = true) puts @global_opt.help if Cli.commands puts puts 'Commands:' Cli.commands.each do |cmd| puts sprintf( '%-36s %s', "#{cmd.resource.join('.')} #{cmd.action} #{cmd.args}", cmd.desc ) end end yield if block_given? exit(exit_code) end |