Class: UniParser

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

Overview

Simple and straightforward config & cli options parser Based on ruby-parseconfig class by BJ Dierkes <[email protected]> github.com/datafolklabs/ruby-parseconfig

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_file = nil) ⇒ UniParser

Returns a new instance of UniParser.



14
15
16
17
18
19
20
21
22
23
# File 'lib/uniparser.rb', line 14

def initialize(config_file = nil)
      self.config_file = config_file

      self.groups = []
      self.cli = Hash[:free => ARGV]
      self.config = Hash[]
      self.merged = Hash[]
      self.params = Hash[:cli => self.cli, :config => self.config, :merged => self.merged]
      self.cli_desc = Array.new
end

Instance Attribute Details

Returns the value of attribute banner.



12
13
14
# File 'lib/uniparser.rb', line 12

def banner
  @banner
end

#cliObject

Returns the value of attribute cli.



12
13
14
# File 'lib/uniparser.rb', line 12

def cli
  @cli
end

#cli_descObject

Returns the value of attribute cli_desc.



12
13
14
# File 'lib/uniparser.rb', line 12

def cli_desc
  @cli_desc
end

#configObject

Returns the value of attribute config.



12
13
14
# File 'lib/uniparser.rb', line 12

def config
  @config
end

#config_fileObject

Returns the value of attribute config_file.



12
13
14
# File 'lib/uniparser.rb', line 12

def config_file
  @config_file
end

#delimObject

Returns the value of attribute delim.



12
13
14
# File 'lib/uniparser.rb', line 12

def delim
  @delim
end

#groupsObject

Returns the value of attribute groups.



12
13
14
# File 'lib/uniparser.rb', line 12

def groups
  @groups
end

#mergedObject

Returns the value of attribute merged.



12
13
14
# File 'lib/uniparser.rb', line 12

def merged
  @merged
end

#paramsObject

Returns the value of attribute params.



12
13
14
# File 'lib/uniparser.rb', line 12

def params
  @params
end

Instance Method Details

#[](param) ⇒ Object



192
193
194
# File 'lib/uniparser.rb', line 192

def [](param)
      return self.params[param]
end

#add(param_name, value) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/uniparser.rb', line 204

def add(param_name, value)
      if value.class == Hash
            if self.config.has_key?(param_name)
                  if self.config[:"#{param_name}"].class == Hash
                        self.config[:"#{param_name}"].merge!(value)
                  elsif self.config.has_key?(param_name)
                        if self.config[:"#{param_name}"].class != value.class
                              raise ArgumentError, "#{param_name} already exists, and is of different type!"
                        end
                  end
            else
                  self.config[:"#{param_name}"] = value
            end
            if ! self.groups.include?(param_name)
                  self.groups.push(param_name)
            end
      else
            self.config[:"#{param_name}"] = value
      end
end

#add_to_group(group, param_name, value) ⇒ Object



225
226
227
228
229
230
# File 'lib/uniparser.rb', line 225

def add_to_group(group, param_name, value)
      if ! self.groups.include?(group)
            self.add(group, {})
      end
      self.config[:"#{group}"][:"#{param_name}"] = value
end

#bound_cli(opt_name, opt_index) ⇒ Object



78
79
80
81
# File 'lib/uniparser.rb', line 78

def bound_cli(opt_name, opt_index)
      return nil if opt_index >= self.cli[:free].size
      self.cli[:"#{opt_name}"] = self.cli[:free][opt_index]
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


257
258
259
# File 'lib/uniparser.rb', line 257

def eql?(other)
      self.params == other.params && self.groups == other.groups
end

#get_groupsObject



200
201
202
# File 'lib/uniparser.rb', line 200

def get_groups()
      return self.groups
end

#get_paramsObject



196
197
198
# File 'lib/uniparser.rb', line 196

def get_params()
      return self.params.keys
end

#get_value(param) ⇒ Object



186
187
188
189
190
# File 'lib/uniparser.rb', line 186

def get_value(param)
      puts "ParseConfig Deprecation Warning: get_value() is deprecated. Use " + \
      "config['param'] or config['group']['param'] instead."
      return self.params[param]
end

#import_configObject



141
142
143
144
145
146
147
148
149
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
181
182
183
184
# File 'lib/uniparser.rb', line 141

def import_config()
      # The config is top down.. anything after a [group] gets added as part
      # of that group until a new [group] is found.
      group = nil
      open(self.config_file) { |f| f.each_with_index do |line, i|
            line.strip!

            # force_encoding not available in all versions of ruby
            begin
                  if i.eql? 0 and line.include?("\xef\xbb\xbf".force_encoding("UTF-8"))
                        line.delete!("\xef\xbb\xbf".force_encoding("UTF-8"))
                  end
            rescue NoMethodError
            end

            unless (/^\#/.match(line))
                  if(/\s*=\s*/.match(line))
                        param, value = line.split(/\s*=\s*/, 2)
                        var_name = "#{param}".chomp.strip
                        value = value.chomp.strip
                        new_value = ''
                        if (value)
                              if value =~ /^['"](.*)['"]$/
                                    new_value = $1
                              else
                                    new_value = value
                              end
                        else
                              new_value = ''
                        end

                        if group
                              self.add_to_group(group, var_name, new_value)
                        else
                              self.add(var_name, new_value)
                        end

                  elsif(/^\[(.+)\]$/.match(line).to_a != [])
                        group = /^\[(.+)\]$/.match(line).to_a[1]
                        self.add(group, {})
                  end
            end
      end }
end

#parse_all(config_file = nil, cli = ARGV) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/uniparser.rb', line 25

def parse_all(config_file = nil, cli = ARGV)
      config_file = self.config_file if self.config_file != nil
      return nil if config_file == nil
      self.config_file = config_file

      self.cli[:free] = cli

      self.parse_file(config_file)
      self.parse_cli([], nil)
      #self.merge()
end

#parse_cli(names, desc, next_is_val = true, merge_with = nil) ⇒ Object



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
# File 'lib/uniparser.rb', line 47

def parse_cli(names, desc, next_is_val = true, merge_with = nil)
      merge = lambda { |val|
            # FIXME: add dynamic hash merging
            if merge_with.size == 1
                  self.merged[:"#{merge_with[0]}"] = self.cli[:"#{gsub_param}"]
            else
                  self.merged[:"#{merge_with[0]}"] = Hash[] if self.merged[:"#{merge_with[0]}"].class.to_s != "Hash"
                  self.merged[:"#{merge_with[0]}"][:"#{merge_with[1]}"] = val
            end
      }
      merge.call( self.config[:"#{merge_with[0]}"][:"#{merge_with[1]}"] ) if merge_with != nil

      self.cli_desc.push ( Array[names, desc, next_is_val] ) if names.size != 0
      return nil if self.cli[:free].size == 0

      self.cli[:free].each_with_index do |param, index|
            next if not names.include? param

            gsub_param = names[1].gsub(/^-+/, "")
            if next_is_val
                  self.cli[:"#{gsub_param}"] = self.cli[:free][index + 1]
                  self.cli[:free].delete_at( index + 1 )
            else
                  self.cli[:"#{gsub_param}"] = true
            end
            self.cli[:free].delete_at(index)

            merge.call( self.cli[:"#{gsub_param}"] ) if merge_with != nil
      end
end

#parse_file(config_file = nil) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/uniparser.rb', line 37

def parse_file(config_file = nil)
      config_file = self.config_file if self.config_file != nil
      return nil if config_file == nil
      self.config_file = config_file

      self.validate_config
      self.import_config
      #self.merge()
end

#show_banner(sort = false) ⇒ Object



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/uniparser.rb', line 109

def show_banner(sort = false)
      puts "#{self.banner}\n\n" if self.banner

      out = Array.new
      out_desc = Array.new
      str_len = 0
      self.cli_desc.sort! if sort

      self.cli_desc.each do |arr|
            all_names = ""
            names = arr[0]
            desc = arr[1]
            next_is_val = arr[2]

            names.each {|name| all_names += name.ljust(7) }
            all_names += "  [value]" if next_is_val
            str_len = all_names.size if all_names.size > str_len

            out.push(all_names)
            out_desc.push(desc)
      end
      out.each_with_index {|str, index| print "".ljust(5); print "#{str.ljust(str_len*2)}#{out_desc[index]}\n" }
end

#types(val) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/uniparser.rb', line 83

def types(val)
      return nil if val == nil

      if val.class.to_s == "Hash"
            val.each do |h_var, h_val|
                  val[h_var] = self.types(h_val) # recursion rocks!
            end
            return val
      end

      case val
      when /^[0-9]+$/
            val = val.to_i
      when /^true$/
            val = true
      when /^false$/
            val = false
      end

      return val
end

#types!Object



105
106
107
# File 'lib/uniparser.rb', line 105

def types!()
      self.params.each {|var, val| self.params[var] = self.types(val) }
end

#validate_configObject



133
134
135
136
137
138
139
# File 'lib/uniparser.rb', line 133

def validate_config()
      unless File.readable?(self.config_file)
            raise Errno::EACCES, "#{self.config_file} is not readable"
      end

      # FIXME: need to validate contents/structure?
end

#write(output_stream = STDOUT, quoted = true) ⇒ Object



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

def write(output_stream=STDOUT, quoted=true)
      self.params.each do |name,value|
            if value.class.to_s != 'Hash'
                  if quoted == true
                        output_stream.puts "#{name} = \"#{value}\""
                  else
                        output_stream.puts "#{name} = #{value}"
                  end
            end
      end
      output_stream.puts "\n"

      self.groups.each do |group|
            output_stream.puts "[#{group}]"
            self.params[group].each do |param, value|
                  if quoted == true
                        output_stream.puts "#{param} = \"#{value}\""
                  else
                        output_stream.puts "#{param} = #{value}"
                  end
            end
            output_stream.puts "\n"
      end
end