Class: JDC::CLI

Inherits:
Mothership show all
Includes:
Interactive, Spacing
Defined in:
lib/jdc/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Spacing

#indented, #justify, #line, #lines, #spaced, #start_line, #tabular, #text_width, #trim_escapes

Methods included from Interactive

#ask, #handler, #input_state, #list_choices, #prompt, #show_default

Class Method Details

.clientObject



511
512
513
# File 'lib/jdc/cli.rb', line 511

def client
  @@client
end

.client=(c) ⇒ Object



515
516
517
# File 'lib/jdc/cli.rb', line 515

def client=(c)
  @@client = c
end

Instance Method Details

#add_exception_name_to_msg(e) ⇒ Object



214
215
216
217
218
# File 'lib/jdc/cli.rb', line 214

def add_exception_name_to_msg(e)
  msg = e.class.name
  msg << ": #{e}" unless e.to_s.empty?
  msg
end

#build_client(target) ⇒ Object



499
500
501
502
503
504
# File 'lib/jdc/cli.rb', line 499

def build_client(target)
  client = JFoundry::V2::Client.new(target, ENV['ACCESS_KEY'], ENV['SECRET_KEY'], JDC::VERSION, "jdc")
  client.http_proxy = input[:http_proxy] || ENV['HTTP_PROXY'] || ENV['http_proxy']
  client.https_proxy = input[:https_proxy] || ENV['HTTPS_PROXY'] || ENV['https_proxy']
  client
end

#check_keyObject



69
70
71
72
73
74
75
76
77
# File 'lib/jdc/cli.rb', line 69

def check_key
    unless ENV["ACCESS_KEY"]
        fail "Please set the env ACCESS_KEY."
    end

    unless ENV["SECRET_KEY"]
        fail "Please set the env SECRET_KEY."
    end
end

#check_logged_inObject



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/jdc/cli.rb', line 116

def check_logged_in
  check_target
  unless client.logged_in?
    if force?
      fail "Please log in with 'jdc login'."
    else
      line c("Please log in first to proceed.", :warning)
      line
      invoke :login
      invalidate_client
    end
  end
end

#check_organization_and_spaceObject



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
# File 'lib/jdc/cli.rb', line 85

def check_organization_and_space
  info = target_info(client.target)

  info_changed = false
  if (info.key? :organization) && info[:access_key] != ENV['ACCESS_KEY']
      info.delete(:organization)
      client.current_organization = nil
      info_changed = true
  end

  if (info.key? :space) && info[:access_key] != ENV['ACCESS_KEY']
      info.delete(:space)
      client.current_space = nil
      info_changed = true
  end

  if info[:access_key] != ENV['ACCESS_KEY']
      info[:access_key] = ENV['ACCESS_KEY']
      info_changed = true
  end

  save_target_info(info, client.target) unless !info_changed

  if @@client.try(:current_user).try(:email) != nil
    unless info.key? :organization
        client.current_organization = JDC::Populators::Organization.new(input).populate_and_save!
        client.current_space = JDC::Populators::Space.new(input, client.current_organization).populate_and_save!
    end
  end
end

#check_targetObject



79
80
81
82
83
# File 'lib/jdc/cli.rb', line 79

def check_target
  unless client && client.target
    fail "Please select a target with 'jdc target'."
  end
end

#client(target = client_target) ⇒ Object



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
# File 'lib/jdc/cli.rb', line 456

def client(target = client_target)
  return @@client if defined?(@@client) && @@client
  return unless target

  info = target_info(target)
  #token = info[:token] && JFoundry::AuthToken.from_hash(info)

  fail "V1 targets are no longer supported." if info[:version] == 1

  @@client = build_client(target)

  @@client.trace = input[:trace]

  uri = URI.parse(target)
  @@client.log = File.expand_path("#{LOGS_DIR}/#{uri.host}.log")

  info_changed = false
  unless info.key? :version
    info[:version] = @@client.version
    info_changed = true
  end

  unless info.key? :access_key
    info[:access_key] = ENV['ACCESS_KEY'] 
    info_changed = true
  end

  save_target_info(info, target) unless !info_changed

  if @@client.try(:current_user).try(:email) != nil
    unless info.key? :organization
        @@client.current_organization = JDC::Populators::Organization.new(input).populate_and_save!
        @@client.current_space = JDC::Populators::Space.new(input, @@client.current_organization).populate_and_save!
    end
  end

  @@client.current_organization = @@client.organization(info[:organization]) if info[:organization]
  @@client.current_space = @@client.space(info[:space]) if info[:space]

  @@client
rescue JFoundry::InvalidTarget
end

#client_targetObject



386
387
388
389
# File 'lib/jdc/cli.rb', line 386

def client_target
  return File.read(target_file).chomp if File.exists?(target_file)
  sane_target_url(JDC::DEFAULT_API_URL)
end

#color_enabled?Boolean

Returns:

  • (Boolean)


308
309
310
# File 'lib/jdc/cli.rb', line 308

def color_enabled?
  input[:color]
end

#debug?Boolean

Returns:

  • (Boolean)


304
305
306
# File 'lib/jdc/cli.rb', line 304

def debug?
  !!input[:debug]
end

#default_actionObject



61
62
63
64
65
66
67
# File 'lib/jdc/cli.rb', line 61

def default_action
  if input[:version]
    line "jdc #{VERSION}"
  else
    super
  end
end

#ensure_config_dirObject



391
392
393
394
# File 'lib/jdc/cli.rb', line 391

def ensure_config_dir
  config = File.expand_path(JDC::CONFIG_DIR)
  FileUtils.mkdir_p(config) unless File.exist? config
end

#err(msg, status = 1) ⇒ Object



339
340
341
342
# File 'lib/jdc/cli.rb', line 339

def err(msg, status = 1)
  $stderr.puts c(msg, :error)
  exit_status status
end

#execute(cmd, argv, global = {}) ⇒ Object



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

def execute(cmd, argv, global = {})
  if input[:help]
    invoke :help, :command => cmd.name.to_s
  else
    wrap_errors do
      @command = cmd
      precondition if respond_to? :precondition

      save_token_if_it_changes do
        super
      end
    end
  end
end

#fail(msg) ⇒ Object

Raises:



344
345
346
# File 'lib/jdc/cli.rb', line 344

def fail(msg)
  raise UserError, msg
end

#fail_unknown(display, name) ⇒ Object



506
507
508
# File 'lib/jdc/cli.rb', line 506

def fail_unknown(display, name)
  fail("Unknown #{display} '#{name}'.")
end

#force?Boolean

Returns:

  • (Boolean)


300
301
302
# File 'lib/jdc/cli.rb', line 300

def force?
  input[:force]
end

#formatted_exception_output(e, msg) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/jdc/cli.rb', line 206

def formatted_exception_output(e, msg)
  log_error(e)
  msg << "\nYou can get #{JDC::CRASH_FILE} # for more details"
  err msg

  raise if debug?
end

#helpObject



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/jdc/cli.rb', line 132

def help
  if name = input[:command]
    if cmd = @@commands[name.gsub("-", "_").to_sym]
      Mothership::Help.command_help(cmd)
    else
      unknown_command(name)
    end
  elsif Help.has_groups?
    puts "#{help_header}"

    Mothership::Help.print_help_groups(@@global, true)
  else
    Mothership::Help.basic_help(@@commands, @@global)
  end
end

#help_headerObject



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/jdc/cli.rb', line 148

def help_header
<<EOS
Jing Dong Foundry Command Line Interface, version [#{JDC::VERSION}]
  Use 'jdc help [command]' for command details.
  For docs and support visit http://appengine.jd.com/help/jdc.html

USAGE EXAMPLES
  $ jdc push                         <-- deploys app to current app space on current target
  $ jdc apps                         <-- list the current apps you pushed

EOS
end

#invalidate_clientObject



451
452
453
454
# File 'lib/jdc/cli.rb', line 451

def invalidate_client
  @@client = nil
  client
end

#log_error(e) ⇒ Object



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
# File 'lib/jdc/cli.rb', line 257

def log_error(e)
  ensure_config_dir

  msg = e.class.name
  msg << ": #{e}" unless e.to_s.empty?

  crash_file = File.expand_path(JDC::CRASH_FILE)

  FileUtils.mkdir_p(File.dirname(crash_file))

  File.open(crash_file, "w") do |f|
    f.puts "Time of crash:"
    f.puts "  #{Time.now}"
    f.puts ""
    f.puts msg
    f.puts ""

    if e.respond_to?(:request_trace)
      f.puts "<<<"
      f.puts e.request_trace
    end

    if e.respond_to?(:response_trace)
      f.puts e.response_trace
      f.puts ">>>"
      f.puts ""
    end

    jdc_dir = File.expand_path("../../../..", __FILE__) + "/"
    e.backtrace.each do |loc|
      if loc =~ /\/gems\//
        f.puts loc.sub(/.*\/gems\//, "")
      else
        f.puts loc.sub(jdc_dir, "")
      end
    end
  end
end

#name_list(xs) ⇒ Object



354
355
356
357
358
359
360
# File 'lib/jdc/cli.rb', line 354

def name_list(xs)
  if xs.empty?
    d("none")
  else
    xs.collect { |x| c(x.name, :name) }.join(", ")
  end
end

#normalize_targets_info(info_by_url) ⇒ Object



419
420
421
422
423
424
425
# File 'lib/jdc/cli.rb', line 419

def normalize_targets_info(info_by_url)
  info_by_url.reduce({}) do |hash, pair|
    key, value = pair
    hash[key] = value.is_a?(String) ? { :token => value } : value
    hash
  end
end

#one_of(*paths) ⇒ Object



377
378
379
380
381
382
383
384
# File 'lib/jdc/cli.rb', line 377

def one_of(*paths)
  paths.each do |p|
    exp = File.expand_path(p)
    return exp if File.exist? exp
  end

  File.expand_path(paths.first)
end

#quiet?Boolean

Returns:

  • (Boolean)


296
297
298
# File 'lib/jdc/cli.rb', line 296

def quiet?
  input[:quiet]
end

#remove_target_info(target = client_target) ⇒ Object



445
446
447
448
449
# File 'lib/jdc/cli.rb', line 445

def remove_target_info(target = client_target)
  ts = targets_info
  ts.delete target
  save_targets(ts)
end

#sane_target_url(url) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/jdc/cli.rb', line 362

def sane_target_url(url)
  unless url =~ /^https?:\/\//
    begin
      #TCPSocket.new(url, Net::HTTP.https_default_port)
      #url = "https://#{url}"
      TCPSocket.new(url, Net::HTTP.http_default_port)
      url = "http://#{url}"
    rescue Errno::ECONNREFUSED, SocketError, Timeout::Error
      url = "http://#{url}"
    end
  end

  url.gsub(/\/$/, "")
end

#save_target_info(info, target = client_target) ⇒ Object



439
440
441
442
443
# File 'lib/jdc/cli.rb', line 439

def save_target_info(info, target = client_target)
  ts = targets_info
  ts[target] = info
  save_targets(ts)
end

#save_targets(ts) ⇒ Object



431
432
433
434
435
436
437
# File 'lib/jdc/cli.rb', line 431

def save_targets(ts)
  ensure_config_dir

  File.open(File.expand_path(JDC::TOKENS_FILE), "w") do |io|
    YAML.dump(ts, io)
  end
end

#save_token_if_it_changesObject



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/jdc/cli.rb', line 235

def save_token_if_it_changes
  return yield unless client
  yield
=begin
  return yield unless client && client.token

  before_token = client.token

  yield

  after_token = client.token

  return unless after_token

  if before_token != after_token
    info = target_info
    info[:token] = after_token.auth_header
    save_target_info(info)
  end
=end
end

#set_target(url) ⇒ Object



396
397
398
399
400
401
402
403
404
# File 'lib/jdc/cli.rb', line 396

def set_target(url)
  ensure_config_dir

  File.open(File.expand_path(JDC::TARGET_FILE), "w") do |f|
    f.write(sane_target_url(url))
  end

  invalidate_client
end

#table(headers, rows) ⇒ Object



348
349
350
351
352
# File 'lib/jdc/cli.rb', line 348

def table(headers, rows)
  tabular(
    !quiet? && headers.collect { |h| h && b(h) },
    *rows)
end

#target_info(target = client_target) ⇒ Object



427
428
429
# File 'lib/jdc/cli.rb', line 427

def target_info(target = client_target)
  targets_info[target] || {}
end

#targets_infoObject



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/jdc/cli.rb', line 406

def targets_info
  new_toks = File.expand_path(JDC::TOKENS_FILE)

  info =
    if File.exist? new_toks
      YAML.load_file(new_toks)
    end

  info ||= {}

  normalize_targets_info(info)
end

#user_colorsObject



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/jdc/cli.rb', line 316

def user_colors
  return @user_colors if @user_colors

  colors = File.expand_path(COLORS_FILE)

  @user_colors = super.dup

  # most terminal schemes are stupid, so use cyan instead
  @user_colors.each do |k, v|
    if v == :blue
      @user_colors[k] = :cyan
    end
  end

  if File.exists?(colors)
    YAML.load_file(colors).each do |k, v|
      @user_colors[k.to_sym] = v.to_sym
    end
  end

  @user_colors
end

#verbose?Boolean

Returns:

  • (Boolean)


312
313
314
# File 'lib/jdc/cli.rb', line 312

def verbose?
  input[:verbose]
end

#wrap_errorsObject



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
# File 'lib/jdc/cli.rb', line 161

def wrap_errors
  yield
rescue JFoundry::Timeout => e
  err(e.message)
rescue Interrupt
  exit_status 130
rescue Mothership::Error
  raise
rescue UserError => e
  log_error(e)
  err e.message
rescue SystemExit
  raise
rescue UserFriendlyError => e
  err e.message
=begin
rescue JFoundry::InvalidAuthToken => e
  line
  line c("Invalid authentication token. Try logging in again with 'cf login'. If problems continue, please contact your Cloud Operator.", :warning)
rescue JFoundry::Forbidden => e
  if !$cf_asked_auth
    $cf_asked_auth = true

    line
    line c("Not authenticated! Try logging in:", :warning)

    # TODO: there's no color here; global flags not being passed
    # through (mothership bug?)
    invoke :login

    retry
  end

  log_error(e)

  err "Denied: #{e.description}"
=end
rescue JFoundry::StagingError => e
  message = "Application failed to stage"
  formatted_exception_output(e, message)

rescue Exception => e
  formatted_exception_output(e, add_exception_name_to_msg(e))
end