Class: Falsework::CliConfig

Inherits:
Object
  • Object
show all
Defined in:
lib/falsework/cliconfig.rb

Overview

Load configuration from 3 places (starting from least significant): config file, env variable, command line.

Constant Summary collapse

DIR_CONFIG =

Possible config file locations.

[Pathname.new(Dir.home) + ".#{Meta::NAME}",
Pathname.new('/etc'),
Pathname.new('/usr/etc'),
Pathname.new('/usr/local/etc'),
CliUtils::DIR_LIB_SRC.parent.parent + 'etc']

Instance Method Summary collapse

Constructor Details

#initializeCliConfig

Example:

conf = CliConfig.new conf = 123 conf.load



25
26
27
28
29
30
31
32
33
# File 'lib/falsework/cliconfig.rb', line 25

def initialize
  @conf = Hash.new
  @conf[:verbose] = 0
  @conf[:banner] = "Usage: #{File.basename($0)} [options]"
  @conf[:config_name] = Meta::NAME + '.yaml'
  @conf[:config_env] = Meta::NAME.upcase + '_CONF'
  @conf[:config_dirs] = DIR_CONFIG
  @conf[:cl_parse_in_order] = false
end

Instance Method Details

#[](key) ⇒ Object

Getter for @conf



42
43
44
# File 'lib/falsework/cliconfig.rb', line 42

def [](key)
  @conf[key]
end

#[]=(key, val) ⇒ Object

Setter for @conf



36
37
38
39
# File 'lib/falsework/cliconfig.rb', line 36

def []=(key, val)
  CliUtils.verbose = val if key == :verbose # sync verbosity levels
  @conf[key] = val
end

#getConfigPathObject

Return a full path to a config file or nil if no config file found.



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/falsework/cliconfig.rb', line 47

def getConfigPath
  if @conf[:config_name].index('/')
    return @conf[:config_name] if File.file?(@conf[:config_name])
  else 
    @conf[:config_dirs].each {|i|
      r = Pathname.new(i) + @conf[:config_name]
      return r if File.file?(r)
    }
  end

  CliUtils.warnx "config file '#{@conf[:config_name]}' not found" if @conf[:verbose] >= 2
  return nil
end

#load(reqOpts = [], argv = ARGV, &block) ⇒ Object

Parse CLO, env variables and load config file.

reqOpts

an array of requied options

&block

a optional block for OptionParser



137
138
139
140
141
# File 'lib/falsework/cliconfig.rb', line 137

def load(reqOpts = [], argv = ARGV, &block)
  optParse(argv, &block)
  loadFile
  requiredOptions?(reqOpts)
end

#loadFileObject

Load a config from file. Return true on success or false otherwise.



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/falsework/cliconfig.rb', line 62

def loadFile
  file = getConfigPath
  return false unless file

  CliUtils::veputs(2, "Loading #{File.basename(file)}... " + CliUtils::NNL_MARK)
  myconf = YAML.load_file(file) rescue CliUtils.errx(EX_CONFIG, "cannot parse config #{file}: #{$!}")
  # preserve existing values
  @conf.merge!(myconf) {|key, oldval, newval| oldval }
  CliUtils::veputs 2, "OK"
  return true
end

#optParse(argv) ⇒ Object

Parse CLO and env variable. If block is given it is passed with OptionParser object as a parameter.



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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/falsework/cliconfig.rb', line 85

def optParse argv
  OptionParser.new do |o|
    o.on('-v', 'Be more verbose.') { |i|
      self[:verbose] += 1
    }
    o.on('-V', '--version', 'Show version & exit.') { |i|
      puts Meta::VERSION
      exit EX_OK
    }
    o.on('--config NAME',
         "Set a config name or file",
         "(default is #{@conf[:config_name]}).") {|arg|
      @conf[:config_name] = arg
    }
    o.on('--config-dirs', 'Show possible config locations.') {
      mark = false
      @conf[:config_dirs].each { |idx|
        f = Pathname(idx) + @conf[:config_name]
        if File.file?(f) && !mark
          puts "* #{f}"
          mark = true
        else
          puts "  #{f}"
        end
      }
      exit EX_OK
    }

    yield o if block_given?
    o.banner = @conf[:banner]

    env = nil
    env = ENV[@conf[:config_env]].shellsplit if ENV.key?(@conf[:config_env])

    begin
      [env, argv].each { |i|
        if @conf[:cl_parse_in_order]
          o.order!(i) if i
        else
          o.parse!(i) if i
        end
      }
    rescue
      CliUtils.errx EX_USAGE, $!.to_s
    end
  end
end

#requiredOptions?(opts) ⇒ Boolean

Check if options in array opts are in @conf.

Returns:

  • (Boolean)


75
76
77
78
79
80
81
# File 'lib/falsework/cliconfig.rb', line 75

def requiredOptions?(opts)
  opts.each {|idx|
    if !@conf.key?(idx) || !@conf[idx]
      CliUtils.errx EX_CONFIG, "option '#{idx}' is either nil or missing"
    end
  }
end