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
130 set(curval + [val]) unless curval.include?(val)
134 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
138 class BotConfigEnumValue < BotConfigValue
139 def initialize(key, params)
141 @values = params[:values]
144 if @values.instance_of?(Proc)
145 return @values.call(BotConfig.bot)
151 unless values.include?(string)
152 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
157 "#{@desc} [valid values are: " + values.join(", ") + "]"
161 # container for bot configuration
163 # Array of registered BotConfigValues for defaults, types and help
168 # Hash containing key => value pairs for lookup and serialisation
169 @@config = Hash.new(false)
177 def BotConfig.register(item)
178 unless item.kind_of?(BotConfigValue)
179 raise ArgumentError,"item must be a BotConfigValue"
181 @@items[item.key] = item
184 # currently we store values in a hash but this could be changed in the
185 # future. We use hash semantics, however.
186 # components that register their config keys and setup defaults are
189 return @@items[key].value if @@items.has_key?(key)
190 return @@items[key.intern].value if @@items.has_key?(key.intern)
191 # try to still support unregistered lookups
192 # but warn about them
193 if @@config.has_key?(key)
194 warning "Unregistered lookup #{key.inspect}"
197 if @@config.has_key?(key.intern)
198 warning "Unregistered lookup #{key.intern.inspect}"
199 return @@config[key.intern]
204 # TODO should I implement this via BotConfigValue or leave it direct?
205 # def []=(key, value)
208 # pass everything else through to the hash
209 def method_missing(method, *args, &block)
210 return @@config.send(method, *args, &block)
213 def handle_list(m, params)
216 @@items.each_key do |key|
217 mod, name = key.to_s.split('.')
218 next unless mod == params[:module]
219 modules.push key unless modules.include?(name)
222 m.reply "no such module #{params[:module]}"
224 m.reply modules.join(", ")
227 @@items.each_key do |key|
228 name = key.to_s.split('.').first
229 modules.push name unless modules.include?(name)
231 m.reply "modules: " + modules.join(", ")
235 def handle_get(m, params)
236 key = params[:key].to_s.intern
237 unless @@items.has_key?(key)
238 m.reply "no such config key #{key}"
241 value = @@items[key].to_s
242 m.reply "#{key}: #{value}"
245 def handle_desc(m, params)
246 key = params[:key].to_s.intern
247 unless @@items.has_key?(key)
248 m.reply "no such config key #{key}"
250 puts @@items[key].inspect
251 m.reply "#{key}: #{@@items[key].desc}"
254 def handle_unset(m, params)
255 key = params[:key].to_s.intern
256 unless @@items.has_key?(key)
257 m.reply "no such config key #{key}"
260 handle_get(m, params)
261 m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
264 def handle_set(m, params)
265 key = params[:key].to_s.intern
266 value = params[:value].join(" ")
267 unless @@items.has_key?(key)
268 m.reply "no such config key #{key}"
272 @@items[key].set_string(value)
273 rescue ArgumentError => e
274 m.reply "failed to set #{key}: #{e.message}"
277 if @@items[key].requires_restart
278 m.reply "this config change will take effect on the next restart"
284 def handle_add(m, params)
285 key = params[:key].to_s.intern
286 value = params[:value]
287 unless @@items.has_key?(key)
288 m.reply "no such config key #{key}"
291 unless @@items[key].class <= BotConfigArrayValue
292 m.reply "config key #{key} is not an array"
296 @@items[key].add(value)
297 rescue ArgumentError => e
298 m.reply "failed to add #{value} to #{key}: #{e.message}"
301 handle_get(m,{:key => key})
302 m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
305 def handle_rm(m, params)
306 key = params[:key].to_s.intern
307 value = params[:value]
308 unless @@items.has_key?(key)
309 m.reply "no such config key #{key}"
312 unless @@items[key].class <= BotConfigArrayValue
313 m.reply "config key #{key} is not an array"
317 @@items[key].rm(value)
318 rescue ArgumentError => e
319 m.reply "failed to remove #{value} from #{key}: #{e.message}"
322 handle_get(m,{:key => key})
323 m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
326 def handle_help(m, params)
327 topic = params[:topic]
330 m.reply "config module - bot configuration. usage: list, desc, get, set, unset, add, rm"
332 m.reply "config list => list configuration modules, config list <module> => list configuration keys for module <module>"
334 m.reply "config get <key> => get configuration value for key <key>"
336 m.reply "reset key <key> to the default"
338 m.reply "config set <key> <value> => set configuration value for key <key> to <value>"
340 m.reply "config desc <key> => describe what key <key> configures"
342 m.reply "config add <value> to <key> => add value <value> to key <key> if <key> is an array"
344 m.reply "config rm <value> from <key> => remove value <value> from key <key> if <key> is an array"
346 m.reply "no help for config #{topic}"
350 m.reply "incorrect usage, try '#{@@bot.nick}: help config'"
353 # bot:: parent bot class
354 # create a new config hash from #{botclass}/conf.rbot
358 # respond to config messages, to provide runtime configuration
368 @handler = MessageMapper.new(self)
369 @handler.map 'config list :module', :action => 'handle_list',
370 :defaults => {:module => false}
371 @handler.map 'config get :key', :action => 'handle_get'
372 @handler.map 'config desc :key', :action => 'handle_desc'
373 @handler.map 'config describe :key', :action => 'handle_desc'
374 @handler.map 'config set :key *value', :action => 'handle_set'
375 @handler.map 'config add :value to :key', :action => 'handle_add'
376 @handler.map 'config rm :value from :key', :action => 'handle_rm'
377 @handler.map 'config del :value from :key', :action => 'handle_rm'
378 @handler.map 'config delete :value from :key', :action => 'handle_rm'
379 @handler.map 'config unset :key', :action => 'handle_unset'
380 @handler.map 'config reset :key', :action => 'handle_unset'
381 @handler.map 'config help :topic', :action => 'handle_help',
382 :defaults => {:topic => false}
383 @handler.map 'help config :topic', :action => 'handle_help',
384 :defaults => {:topic => false}
386 if(File.exist?("#{@@bot.botclass}/conf.yaml"))
388 newconfig = YAML::load_file("#{@@bot.botclass}/conf.yaml")
389 newconfig.each { |key, val|
390 @@config[key.intern] = val
394 error "failed to read conf.yaml: #{$!}"
397 # if we got here, we need to run the first-run wizard
398 BotConfigWizard.new(@@bot).run
399 # save newly created config
403 # write current configuration to #{botclass}/conf.yaml
406 debug "Writing new conf.yaml ..."
407 File.open("#{@@bot.botclass}/conf.yaml.new", "w") do |file|
409 @@config.each { |key, val|
410 savehash[key.to_s] = val
412 file.puts savehash.to_yaml
414 debug "Officializing conf.yaml ..."
415 File.rename("#{@@bot.botclass}/conf.yaml.new",
416 "#{@@bot.botclass}/conf.yaml")
418 error "failed to write configuration file conf.yaml! #{$!}"
419 error "#{e.class}: #{e}"
420 error e.backtrace.join("\n")
429 class BotConfigWizard
432 @questions = BotConfig.items.values.find_all {|i| i.wizard }
436 puts "First time rbot configuration wizard"
437 puts "===================================="
438 puts "This is the first time you have run rbot with a config directory of:"
440 puts "This wizard will ask you a few questions to get you started."
441 puts "The rest of rbot's configuration can be manipulated via IRC once"
442 puts "rbot is connected and you are auth'd."
443 puts "-----------------------------------"
445 return unless @questions
446 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
449 print q.key.to_s + " [#{q.to_s}]: "
450 response = STDIN.gets
452 unless response.empty?
453 q.set_string response, false
455 puts "configured #{q.key} => #{q.to_s}"
456 puts "-----------------------------------"
457 rescue ArgumentError => e
458 puts "failed to set #{q.key}: #{e.message}"