Class: HaveAPI::CLI::Cli
- Inherits:
-
Object
- Object
- HaveAPI::CLI::Cli
- 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
- #param_option(name, p) ⇒ Object
- #parameters(action) ⇒ Object
- #print_examples(action) ⇒ Object
- #protocol_version ⇒ Object
- #show_help(exit_code = true) ⇒ Object
- #show_version ⇒ Object
Constructor Details
#initialize ⇒ Cli
27 28 29 30 31 32 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 |
# File 'lib/haveapi/cli/cli.rb', line 27 def initialize @config = read_config || {} args, @opts = @api = HaveAPI::Client::Communicator.new(api_url, @opts[:version]) @api.identity = $0.split('/').last 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 action.update_description(@api.describe_action(action)) if authenticate(action) @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 end |
Class Attribute Details
.auth_methods ⇒ Object
Returns the value of attribute auth_methods.
10 11 12 |
# File 'lib/haveapi/cli/cli.rb', line 10 def auth_methods @auth_methods end |
.commands ⇒ Object
Returns the value of attribute commands.
10 11 12 |
# File 'lib/haveapi/cli/cli.rb', line 10 def commands @commands end |
Class Method Details
.register_auth_method(name, klass) ⇒ Object
16 17 18 19 |
# File 'lib/haveapi/cli/cli.rb', line 16 def register_auth_method(name, klass) @auth_methods ||= {} @auth_methods[name] = klass end |
.register_command(cmd) ⇒ Object
21 22 23 24 |
# File 'lib/haveapi/cli/cli.rb', line 21 def register_command(cmd) @commands ||= [] @commands << cmd end |
.run ⇒ Object
12 13 14 |
# File 'lib/haveapi/cli/cli.rb', line 12 def run c = new end |
Instance Method Details
#api_url ⇒ Object
118 119 120 |
# File 'lib/haveapi/cli/cli.rb', line 118 def api_url @opts[:client] end |
#authenticate(action = nil) ⇒ Object
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
# File 'lib/haveapi/cli/cli.rb', line 549 def authenticate(action = nil) return false if !action.nil? && !action.auth? if @auth @auth.communicator = @api @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
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/haveapi/cli/cli.rb', line 356 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
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/haveapi/cli/cli.rb', line 372 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
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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 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 |
# File 'lib/haveapi/cli/cli.rb', line 439 def format_output(action, response, out = $>) if @opts[:raw] puts JSON.generate(response) return end return if response.empty? 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
539 540 541 542 543 544 545 546 547 |
# File 'lib/haveapi/cli/cli.rb', line 539 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
340 341 342 343 344 345 346 |
# File 'lib/haveapi/cli/cli.rb', line 340 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
324 325 326 327 328 329 330 |
# File 'lib/haveapi/cli/cli.rb', line 324 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
332 333 334 335 336 337 338 |
# File 'lib/haveapi/cli/cli.rb', line 332 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
312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/haveapi/cli/cli.rb', line 312 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
399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/haveapi/cli/cli.rb', line 399 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
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 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 |
# File 'lib/haveapi/cli/cli.rb', line 122 def = { client: default_url, 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 @auth = Cli.auth_methods[m].new(server_config([:client])[:auth][m]) @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('-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]) @auth = Cli.auth_methods[cfg[:last_auth]].new(cfg[:auth][cfg[:last_auth]]) if cfg[:last_auth] end [args, ] end |
#param_option(name, p) ⇒ Object
298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/haveapi/cli/cli.rb', line 298 def param_option(name, p) ret = '--' name = name.to_s.dasherize if p[:type] == 'Boolean' ret += "[no-]#{name}" else ret += "#{name} #{name.underscore.upcase}" end ret end |
#parameters(action) ⇒ Object
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 |
# File 'lib/haveapi/cli/cli.rb', line 251 def parameters(action) = {} sep = ARGV.index('--') @action_opt = OptionParser.new do |opts| opts. = '' action.input[:parameters].each do |name, p| opts.on(param_option(name, p), p[:description] || p[:label] || '') do |*args| [name] = args.first 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
432 433 434 435 436 437 |
# File 'lib/haveapi/cli/cli.rb', line 432 def print_examples(action) unless action.examples.empty? puts "\nExamples:\n" ExampleFormatter.format_examples(self, action) end end |
#protocol_version ⇒ Object
352 353 354 |
# File 'lib/haveapi/cli/cli.rb', line 352 def protocol_version puts HaveAPI::Client::PROTOCOL_VERSION end |
#show_help(exit_code = true) ⇒ Object
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/haveapi/cli/cli.rb', line 413 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 |