5 unless YAML.respond_to?(:load_file)
6 def YAML.load_file( filepath )
7 File.open( filepath ) do |f|
19 # allow the definition order to be preserved so that sorting by
20 # definition order is possible. The Wizard does this to allow
21 # the :wizard questions to be in a sensible order.
27 attr_reader :requires_restart
28 attr_reader :requires_rescan
31 attr_reader :auth_path
32 def initialize(key, params)
33 @manager = Config.manager
34 # Keys must be in the form 'module.name'.
35 # They will be internally passed around as symbols,
36 # but we accept them both in string and symbol form.
37 unless key.to_s =~ /^.+\..+$/
38 raise ArgumentError,"key must be of the form 'module.name'"
43 if params.has_key? :default
44 @default = params[:default]
49 @type = params[:type] || String
50 @on_change = params[:on_change]
51 @validate = params[:validate]
52 @wizard = params[:wizard]
53 @requires_restart = params[:requires_restart]
54 @requires_rescan = params[:requires_rescan]
55 @auth_path = "config::key::#{key.sub('.','::')}"
58 if @default.instance_of?(Proc)
65 return @manager.config[@key] if @manager.config.has_key?(@key)
69 def set(value, on_change = true)
70 @manager.config[@key] = value
71 @manager.changed = true
72 @on_change.call(@manager.bot, value) if on_change && @on_change
75 @manager.config.delete(@key)
76 @manager.changed = true
77 @on_change.call(@manager.bot, value) if @on_change
80 # set string will raise ArgumentErrors on failed parse/validate
81 def set_string(string, on_change = true)
86 raise ArgumentError, "invalid value: #{string}"
90 # override this. the default will work for strings only
100 def validate(val, validator = @validate)
105 return validator.call(val)
107 raise ArgumentError, "validation via Regexp only supported for strings!" unless String === val
108 return validator.match(val)
110 raise ArgumentError, "validation type #{validator.class} not supported"
115 class StringValue < Value
118 class BooleanValue < Value
120 return true if string == "true"
121 return false if string == "false"
122 if string =~ /^-?\d+$/
123 return string.to_i != 0
125 raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
129 if r.kind_of?(Integer)
137 class IntegerValue < Value
139 return 1 if string == "true"
140 return 0 if string == "false"
141 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
146 if r.kind_of?(Integer)
154 class FloatValue < Value
156 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
161 class ArrayValue < Value
162 def initialize(key, params)
164 @validate_item = params[:validate_item]
165 @validate ||= Proc.new do |v|
166 !v.find { |i| !validate_item(i) }
170 def validate_item(item)
171 validate(item, @validate_item)
181 newval = self.get.dup
182 unless newval.include? val
184 validate_item(val) or raise ArgumentError, "invalid item: #{val}"
185 validate(newval) or raise ArgumentError, "invalid value: #{newval.to_s}"
191 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
196 class EnumValue < Value
197 def initialize(key, params)
199 @values = params[:values]
202 if @values.instance_of?(Proc)
203 return @values.call(@manager.bot)
209 unless values.include?(string)
210 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
215 _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
219 # container for bot configuration
227 attr_accessor :changed
230 bot_associate(nil,true)
235 @config = Hash.new(false)
238 # Associate with bot _bot_
239 def bot_associate(bot, reset=false)
240 reset_config if reset
245 if(File.exist?("#{@bot.botclass}/conf.yaml"))
247 newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
248 newconfig.each { |key, val|
249 @config[key.to_sym] = val
253 error "failed to read conf.yaml: #{$!}"
256 # if we got here, we need to run the first-run wizard
258 # save newly created config
264 unless item.kind_of?(Value)
265 raise ArgumentError,"item must be an Irc::Bot::Config::Value"
267 @items[item.key] = item
270 # currently we store values in a hash but this could be changed in the
271 # future. We use hash semantics, however.
272 # components that register their config keys and setup defaults are
275 # return @items[key].value if @items.has_key?(key)
276 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
277 # try to still support unregistered lookups
278 # but warn about them
279 # if @config.has_key?(key)
280 # warning "Unregistered lookup #{key.inspect}"
281 # return @config[key]
283 if @config.has_key?(key.to_sym)
284 warning _("Unregistered lookup #{key.to_sym.inspect}")
285 return @config[key.to_sym]
290 # TODO should I implement this via Value or leave it direct?
291 # def []=(key, value)
294 # pass everything else through to the hash
295 def method_missing(method, *args, &block)
296 return @config.send(method, *args, &block)
299 # write current configuration to #{botclass}/conf.yaml
302 debug "Not writing conf.yaml (unchanged)"
306 debug "Writing new conf.yaml ..."
307 File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
309 @config.each { |key, val|
310 savehash[key.to_s] = val
312 file.puts savehash.to_yaml
314 debug "Officializing conf.yaml ..."
315 File.rename("#{@bot.botclass}/conf.yaml.new",
316 "#{@bot.botclass}/conf.yaml")
319 error "failed to write configuration file conf.yaml! #{$!}"
320 error "#{e.class}: #{e}"
321 error e.backtrace.join("\n")
326 # Returns the only Irc::Bot::Config::ManagerClass
329 return ManagerClass.instance
332 # Register a config value
333 def Config.register(item)
334 Config.manager.register(item)
340 @manager = Config.manager
341 @questions = @manager.items.values.find_all {|i| i.wizard }
345 puts _("First time rbot configuration wizard")
346 puts "===================================="
347 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
348 puts _("This wizard will ask you a few questions to get you started.")
349 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
350 puts "-----------------------------------"
352 return unless @questions
353 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
356 print q.key.to_s + " [#{q.to_s}]: "
357 response = STDIN.gets
359 unless response.empty?
360 q.set_string response, false
362 puts _("configured #{q.key} => #{q.to_s}")
363 puts "-----------------------------------"
364 rescue ArgumentError => e
365 puts _("failed to set #{q.key}: #{e.message}")