]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/config.rb
Use symbols internally instead of strings for config keys.
[user/henk/code/ruby/rbot.git] / lib / rbot / config.rb
1 module Irc
2
3   require 'yaml'
4   require 'rbot/messagemapper'
5
6   unless YAML.respond_to?(:load_file)
7       def YAML.load_file( filepath )
8         File.open( filepath ) do |f|
9           YAML::load( f )
10         end
11       end
12   end
13
14   class BotConfigValue
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.
18     @@order = 0
19     attr_reader :type
20     attr_reader :desc
21     attr_reader :key
22     attr_reader :wizard
23     attr_reader :requires_restart
24     attr_reader :order
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'"
31       end
32       @order = @@order
33       @@order += 1
34       @key = key.intern
35       if params.has_key? :default
36         @default = params[:default]
37       else
38         @default = false
39       end
40       @desc = params[:desc]
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]
46     end
47     def default
48       if @default.instance_of?(Proc)
49         @default.call
50       else
51         @default
52       end
53     end
54     def get
55       return BotConfig.config[@key] if BotConfig.config.has_key?(@key)
56       return @default
57     end
58     alias :value :get
59     def set(value, on_change = true)
60       BotConfig.config[@key] = value
61       @on_change.call(BotConfig.bot, value) if on_change && @on_change
62     end
63     def unset
64       BotConfig.config.delete(@key)
65     end
66
67     # set string will raise ArgumentErrors on failed parse/validate
68     def set_string(string, on_change = true)
69       value = parse string
70       if validate value
71         set value, on_change
72       else
73         raise ArgumentError, "invalid value: #{string}"
74       end
75     end
76     
77     # override this. the default will work for strings only
78     def parse(string)
79       string
80     end
81
82     def to_s
83       get.to_s
84     end
85
86     private
87     def validate(value)
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)
94       else
95         raise ArgumentError, "validation type #{@validate.class} not supported"
96       end
97     end
98   end
99
100   class BotConfigStringValue < BotConfigValue
101   end
102   class BotConfigBooleanValue < BotConfigValue
103     def parse(string)
104       return true if string == "true"
105       return false if string == "false"
106       raise ArgumentError, "#{string} does not match either 'true' or 'false'"
107     end
108   end
109   class BotConfigIntegerValue < BotConfigValue
110     def parse(string)
111       raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
112       string.to_i
113     end
114   end
115   class BotConfigFloatValue < BotConfigValue
116     def parse(string)
117       raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
118       string.to_f
119     end
120   end
121   class BotConfigArrayValue < BotConfigValue
122     def parse(string)
123       string.split(/,\s+/)
124     end
125     def to_s
126       get.join(", ")
127     end
128   end
129   class BotConfigEnumValue < BotConfigValue
130     def initialize(key, params)
131       super
132       @values = params[:values]
133     end
134     def values
135       if @values.instance_of?(Proc)
136         return @values.call(BotConfig.bot)
137       else
138         return @values
139       end
140     end
141     def parse(string)
142       unless values.include?(string)
143         raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
144       end
145       string
146     end
147     def desc
148       "#{@desc} [valid values are: " + values.join(", ") + "]"
149     end
150   end
151
152   # container for bot configuration
153   class BotConfig
154     # Array of registered BotConfigValues for defaults, types and help
155     @@items = Hash.new
156     def BotConfig.items
157       @@items
158     end
159     # Hash containing key => value pairs for lookup and serialisation
160     @@config = Hash.new(false)
161     def BotConfig.config
162       @@config
163     end
164     def BotConfig.bot
165       @@bot
166     end
167     
168     def BotConfig.register(item)
169       unless item.kind_of?(BotConfigValue)
170         raise ArgumentError,"item must be a BotConfigValue"
171       end
172       @@items[item.key] = item
173     end
174
175     # currently we store values in a hash but this could be changed in the
176     # future. We use hash semantics, however.
177     # components that register their config keys and setup defaults are
178     # supported via []
179     def [](key)
180       return @@items[key].value if @@items.has_key?(key)
181       return @@items[key.intern].value if @@items.has_key?(key.intern)
182       # try to still support unregistered lookups
183       # but warn about them
184       if @@config.has_key?(key)
185         warning "Unregistered lookup #{key.inspect}"
186         return @@config[key]
187       end
188       if @@config.has_key?(key.intern)
189         warning "Unregistered lookup #{key.intern.inspect}"
190         return @@config[key.intern]
191       end
192       return false
193     end
194
195     # TODO should I implement this via BotConfigValue or leave it direct?
196     #    def []=(key, value)
197     #    end
198     
199     # pass everything else through to the hash
200     def method_missing(method, *args, &block)
201       return @@config.send(method, *args, &block)
202     end
203
204     def handle_list(m, params)
205       modules = []
206       if params[:module]
207         @@items.each_key do |key|
208           mod, name = key.split('.')
209           next unless mod == params[:module]
210           modules.push key unless modules.include?(name)
211         end
212         if modules.empty?
213           m.reply "no such module #{params[:module]}"
214         else
215           m.reply modules.join(", ")
216         end
217       else
218         @@items.each_key do |key|
219           name = key.to_s.split('.').first
220           modules.push name unless modules.include?(name)
221         end
222         m.reply "modules: " + modules.join(", ")
223       end
224     end
225
226     def handle_get(m, params)
227       key = params[:key].to_s.intern
228       unless @@items.has_key?(key)
229         m.reply "no such config key #{key}"
230         return
231       end
232       value = @@items[key].to_s
233       m.reply "#{key}: #{value}"
234     end
235
236     def handle_desc(m, params)
237       key = params[:key].to_s.intern
238       unless @@items.has_key?(key)
239         m.reply "no such config key #{key}"
240       end
241       puts @@items[key].inspect
242       m.reply "#{key}: #{@@items[key].desc}"
243     end
244
245     def handle_unset(m, params)
246       key = params[:key].to_s.intern
247       unless @@items.has_key?(key)
248         m.reply "no such config key #{key}"
249       end
250       @@items[key].unset
251       handle_get(m, params)
252     end
253
254     def handle_set(m, params)
255       key = params[:key].to_s.intern
256       value = params[:value].to_s
257       unless @@items.has_key?(key)
258         m.reply "no such config key #{key}"
259         return
260       end
261       begin
262         @@items[key].set_string(value)
263       rescue ArgumentError => e
264         m.reply "failed to set #{key}: #{e.message}"
265         return
266       end
267       if @@items[key].requires_restart
268         m.reply "this config change will take effect on the next restart"
269       else
270         m.okay
271       end
272     end
273
274     def handle_help(m, params)
275       topic = params[:topic]
276       case topic
277       when false
278         m.reply "config module - bot configuration. usage: list, desc, get, set, unset"
279       when "list"
280         m.reply "config list => list configuration modules, config list <module> => list configuration keys for module <module>"
281       when "get"
282         m.reply "config get <key> => get configuration value for key <key>"
283       when "unset"
284         m.reply "reset key <key> to the default"
285       when "set"
286         m.reply "config set <key> <value> => set configuration value for key <key> to <value>"
287       when "desc"
288         m.reply "config desc <key> => describe what key <key> configures"
289       else
290         m.reply "no help for config #{topic}"
291       end
292     end
293     def usage(m,params)
294       m.reply "incorrect usage, try '#{@@bot.nick}: help config'"
295     end
296
297     # bot:: parent bot class
298     # create a new config hash from #{botclass}/conf.rbot
299     def initialize(bot)
300       @@bot = bot
301
302       # respond to config messages, to provide runtime configuration
303       # management
304       # messages will be:
305       #  get
306       #  set
307       #  unset
308       #  desc
309       #  and for arrays:
310       #    add TODO
311       #    remove TODO
312       @handler = MessageMapper.new(self)
313       @handler.map 'config list :module', :action => 'handle_list',
314                    :defaults => {:module => false}
315       @handler.map 'config get :key', :action => 'handle_get'
316       @handler.map 'config desc :key', :action => 'handle_desc'
317       @handler.map 'config describe :key', :action => 'handle_desc'
318       @handler.map 'config set :key *value', :action => 'handle_set'
319       @handler.map 'config unset :key', :action => 'handle_unset'
320       @handler.map 'config help :topic', :action => 'handle_help',
321                    :defaults => {:topic => false}
322       @handler.map 'help config :topic', :action => 'handle_help',
323                    :defaults => {:topic => false}
324       
325       if(File.exist?("#{@@bot.botclass}/conf.yaml"))
326         begin
327           newconfig = YAML::load_file("#{@@bot.botclass}/conf.yaml")
328           newconfig.each { |key, val|
329             @@config[key.intern] = val
330           }
331           return
332         rescue
333           error "failed to read conf.yaml: #{$!}"
334         end
335       end
336       # if we got here, we need to run the first-run wizard
337       BotConfigWizard.new(@@bot).run
338       # save newly created config
339       save
340     end
341
342     # write current configuration to #{botclass}/conf.yaml
343     def save
344       begin
345         debug "Writing new conf.yaml ..."
346         File.open("#{@@bot.botclass}/conf.yaml.new", "w") do |file|
347           savehash = {}
348           @@config.each { |key, val|
349             savehash[key.to_s] = val
350           }
351           file.puts savehash.to_yaml
352         end
353         debug "Officializing conf.yaml ..."
354         File.rename("#{@@bot.botclass}/conf.yaml.new",
355                     "#{@@bot.botclass}/conf.yaml")
356       rescue => e
357         error "failed to write configuration file conf.yaml! #{$!}"
358         error "#{e.class}: #{e}"
359         error e.backtrace.join("\n")
360       end
361     end
362
363     def privmsg(m)
364       @handler.handle(m)
365     end
366   end
367
368   class BotConfigWizard
369     def initialize(bot)
370       @bot = bot
371       @questions = BotConfig.items.values.find_all {|i| i.wizard }
372     end
373     
374     def run()
375       puts "First time rbot configuration wizard"
376       puts "===================================="
377       puts "This is the first time you have run rbot with a config directory of:"
378       puts @bot.botclass
379       puts "This wizard will ask you a few questions to get you started."
380       puts "The rest of rbot's configuration can be manipulated via IRC once"
381       puts "rbot is connected and you are auth'd."
382       puts "-----------------------------------"
383
384       return unless @questions
385       @questions.sort{|a,b| a.order <=> b.order }.each do |q|
386         puts q.desc
387         begin
388           print q.key.to_s + " [#{q.to_s}]: "
389           response = STDIN.gets
390           response.chop!
391           unless response.empty?
392             q.set_string response, false
393           end
394           puts "configured #{q.key} => #{q.to_s}"
395           puts "-----------------------------------"
396         rescue ArgumentError => e
397           puts "failed to set #{q.key}: #{e.message}"
398           retry
399         end
400       end
401     end
402   end
403 end