7 unless YAML.respond_to?(:load_file)
8 def YAML.load_file( filepath )
9 File.open( filepath ) do |f|
16 # allow the definition order to be preserved so that sorting by
17 # definition order is possible. The BotConfigWizard does this to allow
18 # the :wizard questions to be in a sensible order.
24 attr_reader :requires_restart
25 attr_reader :requires_rescan
28 attr_reader :auth_path
29 def initialize(key, params)
30 @manager = BotConfig::configmanager
31 # Keys must be in the form 'module.name'.
32 # They will be internally passed around as symbols,
33 # but we accept them both in string and symbol form.
34 unless key.to_s =~ /^.+\..+$/
35 raise ArgumentError,"key must be of the form 'module.name'"
40 if params.has_key? :default
41 @default = params[:default]
46 @type = params[:type] || String
47 @on_change = params[:on_change]
48 @validate = params[:validate]
49 @wizard = params[:wizard]
50 @requires_restart = params[:requires_restart]
51 @requires_rescan = params[:requires_rescan]
52 @auth_path = "config::key::#{key.sub('.','::')}"
55 if @default.instance_of?(Proc)
62 return @manager.config[@key] if @manager.config.has_key?(@key)
66 def set(value, on_change = true)
67 @manager.config[@key] = value
68 @manager.changed = true
69 @on_change.call(@manager.bot, value) if on_change && @on_change
72 @manager.config.delete(@key)
73 @manager.changed = true
74 @on_change.call(@manager.bot, value) if @on_change
77 # set string will raise ArgumentErrors on failed parse/validate
78 def set_string(string, on_change = true)
83 raise ArgumentError, "invalid value: #{string}"
87 # override this. the default will work for strings only
98 return true unless @validate
99 if @validate.instance_of?(Proc)
100 return @validate.call(value)
101 elsif @validate.instance_of?(Regexp)
102 raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
103 return @validate.match(value)
105 raise ArgumentError, "validation type #{@validate.class} not supported"
110 class BotConfigStringValue < BotConfigValue
113 class BotConfigBooleanValue < BotConfigValue
115 return true if string == "true"
116 return false if string == "false"
117 if string =~ /^-?\d+$/
118 return string.to_i != 0
120 raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
124 if r.kind_of?(Integer)
132 class BotConfigIntegerValue < BotConfigValue
134 return 1 if string == "true"
135 return 0 if string == "false"
136 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
141 if r.kind_of?(Integer)
149 class BotConfigFloatValue < BotConfigValue
151 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
156 class BotConfigArrayValue < BotConfigValue
165 set(curval + [val]) unless curval.include?(val)
169 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
174 class BotConfigEnumValue < BotConfigValue
175 def initialize(key, params)
177 @values = params[:values]
180 if @values.instance_of?(Proc)
181 return @values.call(@manager.bot)
187 unless values.include?(string)
188 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
193 _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
197 # container for bot configuration
198 class BotConfigManagerClass
205 attr_accessor :changed
208 bot_associate(nil,true)
213 @config = Hash.new(false)
216 # Associate with bot _bot_
217 def bot_associate(bot, reset=false)
218 reset_config if reset
223 if(File.exist?("#{@bot.botclass}/conf.yaml"))
225 newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
226 newconfig.each { |key, val|
227 @config[key.to_sym] = val
231 error "failed to read conf.yaml: #{$!}"
234 # if we got here, we need to run the first-run wizard
235 BotConfigWizard.new(@bot).run
236 # save newly created config
242 unless item.kind_of?(BotConfigValue)
243 raise ArgumentError,"item must be a BotConfigValue"
245 @items[item.key] = item
248 # currently we store values in a hash but this could be changed in the
249 # future. We use hash semantics, however.
250 # components that register their config keys and setup defaults are
253 # return @items[key].value if @items.has_key?(key)
254 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
255 # try to still support unregistered lookups
256 # but warn about them
257 # if @config.has_key?(key)
258 # warning "Unregistered lookup #{key.inspect}"
259 # return @config[key]
261 if @config.has_key?(key.to_sym)
262 warning _("Unregistered lookup #{key.to_sym.inspect}")
263 return @config[key.to_sym]
268 # TODO should I implement this via BotConfigValue or leave it direct?
269 # def []=(key, value)
272 # pass everything else through to the hash
273 def method_missing(method, *args, &block)
274 return @config.send(method, *args, &block)
277 # write current configuration to #{botclass}/conf.yaml
280 debug "Not writing conf.yaml (unchanged)"
284 debug "Writing new conf.yaml ..."
285 File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
287 @config.each { |key, val|
288 savehash[key.to_s] = val
290 file.puts savehash.to_yaml
292 debug "Officializing conf.yaml ..."
293 File.rename("#{@bot.botclass}/conf.yaml.new",
294 "#{@bot.botclass}/conf.yaml")
297 error "failed to write configuration file conf.yaml! #{$!}"
298 error "#{e.class}: #{e}"
299 error e.backtrace.join("\n")
305 # Returns the only BotConfigManagerClass
307 def BotConfig.configmanager
308 return BotConfigManagerClass.instance
311 # Register a config value
312 def BotConfig.register(item)
313 BotConfig.configmanager.register(item)
317 class BotConfigWizard
320 @manager = BotConfig::configmanager
321 @questions = @manager.items.values.find_all {|i| i.wizard }
325 puts _("First time rbot configuration wizard")
326 puts "===================================="
327 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
328 puts _("This wizard will ask you a few questions to get you started.")
329 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
330 puts "-----------------------------------"
332 return unless @questions
333 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
336 print q.key.to_s + " [#{q.to_s}]: "
337 response = STDIN.gets
339 unless response.empty?
340 q.set_string response, false
342 puts _("configured #{q.key} => #{q.to_s}")
343 puts "-----------------------------------"
344 rescue ArgumentError => e
345 puts _("failed to set #{q.key}: #{e.message}")