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 params.has_key? :default
44 @default = params[:default]
49 @type = params[:type] || String
50 @on_change = params[:on_change]
51 @validate = params[:validate]
52 @wizard = params[:wizard]
53 @requires_restart = params[:requires_restart]
54 @requires_rescan = params[:requires_rescan]
55 @auth_path = "config::key::#{key.sub('.','::')}"
58 if @default.instance_of?(Proc)
65 return @manager.config[@key] if @manager.config.has_key?(@key)
69 def set(value, on_change = true)
70 @manager.config[@key] = value
71 @manager.changed = true
72 @on_change.call(@manager.bot, value) if on_change && @on_change
75 @manager.config.delete(@key)
76 @manager.changed = true
77 @on_change.call(@manager.bot, value) if @on_change
80 # set string will raise ArgumentErrors on failed parse/validate
81 def set_string(string, on_change = true)
86 raise ArgumentError, "invalid value: #{string}"
90 # override this. the default will work for strings only
101 return true unless @validate
102 if @validate.instance_of?(Proc)
103 return @validate.call(value)
104 elsif @validate.instance_of?(Regexp)
105 raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
106 return @validate.match(value)
108 raise ArgumentError, "validation type #{@validate.class} not supported"
113 class StringValue < Value
116 class BooleanValue < Value
118 return true if string == "true"
119 return false if string == "false"
120 if string =~ /^-?\d+$/
121 return string.to_i != 0
123 raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
127 if r.kind_of?(Integer)
135 class IntegerValue < Value
137 return 1 if string == "true"
138 return 0 if string == "false"
139 raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
144 if r.kind_of?(Integer)
152 class FloatValue < Value
154 raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
159 class ArrayValue < Value
168 set(curval + [val]) unless curval.include?(val)
172 raise ArgumentError, "value #{val} not present" unless curval.include?(val)
177 class EnumValue < Value
178 def initialize(key, params)
180 @values = params[:values]
183 if @values.instance_of?(Proc)
184 return @values.call(@manager.bot)
190 unless values.include?(string)
191 raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
196 _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
200 # container for bot configuration
208 attr_accessor :changed
211 bot_associate(nil,true)
216 @config = Hash.new(false)
219 # Associate with bot _bot_
220 def bot_associate(bot, reset=false)
221 reset_config if reset
226 if(File.exist?("#{@bot.botclass}/conf.yaml"))
228 newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
229 newconfig.each { |key, val|
230 @config[key.to_sym] = val
234 error "failed to read conf.yaml: #{$!}"
237 # if we got here, we need to run the first-run wizard
239 # save newly created config
245 unless item.kind_of?(Value)
246 raise ArgumentError,"item must be an Irc::Bot::Config::Value"
248 @items[item.key] = item
251 # currently we store values in a hash but this could be changed in the
252 # future. We use hash semantics, however.
253 # components that register their config keys and setup defaults are
256 # return @items[key].value if @items.has_key?(key)
257 return @items[key.to_sym].value if @items.has_key?(key.to_sym)
258 # try to still support unregistered lookups
259 # but warn about them
260 # if @config.has_key?(key)
261 # warning "Unregistered lookup #{key.inspect}"
262 # return @config[key]
264 if @config.has_key?(key.to_sym)
265 warning _("Unregistered lookup #{key.to_sym.inspect}")
266 return @config[key.to_sym]
271 # TODO should I implement this via Value or leave it direct?
272 # def []=(key, value)
275 # pass everything else through to the hash
276 def method_missing(method, *args, &block)
277 return @config.send(method, *args, &block)
280 # write current configuration to #{botclass}/conf.yaml
283 debug "Not writing conf.yaml (unchanged)"
287 debug "Writing new conf.yaml ..."
288 File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
290 @config.each { |key, val|
291 savehash[key.to_s] = val
293 file.puts savehash.to_yaml
295 debug "Officializing conf.yaml ..."
296 File.rename("#{@bot.botclass}/conf.yaml.new",
297 "#{@bot.botclass}/conf.yaml")
300 error "failed to write configuration file conf.yaml! #{$!}"
301 error "#{e.class}: #{e}"
302 error e.backtrace.join("\n")
307 # Returns the only Irc::Bot::Config::ManagerClass
310 return ManagerClass.instance
313 # Register a config value
314 def Config.register(item)
315 Config.manager.register(item)
321 @manager = Config.manager
322 @questions = @manager.items.values.find_all {|i| i.wizard }
326 puts _("First time rbot configuration wizard")
327 puts "===================================="
328 puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
329 puts _("This wizard will ask you a few questions to get you started.")
330 puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
331 puts "-----------------------------------"
333 return unless @questions
334 @questions.sort{|a,b| a.order <=> b.order }.each do |q|
337 print q.key.to_s + " [#{q.to_s}]: "
338 response = STDIN.gets
340 unless response.empty?
341 q.set_string response, false
343 puts _("configured #{q.key} => #{q.to_s}")
344 puts "-----------------------------------"
345 rescue ArgumentError => e
346 puts _("failed to set #{q.key}: #{e.message}")