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 :store_default
28 attr_reader :requires_restart
29 attr_reader :requires_rescan
32 attr_reader :auth_path
33 def initialize(key, params)
34 @manager = Config.manager
35 # Keys must be in the form 'module.name'.
36 # They will be internally passed around as symbols,
37 # but we accept them both in string and symbol form.
38 unless key.to_s =~ /^.+\..+$/
39 raise ArgumentError,"key must be of the form 'module.name'"
44 if @manager.overrides.key?(@key)
45 @default = @manager.overrides[@key]
46 elsif params.has_key? :default
47 @default = params[:default]
52 @type = params[:type] || String
53 @on_change = params[:on_change]
54 @validate = params[:validate]
55 @wizard = params[:wizard]
56 @store_default = params[:store_default]
57 @requires_restart = params[:requires_restart]
58 @requires_rescan = params[:requires_rescan]
59 @auth_path = "config::key::#{key.sub('.','::')}"
62 if @default.instance_of?(Proc)
69 return @manager.config[@key] if @manager.config.has_key?(@key)
73 def set(value, on_change = true)
74 @manager.config[@key] = value
75 @manager.changed = true
76 @on_change.call(@manager.bot, value) if on_change && @on_change
80 @manager.config.delete(@key)
81 @manager.changed = true
82 @on_change.call(@manager.bot, value) if @on_change
86 # set string will raise ArgumentErrors on failed parse/validate
87 def set_string(string, on_change = true)
92 raise ArgumentError, "invalid value: #{string}"
96 # override this. the default will work for strings only
106 def validate(val, validator = @validate)
111 return validator.call(val)
113 raise ArgumentError, "validation via Regexp only supported for strings!" unless String === val
114 return validator.match(val)
116 raise ArgumentError, "validation type #{validator.class} not supported"
121 class StringValue < Value
124 class BooleanValue < Value
126 return true if string == "true"
127 return false if string == "false"
128 if string =~ /^-?\d+$/
129 return string.to_i != 0
131 raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
135 if r.kind_of?(Integer)
143 class IntegerValue < Value
145 return 1 if string == "true"
146 return 0 if string == "false"
147 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
152 if r.kind_of?(Integer)
160 class FloatValue < Value
162 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
167 class ArrayValue < Value
168 def initialize(key, params)
170 @validate_item = params[:validate_item]
171 @validate ||= Proc.new do |v|
172 !v.find { |i| !validate_item(i) }
176 def validate_item(item)
177 validate(item, @validate_item)
187 newval = self.get.dup
188 unless newval.include? val
190 validate_item(val) or raise ArgumentError, "invalid item: #{val}"
191 validate(newval) or raise ArgumentError, "invalid value: #{newval.inspect}"
197 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
202 class EnumValue < Value
203 def initialize(key, params)
205 @values = params[:values]
208 if @values.instance_of?(Proc)
209 return @values.call(@manager.bot)
215 unless values.include?(string)
216 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
221 _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
225 # container for bot configuration
233 attr_reader :overrides
234 attr_accessor :changed
237 bot_associate(nil,true)
242 @config = Hash.new(false)
244 # We allow default values for config keys to be overridden by
245 # the config file /etc/rbot.conf
246 # The main purpose for this is to allow distro or system-wide
247 # settings such as external program paths (figlet, toilet, ispell)
248 # to be set once for all the bots.
249 @overrides = Hash.new
250 etcfile = "/etc/rbot.conf"
251 if File.exist?(etcfile)
252 log "Loading defaults from #{etcfile}"
253 etcconf = YAML::load_file(etcfile)
254 etcconf.each { |k, v|
255 @overrides[k.to_sym] = v
260 # Associate with bot _bot_
261 def bot_associate(bot, reset=false)
262 reset_config if reset
267 conf = @bot.path 'conf.yaml'
270 newconfig = YAML::load_file conf
271 newconfig.each { |key, val|
272 @config[key.to_sym] = val
276 error "failed to read conf.yaml: #{$!}"
279 # config options with :store_default to true should store
280 # their default value at first run.
281 # Some defaults might change anytime the bot starts
282 # for instance core.db or authpw
283 @items.values.find_all {|i| i.store_default }.each do |value|
284 @config[value.key] = value.default
287 # if we got here, we need to run the first-run wizard
289 # save newly created config
295 unless item.kind_of?(Value)
296 raise ArgumentError,"item must be an Irc::Bot::Config::Value"
298 @items[item.key] = item
301 # currently we store values in a hash but this could be changed in the
302 # future. We use hash semantics, however.
303 # components that register their config keys and setup defaults are
306 # return @items[key].value if @items.has_key?(key)
307 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
308 # try to still support unregistered lookups
309 # but warn about them
310 # if @config.has_key?(key)
311 # warning "Unregistered lookup #{key.inspect}"
312 # return @config[key]
314 if @config.has_key?(key.to_sym)
315 warning _("Unregistered lookup #{key.to_sym.inspect}")
316 return @config[key.to_sym]
322 return @items[key.to_sym].set(value) if @items.has_key?(key.to_sym)
323 if @config.has_key?(key.to_sym)
324 warning _("Unregistered lookup #{key.to_sym.inspect}")
325 return @config[key.to_sym] = value
329 # pass everything else through to the hash
330 def method_missing(method, *args, &block)
331 return @config.send(method, *args, &block)
334 # write current configuration to #{botclass}/conf.yaml
337 debug "Not writing conf.yaml (unchanged)"
341 conf = @bot.path 'conf.yaml'
343 debug "Writing new conf.yaml ..."
344 File.open(fnew, "w") do |file|
346 @config.each { |key, val|
347 savehash[key.to_s] = val
349 file.puts savehash.to_yaml
351 debug "Officializing conf.yaml ..."
352 File.rename(fnew, conf)
355 error "failed to write configuration file conf.yaml! #{$!}"
356 error "#{e.class}: #{e}"
357 error e.backtrace.join("\n")
362 # Returns the only Irc::Bot::Config::ManagerClass
365 return ManagerClass.instance
368 # Register a config value
369 def Config.register(item)
370 Config.manager.register(item)
376 @manager = Config.manager
377 @questions = @manager.items.values.find_all {|i| i.wizard }
382 puts _("First time rbot configuration wizard")
383 puts "===================================="
384 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
385 puts _("This wizard will ask you a few questions to get you started.")
386 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
387 puts "-----------------------------------"
389 return unless @questions
390 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
393 print q.key.to_s + " [#{q.to_s}]: "
394 response = STDIN.gets
396 unless response.empty?
397 q.set_string response, false
399 puts _("configured #{q.key} => #{q.to_s}")
400 puts "-----------------------------------"
401 rescue ArgumentError => e
402 puts _("failed to set #{q.key}: #{e.message}")