Class: WavefrontCli::OptHandler

Inherits:
Object
  • Object
show all
Includes:
Constants
Defined in:
lib/wavefront-cli/opt_handler.rb

Overview

Options to commands can come from three sources, with the following order of precedence: program defaults, a configuration file, and command-line options. Docopt is not well suited to this, as it will “fill in” any missing options with defaults, producing a single hash which must be merged with values from the config file. Assuming we give the command-line higher precedence, a default value, not supplied by the user, will override a value in the config file. The other way round, and you can’t override anything in the config file from the command-line. I think this behaviour is far from unique to Docopt.

So, we have a hash of defaults, and we do the merging ourselves, in this class. We trick Docopt into not using the defaults by avoiding the magic string ‘default: ’ in our options stanzas.

Constant Summary

Constants included from Constants

Constants::ALL_PAGE_SIZE, Constants::DEFAULT_CONFIG, Constants::DEFAULT_OPTS, Constants::HUMAN_TIME_FORMAT, Constants::HUMAN_TIME_FORMAT_MS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cli_opts = {}) ⇒ OptHandler



28
29
30
31
32
33
34
35
36
# File 'lib/wavefront-cli/opt_handler.rb', line 28

def initialize(cli_opts = {})
  cred_opts = setup_cred_opts(cli_opts)
  cli_opts.reject! { |_k, v| v.nil? }
  @opts = DEFAULT_OPTS.merge(load_profile(cred_opts)).merge(cli_opts)
rescue WavefrontCli::Exception::ConfigFileNotFound => e
  abort "Configuration file '#{e}' not found."
rescue Wavefront::Exception::InvalidConfigFile => e
  abort "Could not load configuration file '#{e.message}'."
end

Instance Attribute Details

#optsObject (readonly)

Returns the value of attribute opts.



26
27
28
# File 'lib/wavefront-cli/opt_handler.rb', line 26

def opts
  @opts
end

Instance Method Details

#load_profile(cred_opts) ⇒ Hash

Load credentials (and other config) using the SDK Credentials class. This allows the user to override values with environment variables



68
69
70
71
# File 'lib/wavefront-cli/opt_handler.rb', line 68

def load_profile(cred_opts)
  creds = Wavefront::Credentials.new(cred_opts).config
  Hash[creds.map { |k, v| [k.to_sym, v] }]
end

#setup_cred_opts(cli_opts) ⇒ Hash

Create an options hash to pass to the Wavefront::Credentials constructor.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/wavefront-cli/opt_handler.rb', line 45

def setup_cred_opts(cli_opts)
  cred_opts = {}

  if cli_opts[:config]
    cred_opts[:file] = Pathname.new(cli_opts[:config])

    unless cred_opts[:file].exist?
      raise WavefrontCli::Exception::ConfigFileNotFound, cred_opts[:file]
    end
  end

  cred_opts[:profile] = cli_opts[:profile] if cli_opts[:profile]
  cred_opts
end