Class: Bosh::Cli::Runner

Inherits:
Object show all
Defined in:
lib/cli/runner.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args, options = {}) ⇒ Runner

Returns a new instance of Runner.

Parameters:

  • args (Array)


22
23
24
25
26
27
28
29
30
31
# File 'lib/cli/runner.rb', line 22

def initialize(args, options = {})
  @args = args
  @options = options.dup

  banner = "Usage: bosh [<options>] <command> [<args>]"
  @option_parser = OptionParser.new(banner)

  Config.colorize = true
  Config.output ||= STDOUT
end

Instance Attribute Details

#argsArray (readonly)

Returns:

  • (Array)


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

def args
  @args
end

#optionsHash (readonly)

Returns:

  • (Hash)


14
15
16
# File 'lib/cli/runner.rb', line 14

def options
  @options
end

Class Method Details

.run(args) ⇒ Object

Parameters:

  • args (Array)


17
18
19
# File 'lib/cli/runner.rb', line 17

def self.run(args)
  new(args).run
end

Instance Method Details

#add_shortcutsObject



197
198
199
200
201
202
203
204
205
# File 'lib/cli/runner.rb', line 197

def add_shortcuts
  {
    "st" => "status",
    "props" => "properties",
    "cck" => "cloudcheck"
  }.each do |short, long|
    @parse_tree[short] = @parse_tree[long]
  end
end

#build_parse_treeObject



182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/cli/runner.rb', line 182

def build_parse_tree
  @parse_tree = ParseTreeNode.new

  Config.commands.each_value do |command|
    p = @parse_tree
    n_kw = command.keywords.size

    command.keywords.each_with_index do |kw, i|
      p[kw] ||= ParseTreeNode.new
      p = p[kw]
      p.command = command if i == n_kw - 1
    end
  end
end

#find_completions(words, node = @parse_tree, index = 0) ⇒ Object

Finds command completions in the parse tree

Parameters:

  • words (Array)

    Completion prefix

  • node (Bosh::Cli::ParseTreeNode) (defaults to: @parse_tree)

    Current parse tree node



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/cli/runner.rb', line 83

def find_completions(words, node = @parse_tree, index = 0)
  word = words[index]

  # exact match and not on the last word
  if node[word] && words.length != index
    find_completions(words, node[word], index + 1)

    # exact match at the last word
  elsif node[word]
    node[word].values

    # find all partial matches
  else
    node.keys.grep(/^#{word}/)
  end
end

#load_pluginsvoid

This method returns an undefined value.

Discover and load CLI plugins from all available gems



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

def load_plugins
  plugins_glob = "bosh/cli/commands/*.rb"

  unless Gem::Specification.respond_to?(:latest_specs) &&
         Gem::Specification.instance_methods.include?(:matches_for_glob)
    say("Cannot load plugins, ".yellow +
        "please run `gem update --system' to ".yellow +
        "update your RubyGems".yellow)
    return
  end

  plugins = Gem::Specification.latest_specs(true).map { |spec|
    spec.matches_for_glob(plugins_glob)
  }.flatten

  plugins.each do |plugin|
    n_commands = Config.commands.size
    gem_dir = Pathname.new(Gem.dir)
    plugin_name = Pathname.new(plugin).relative_path_from(gem_dir)
    begin
      require plugin
    rescue Exception => e
      say("Failed to load plugin #{plugin_name}: #{e.message}".red)
    end
    if Config.commands.size == n_commands
      say(("File #{plugin_name} has been loaded as plugin but it didn't " +
          "contain any commands.\nMake sure this plugin is updated to be " +
          "compatible with BOSH CLI 1.0.").columnize(80).yellow)
    end
  end
end

#parse_global_optionsObject



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

def parse_global_options
  # -v is reserved for verbose but having 'bosh -v' is handy,
  # hence the little hack
  if @args.size == 1 && (@args[0] == "-v" || @args[0] == "--version")
    @args = %w(version)
    return
  end

  opts = @option_parser
  opts.on("-c", "--config FILE", "Override configuration file") do |file|
    @options[:config] = file
  end
  opts.on("-C", "--cache-dir DIR", "Override cache directory") do |dir|
    @options[:cache_dir] = dir
  end
  opts.on("--[no-]color", "Toggle colorized output") do |v|
    Config.colorize = v
  end

  opts.on("-v", "--verbose", "Show additional output") do
    @options[:verbose] = true
  end
  opts.on("-q", "--quiet", "Suppress all output") do
    Config.output = nil
  end
  opts.on("-n", "--non-interactive", "Don't ask for user input") do
    @options[:non_interactive] = true
    Config.colorize = false
  end
  opts.on("-N", "--no-track", "Return Task ID and don't track") do
    @options[:no_track] = true
  end
  opts.on("-t", "--target URL", "Override target") do |target|
    @options[:target] = target
  end
  opts.on("-u", "--user USER", "Override username") do |user|
    @options[:username] = user
  end
  opts.on("-p", "--password PASSWORD", "Override password") do |pass|
    @options[:password] = pass
  end
  opts.on("-d", "--deployment FILE", "Override deployment") do |file|
    @options[:deployment] = file
  end

  @args = @option_parser.order!(@args)
end

#runvoid

This method returns an undefined value.

Find and run CLI command



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

def run
  parse_global_options

  Config.interactive = !@options[:non_interactive]
  Config.cache = Bosh::Cli::Cache.new(@options[:cache_dir])

  load_plugins
  build_parse_tree
  add_shortcuts

  if @args.empty?
    say(usage)
    exit(0)
  end

  command = search_parse_tree(@parse_tree)
  if command.nil? && Config.interactive
    command = try_alias
  end

  if command.nil?
    err("Unknown command: #{@args.join(" ")}")
  end

  command.runner = self
  begin
    exit_code = command.run(@args, @options)
    exit(exit_code)
  rescue OptionParser::ParseError => e
    say(e.message.red)
    say("Usage: bosh #{command.usage_with_params.columnize(60, 7)}")
    if command.has_options?
      say(command.options_summary.indent(7))
    end
  end

rescue OptionParser::ParseError => e
  say(e.message.red)
  say(@option_parser.to_s)
  exit(1)
rescue Bosh::Cli::CliError => e
  say(e.message.red)
  exit(e.exit_code)
end

#search_parse_tree(node) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/cli/runner.rb', line 211

def search_parse_tree(node)
  return nil if node.nil?
  arg = @args.shift

  longer_command = search_parse_tree(node[arg])

  if longer_command.nil?
    @args.unshift(arg) if arg # backtrack if needed
    node.command
  else
    longer_command
  end
end

#try_aliasObject



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

def try_alias
  # Tries to find best match among aliases (possibly multiple words),
  # then unwinds it onto the remaining args and searches parse tree again.
  # Not the most effective algorithm but does the job.
  config = Bosh::Cli::Config.new(@options[:config])
  candidate = []
  best_match = nil
  save_args = @args.dup

  while (arg = @args.shift)
    candidate << arg
    resolved = config.resolve_alias(:cli, candidate.join(" "))
    if best_match && resolved.nil?
      @args.unshift(arg)
      break
    end
    best_match = resolved
  end

  if best_match.nil?
    @args = save_args
    return
  end

  best_match.split(/\s+/).reverse.each do |keyword|
    @args.unshift(keyword)
  end

  search_parse_tree(@parse_tree)
end

#usageObject



207
208
209
# File 'lib/cli/runner.rb', line 207

def usage
  @option_parser.to_s
end