Class: VMC::CLI

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

Direct Known Subclasses

V2CheckCLI

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



443
444
445
# File 'lib/vmc/cli.rb', line 443

def client
  @@client
end

.client=(c) ⇒ Object



447
448
449
# File 'lib/vmc/cli.rb', line 447

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

Instance Method Details

#check_logged_inObject



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/vmc/cli.rb', line 74

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

#check_targetObject



68
69
70
71
72
# File 'lib/vmc/cli.rb', line 68

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

#client(target = client_target) ⇒ Object



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/vmc/cli.rb', line 396

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

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

  @@client =
    case info[:version]
    when 2
      fail "User switching not implemented for v2." if input[:proxy]
      CFoundry::V2::Client.new(target, token)
    when 1
      CFoundry::V1::Client.new(target, token)
    else
      CFoundry::Client.new(target, token)
    end

  @@client.proxy = input[:proxy]
  @@client.http_proxy = input[:http_proxy] || ENV['HTTP_PROXY'] || ENV['http_proxy'] || nil
  @@client.trace = input[:trace]

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

  unless info.key? :version
    info[:version] = @@client.version
    save_target_info(info, target)
  end

  if org = info[:organization]
    @@client.current_organization = @@client.organization(org)
  end

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

  @@client
rescue CFoundry::InvalidTarget
end

#client_targetObject



314
315
316
317
318
# File 'lib/vmc/cli.rb', line 314

def client_target
  if File.exists?(target_file)
    File.read(target_file).chomp
  end
end

#color_enabled?Boolean

Returns:

  • (Boolean)


230
231
232
# File 'lib/vmc/cli.rb', line 230

def color_enabled?
  input[:color]
end

#debug?Boolean

Returns:

  • (Boolean)


226
227
228
# File 'lib/vmc/cli.rb', line 226

def debug?
  !!input[:debug]
end

#default_actionObject



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

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

#ensure_config_dirObject



320
321
322
323
# File 'lib/vmc/cli.rb', line 320

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

#err(msg, status = 1) ⇒ Object



261
262
263
264
# File 'lib/vmc/cli.rb', line 261

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

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



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

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

      save_token_if_it_changes do
        super
      end
    end
  end
end

#fail(msg) ⇒ Object

Raises:



266
267
268
# File 'lib/vmc/cli.rb', line 266

def fail(msg)
  raise UserError, msg
end

#fail_unknown(display, name) ⇒ Object



438
439
440
# File 'lib/vmc/cli.rb', line 438

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

#force?Boolean

Returns:

  • (Boolean)


222
223
224
# File 'lib/vmc/cli.rb', line 222

def force?
  input[:force]
end

#invalidate_clientObject



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

def invalidate_client
  @@client = nil
  client
end

#log_error(e) ⇒ Object



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

def log_error(e)
  ensure_config_dir

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

  crash_file = File.expand_path(VMC::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

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

#name_list(xs) ⇒ Object



276
277
278
279
280
281
282
# File 'lib/vmc/cli.rb', line 276

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

#no_v2Object



383
384
385
# File 'lib/vmc/cli.rb', line 383

def no_v2
  fail "Not implemented for v2." if v2?
end

#normalize_targets_info(info_by_url) ⇒ Object



351
352
353
354
355
356
357
# File 'lib/vmc/cli.rb', line 351

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



305
306
307
308
309
310
311
312
# File 'lib/vmc/cli.rb', line 305

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

#preconditionObject



87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/vmc/cli.rb', line 87

def precondition
  check_target
  check_logged_in

  return unless v2?

  unless client.current_organization
    fail "Please select an organization with 'vmc target --ask-org'."
  end

  unless client.current_space
    fail "Please select a space with 'vmc target --ask-space'."
  end
end

#quiet?Boolean

Returns:

  • (Boolean)


218
219
220
# File 'lib/vmc/cli.rb', line 218

def quiet?
  input[:quiet]
end

#remove_target_info(target = client_target) ⇒ Object



377
378
379
380
381
# File 'lib/vmc/cli.rb', line 377

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

#sane_target_url(url) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/vmc/cli.rb', line 284

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

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

#save_target_info(info, target = client_target) ⇒ Object



371
372
373
374
375
# File 'lib/vmc/cli.rb', line 371

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

#save_targets(ts) ⇒ Object



363
364
365
366
367
368
369
# File 'lib/vmc/cli.rb', line 363

def save_targets(ts)
  ensure_config_dir

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

#save_token_if_it_changesObject



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/vmc/cli.rb', line 161

def save_token_if_it_changes
  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

#set_target(url) ⇒ Object



325
326
327
328
329
330
331
332
333
# File 'lib/vmc/cli.rb', line 325

def set_target(url)
  ensure_config_dir

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

  invalidate_client
end

#table(headers, rows) ⇒ Object



270
271
272
273
274
# File 'lib/vmc/cli.rb', line 270

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

#target_fileObject



297
298
299
# File 'lib/vmc/cli.rb', line 297

def target_file
  one_of(VMC::TARGET_FILE, VMC::OLD_TARGET_FILE)
end

#target_info(target = client_target) ⇒ Object



359
360
361
# File 'lib/vmc/cli.rb', line 359

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

#targets_infoObject



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/vmc/cli.rb', line 335

def targets_info
  new_toks = File.expand_path(VMC::TOKENS_FILE)
  old_toks = File.expand_path(VMC::OLD_TOKENS_FILE)

  info =
    if File.exist? new_toks
      YAML.load_file(new_toks)
    elsif File.exist? old_toks
      MultiJson.load(File.read(old_toks))
    end

  info ||= {}

  normalize_targets_info(info)
end

#tokens_fileObject



301
302
303
# File 'lib/vmc/cli.rb', line 301

def tokens_file
  one_of(VMC::TOKENS_FILE, VMC::OLD_TOKENS_FILE)
end

#user_colorsObject



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/vmc/cli.rb', line 238

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

#v2?Boolean

Returns:

  • (Boolean)


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

def v2?
  client.version == 2
end

#verbose?Boolean

Returns:

  • (Boolean)


234
235
236
# File 'lib/vmc/cli.rb', line 234

def verbose?
  input[:verbose]
end

#wrap_errorsObject



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

def wrap_errors
  yield
rescue CFoundry::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
rescue CFoundry::Forbidden, CFoundry::InvalidAuthToken => e
  if !$vmc_asked_auth
    $vmc_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}"

rescue Exception => e
  log_error(e)

  msg = e.class.name
  msg << ": #{e}" unless e.to_s.empty?
  msg << "\nFor more information, see #{VMC::CRASH_FILE}"
  err msg

  raise if debug?
end