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 @manager.overrides.key?(@key)
44 @default = @manager.overrides[@key]
45 elsif params.has_key? :default
46 @default = params[:default]
51 @type = params[:type] || String
52 @on_change = params[:on_change]
53 @validate = params[:validate]
54 @wizard = params[:wizard]
55 @requires_restart = params[:requires_restart]
56 @requires_rescan = params[:requires_rescan]
57 @auth_path = "config::key::#{key.sub('.','::')}"
60 if @default.instance_of?(Proc)
67 return @manager.config[@key] if @manager.config.has_key?(@key)
71 def set(value, on_change = true)
72 @manager.config[@key] = value
73 @manager.changed = true
74 @on_change.call(@manager.bot, value) if on_change && @on_change
78 @manager.config.delete(@key)
79 @manager.changed = true
80 @on_change.call(@manager.bot, value) if @on_change
84 # set string will raise ArgumentErrors on failed parse/validate
85 def set_string(string, on_change = true)
90 raise ArgumentError, "invalid value: #{string}"
94 # override this. the default will work for strings only
104 def validate(val, validator = @validate)
109 return validator.call(val)
111 raise ArgumentError, "validation via Regexp only supported for strings!" unless String === val
112 return validator.match(val)
114 raise ArgumentError, "validation type #{validator.class} not supported"
119 class StringValue < Value
122 class BooleanValue < Value
124 return true if string == "true"
125 return false if string == "false"
126 if string =~ /^-?\d+$/
127 return string.to_i != 0
129 raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
133 if r.kind_of?(Integer)
141 class IntegerValue < Value
143 return 1 if string == "true"
144 return 0 if string == "false"
145 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
150 if r.kind_of?(Integer)
158 class FloatValue < Value
160 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
165 class ArrayValue < Value
166 def initialize(key, params)
168 @validate_item = params[:validate_item]
169 @validate ||= Proc.new do |v|
170 !v.find { |i| !validate_item(i) }
174 def validate_item(item)
175 validate(item, @validate_item)
185 newval = self.get.dup
186 unless newval.include? val
188 validate_item(val) or raise ArgumentError, "invalid item: #{val}"
189 validate(newval) or raise ArgumentError, "invalid value: #{newval.to_s}"
195 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
200 class EnumValue < Value
201 def initialize(key, params)
203 @values = params[:values]
206 if @values.instance_of?(Proc)
207 return @values.call(@manager.bot)
213 unless values.include?(string)
214 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
219 _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
223 # container for bot configuration
231 attr_reader :overrides
232 attr_accessor :changed
235 bot_associate(nil,true)
240 @config = Hash.new(false)
242 # We allow default values for config keys to be overridden by
243 # the config file /etc/rbot.conf
244 # The main purpose for this is to allow distro or system-wide
245 # settings such as external program paths (figlet, toilet, ispell)
246 # to be set once for all the bots.
247 @overrides = Hash.new
248 etcfile = "/etc/rbot.conf"
249 if File.exist?(etcfile)
250 log "Loading defaults from #{etcfile}"
251 etcconf = YAML::load_file(etcfile)
252 etcconf.each { |k, v|
253 @overrides[k.to_sym] = v
258 # Associate with bot _bot_
259 def bot_associate(bot, reset=false)
260 reset_config if reset
265 if(File.exist?("#{@bot.botclass}/conf.yaml"))
267 newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
268 newconfig.each { |key, val|
269 @config[key.to_sym] = val
273 error "failed to read conf.yaml: #{$!}"
276 # if we got here, we need to run the first-run wizard
278 # save newly created config
284 unless item.kind_of?(Value)
285 raise ArgumentError,"item must be an Irc::Bot::Config::Value"
287 @items[item.key] = item
290 # currently we store values in a hash but this could be changed in the
291 # future. We use hash semantics, however.
292 # components that register their config keys and setup defaults are
295 # return @items[key].value if @items.has_key?(key)
296 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
297 # try to still support unregistered lookups
298 # but warn about them
299 # if @config.has_key?(key)
300 # warning "Unregistered lookup #{key.inspect}"
301 # return @config[key]
303 if @config.has_key?(key.to_sym)
304 warning _("Unregistered lookup #{key.to_sym.inspect}")
305 return @config[key.to_sym]
311 return @items[key.to_sym].set(value) if @items.has_key?(key.to_sym)
312 if @config.has_key?(key.to_sym)
313 warning _("Unregistered lookup #{key.to_sym.inspect}")
314 return @config[key.to_sym] = value
318 # pass everything else through to the hash
319 def method_missing(method, *args, &block)
320 return @config.send(method, *args, &block)
323 # write current configuration to #{botclass}/conf.yaml
326 debug "Not writing conf.yaml (unchanged)"
330 debug "Writing new conf.yaml ..."
331 File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
333 @config.each { |key, val|
334 savehash[key.to_s] = val
336 file.puts savehash.to_yaml
338 debug "Officializing conf.yaml ..."
339 File.rename("#{@bot.botclass}/conf.yaml.new",
340 "#{@bot.botclass}/conf.yaml")
343 error "failed to write configuration file conf.yaml! #{$!}"
344 error "#{e.class}: #{e}"
345 error e.backtrace.join("\n")
350 # Returns the only Irc::Bot::Config::ManagerClass
353 return ManagerClass.instance
356 # Register a config value
357 def Config.register(item)
358 Config.manager.register(item)
364 @manager = Config.manager
365 @questions = @manager.items.values.find_all {|i| i.wizard }
370 puts _("First time rbot configuration wizard")
371 puts "===================================="
372 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
373 puts _("This wizard will ask you a few questions to get you started.")
374 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
375 puts "-----------------------------------"
377 return unless @questions
378 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
381 print q.key.to_s + " [#{q.to_s}]: "
382 response = STDIN.gets
384 unless response.empty?
385 q.set_string response, false
387 puts _("configured #{q.key} => #{q.to_s}")
388 puts "-----------------------------------"
389 rescue ArgumentError => e
390 puts _("failed to set #{q.key}: #{e.message}")