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.inspect}"
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 conf = @bot.path 'conf.yaml'
268 newconfig = YAML::load_file conf
269 newconfig.each { |key, val|
270 @config[key.to_sym] = val
274 error "failed to read conf.yaml: #{$!}"
277 # if we got here, we need to run the first-run wizard
279 # save newly created config
285 unless item.kind_of?(Value)
286 raise ArgumentError,"item must be an Irc::Bot::Config::Value"
288 @items[item.key] = item
291 # currently we store values in a hash but this could be changed in the
292 # future. We use hash semantics, however.
293 # components that register their config keys and setup defaults are
296 # return @items[key].value if @items.has_key?(key)
297 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
298 # try to still support unregistered lookups
299 # but warn about them
300 # if @config.has_key?(key)
301 # warning "Unregistered lookup #{key.inspect}"
302 # return @config[key]
304 if @config.has_key?(key.to_sym)
305 warning _("Unregistered lookup #{key.to_sym.inspect}")
306 return @config[key.to_sym]
312 return @items[key.to_sym].set(value) if @items.has_key?(key.to_sym)
313 if @config.has_key?(key.to_sym)
314 warning _("Unregistered lookup #{key.to_sym.inspect}")
315 return @config[key.to_sym] = value
319 # pass everything else through to the hash
320 def method_missing(method, *args, &block)
321 return @config.send(method, *args, &block)
324 # write current configuration to #{botclass}/conf.yaml
327 debug "Not writing conf.yaml (unchanged)"
331 conf = @bot.path 'conf.yaml'
333 debug "Writing new conf.yaml ..."
334 File.open(fnew, "w") do |file|
336 @config.each { |key, val|
337 savehash[key.to_s] = val
339 file.puts savehash.to_yaml
341 debug "Officializing conf.yaml ..."
342 File.rename(fnew, conf)
345 error "failed to write configuration file conf.yaml! #{$!}"
346 error "#{e.class}: #{e}"
347 error e.backtrace.join("\n")
352 # Returns the only Irc::Bot::Config::ManagerClass
355 return ManagerClass.instance
358 # Register a config value
359 def Config.register(item)
360 Config.manager.register(item)
366 @manager = Config.manager
367 @questions = @manager.items.values.find_all {|i| i.wizard }
372 puts _("First time rbot configuration wizard")
373 puts "===================================="
374 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
375 puts _("This wizard will ask you a few questions to get you started.")
376 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
377 puts "-----------------------------------"
379 return unless @questions
380 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
383 print q.key.to_s + " [#{q.to_s}]: "
384 response = STDIN.gets
386 unless response.empty?
387 q.set_string response, false
389 puts _("configured #{q.key} => #{q.to_s}")
390 puts "-----------------------------------"
391 rescue ArgumentError => e
392 puts _("failed to set #{q.key}: #{e.message}")