4 require 'rbot/messagemapper'
6 unless YAML.respond_to?(:load_file)
7 def YAML.load_file( filepath )
8 File.open( filepath ) do |f|
15 # allow the definition order to be preserved so that sorting by
16 # definition order is possible. The BotConfigWizard does this to allow
17 # the :wizard questions to be in a sensible order.
23 attr_reader :requires_restart
25 def initialize(key, params)
26 # Keys must be in the form 'module.name'.
27 # They will be internally passed around as symbols,
28 # but we accept them both in string and symbol form.
29 unless key.to_s =~ /^.+\..+$/
30 raise ArgumentError,"key must be of the form 'module.name'"
35 if params.has_key? :default
36 @default = params[:default]
41 @type = params[:type] || String
42 @on_change = params[:on_change]
43 @validate = params[:validate]
44 @wizard = params[:wizard]
45 @requires_restart = params[:requires_restart]
48 if @default.instance_of?(Proc)
55 return BotConfig.config[@key] if BotConfig.config.has_key?(@key)
59 def set(value, on_change = true)
60 BotConfig.config[@key] = value
61 @on_change.call(BotConfig.bot, value) if on_change && @on_change
64 BotConfig.config.delete(@key)
67 # set string will raise ArgumentErrors on failed parse/validate
68 def set_string(string, on_change = true)
73 raise ArgumentError, "invalid value: #{string}"
77 # override this. the default will work for strings only
88 return true unless @validate
89 if @validate.instance_of?(Proc)
90 return @validate.call(value)
91 elsif @validate.instance_of?(Regexp)
92 raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
93 return @validate.match(value)
95 raise ArgumentError, "validation type #{@validate.class} not supported"
100 class BotConfigStringValue < BotConfigValue
102 class BotConfigBooleanValue < BotConfigValue
104 return true if string == "true"
105 return false if string == "false"
106 raise ArgumentError, "#{string} does not match either 'true' or 'false'"
109 class BotConfigIntegerValue < BotConfigValue
111 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
115 class BotConfigFloatValue < BotConfigValue
117 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
121 class BotConfigArrayValue < BotConfigValue
129 class BotConfigEnumValue < BotConfigValue
130 def initialize(key, params)
132 @values = params[:values]
135 if @values.instance_of?(Proc)
136 return @values.call(BotConfig.bot)
142 unless values.include?(string)
143 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
148 "#{@desc} [valid values are: " + values.join(", ") + "]"
152 # container for bot configuration
154 # Array of registered BotConfigValues for defaults, types and help
159 # Hash containing key => value pairs for lookup and serialisation
160 @@config = Hash.new(false)
168 def BotConfig.register(item)
169 unless item.kind_of?(BotConfigValue)
170 raise ArgumentError,"item must be a BotConfigValue"
172 @@items[item.key] = item
175 # currently we store values in a hash but this could be changed in the
176 # future. We use hash semantics, however.
177 # components that register their config keys and setup defaults are
180 return @@items[key].value if @@items.has_key?(key)
181 return @@items[key.intern].value if @@items.has_key?(key.intern)
182 # try to still support unregistered lookups
183 # but warn about them
184 if @@config.has_key?(key)
185 warning "Unregistered lookup #{key.inspect}"
188 if @@config.has_key?(key.intern)
189 warning "Unregistered lookup #{key.intern.inspect}"
190 return @@config[key.intern]
195 # TODO should I implement this via BotConfigValue or leave it direct?
196 # def []=(key, value)
199 # pass everything else through to the hash
200 def method_missing(method, *args, &block)
201 return @@config.send(method, *args, &block)
204 def handle_list(m, params)
207 @@items.each_key do |key|
208 mod, name = key.split('.')
209 next unless mod == params[:module]
210 modules.push key unless modules.include?(name)
213 m.reply "no such module #{params[:module]}"
215 m.reply modules.join(", ")
218 @@items.each_key do |key|
219 name = key.to_s.split('.').first
220 modules.push name unless modules.include?(name)
222 m.reply "modules: " + modules.join(", ")
226 def handle_get(m, params)
227 key = params[:key].to_s.intern
228 unless @@items.has_key?(key)
229 m.reply "no such config key #{key}"
232 value = @@items[key].to_s
233 m.reply "#{key}: #{value}"
236 def handle_desc(m, params)
237 key = params[:key].to_s.intern
238 unless @@items.has_key?(key)
239 m.reply "no such config key #{key}"
241 puts @@items[key].inspect
242 m.reply "#{key}: #{@@items[key].desc}"
245 def handle_unset(m, params)
246 key = params[:key].to_s.intern
247 unless @@items.has_key?(key)
248 m.reply "no such config key #{key}"
251 handle_get(m, params)
254 def handle_set(m, params)
255 key = params[:key].to_s.intern
256 value = params[:value].to_s
257 unless @@items.has_key?(key)
258 m.reply "no such config key #{key}"
262 @@items[key].set_string(value)
263 rescue ArgumentError => e
264 m.reply "failed to set #{key}: #{e.message}"
267 if @@items[key].requires_restart
268 m.reply "this config change will take effect on the next restart"
274 def handle_help(m, params)
275 topic = params[:topic]
278 m.reply "config module - bot configuration. usage: list, desc, get, set, unset"
280 m.reply "config list => list configuration modules, config list <module> => list configuration keys for module <module>"
282 m.reply "config get <key> => get configuration value for key <key>"
284 m.reply "reset key <key> to the default"
286 m.reply "config set <key> <value> => set configuration value for key <key> to <value>"
288 m.reply "config desc <key> => describe what key <key> configures"
290 m.reply "no help for config #{topic}"
294 m.reply "incorrect usage, try '#{@@bot.nick}: help config'"
297 # bot:: parent bot class
298 # create a new config hash from #{botclass}/conf.rbot
302 # respond to config messages, to provide runtime configuration
312 @handler = MessageMapper.new(self)
313 @handler.map 'config list :module', :action => 'handle_list',
314 :defaults => {:module => false}
315 @handler.map 'config get :key', :action => 'handle_get'
316 @handler.map 'config desc :key', :action => 'handle_desc'
317 @handler.map 'config describe :key', :action => 'handle_desc'
318 @handler.map 'config set :key *value', :action => 'handle_set'
319 @handler.map 'config unset :key', :action => 'handle_unset'
320 @handler.map 'config help :topic', :action => 'handle_help',
321 :defaults => {:topic => false}
322 @handler.map 'help config :topic', :action => 'handle_help',
323 :defaults => {:topic => false}
325 if(File.exist?("#{@@bot.botclass}/conf.yaml"))
327 newconfig = YAML::load_file("#{@@bot.botclass}/conf.yaml")
328 newconfig.each { |key, val|
329 @@config[key.intern] = val
333 error "failed to read conf.yaml: #{$!}"
336 # if we got here, we need to run the first-run wizard
337 BotConfigWizard.new(@@bot).run
338 # save newly created config
342 # write current configuration to #{botclass}/conf.yaml
345 debug "Writing new conf.yaml ..."
346 File.open("#{@@bot.botclass}/conf.yaml.new", "w") do |file|
348 @@config.each { |key, val|
349 savehash[key.to_s] = val
351 file.puts savehash.to_yaml
353 debug "Officializing conf.yaml ..."
354 File.rename("#{@@bot.botclass}/conf.yaml.new",
355 "#{@@bot.botclass}/conf.yaml")
357 error "failed to write configuration file conf.yaml! #{$!}"
358 error "#{e.class}: #{e}"
359 error e.backtrace.join("\n")
368 class BotConfigWizard
371 @questions = BotConfig.items.values.find_all {|i| i.wizard }
375 puts "First time rbot configuration wizard"
376 puts "===================================="
377 puts "This is the first time you have run rbot with a config directory of:"
379 puts "This wizard will ask you a few questions to get you started."
380 puts "The rest of rbot's configuration can be manipulated via IRC once"
381 puts "rbot is connected and you are auth'd."
382 puts "-----------------------------------"
384 return unless @questions
385 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
388 print q.key.to_s + " [#{q.to_s}]: "
389 response = STDIN.gets
391 unless response.empty?
392 q.set_string response, false
394 puts "configured #{q.key} => #{q.to_s}"
395 puts "-----------------------------------"
396 rescue ArgumentError => e
397 puts "failed to set #{q.key}: #{e.message}"