]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/config.rb
New config commands: reset (synonym for unset), add <...> to <...> and rm <...> from...
[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     def add(val)
129       curval = self.get
130       set(curval + [val]) unless curval.include?(val)
131     end
132     def rm(val)
133       curval = self.get
134       raise ArgumentError, "value #{val} not present" unless curval.include?(val)
135       set(curval - [val])
136     end
137   end
138   class BotConfigEnumValue < BotConfigValue
139     def initialize(key, params)
140       super
141       @values = params[:values]
142     end
143     def values
144       if @values.instance_of?(Proc)
145         return @values.call(BotConfig.bot)
146       else
147         return @values
148       end
149     end
150     def parse(string)
151       unless values.include?(string)
152         raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
153       end
154       string
155     end
156     def desc
157       "#{@desc} [valid values are: " + values.join(", ") + "]"
158     end
159   end
160
161   # container for bot configuration
162   class BotConfig
163     # Array of registered BotConfigValues for defaults, types and help
164     @@items = Hash.new
165     def BotConfig.items
166       @@items
167     end
168     # Hash containing key => value pairs for lookup and serialisation
169     @@config = Hash.new(false)
170     def BotConfig.config
171       @@config
172     end
173     def BotConfig.bot
174       @@bot
175     end
176     
177     def BotConfig.register(item)
178       unless item.kind_of?(BotConfigValue)
179         raise ArgumentError,"item must be a BotConfigValue"
180       end
181       @@items[item.key] = item
182     end
183
184     # currently we store values in a hash but this could be changed in the
185     # future. We use hash semantics, however.
186     # components that register their config keys and setup defaults are
187     # supported via []
188     def [](key)
189       return @@items[key].value if @@items.has_key?(key)
190       return @@items[key.intern].value if @@items.has_key?(key.intern)
191       # try to still support unregistered lookups
192       # but warn about them
193       if @@config.has_key?(key)
194         warning "Unregistered lookup #{key.inspect}"
195         return @@config[key]
196       end
197       if @@config.has_key?(key.intern)
198         warning "Unregistered lookup #{key.intern.inspect}"
199         return @@config[key.intern]
200       end
201       return false
202     end
203
204     # TODO should I implement this via BotConfigValue or leave it direct?
205     #    def []=(key, value)
206     #    end
207     
208     # pass everything else through to the hash
209     def method_missing(method, *args, &block)
210       return @@config.send(method, *args, &block)
211     end
212
213     def handle_list(m, params)
214       modules = []
215       if params[:module]
216         @@items.each_key do |key|
217           mod, name = key.to_s.split('.')
218           next unless mod == params[:module]
219           modules.push key unless modules.include?(name)
220         end
221         if modules.empty?
222           m.reply "no such module #{params[:module]}"
223         else
224           m.reply modules.join(", ")
225         end
226       else
227         @@items.each_key do |key|
228           name = key.to_s.split('.').first
229           modules.push name unless modules.include?(name)
230         end
231         m.reply "modules: " + modules.join(", ")
232       end
233     end
234
235     def handle_get(m, params)
236       key = params[:key].to_s.intern
237       unless @@items.has_key?(key)
238         m.reply "no such config key #{key}"
239         return
240       end
241       value = @@items[key].to_s
242       m.reply "#{key}: #{value}"
243     end
244
245     def handle_desc(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       puts @@items[key].inspect
251       m.reply "#{key}: #{@@items[key].desc}"
252     end
253
254     def handle_unset(m, params)
255       key = params[:key].to_s.intern
256       unless @@items.has_key?(key)
257         m.reply "no such config key #{key}"
258       end
259       @@items[key].unset
260       handle_get(m, params)
261       m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
262     end
263
264     def handle_set(m, params)
265       key = params[:key].to_s.intern
266       value = params[:value].join(" ")
267       unless @@items.has_key?(key)
268         m.reply "no such config key #{key}"
269         return
270       end
271       begin
272         @@items[key].set_string(value)
273       rescue ArgumentError => e
274         m.reply "failed to set #{key}: #{e.message}"
275         return
276       end
277       if @@items[key].requires_restart
278         m.reply "this config change will take effect on the next restart"
279       else
280         m.okay
281       end
282     end
283
284     def handle_add(m, params)
285       key = params[:key].to_s.intern
286       value = params[:value]
287       unless @@items.has_key?(key)
288         m.reply "no such config key #{key}"
289         return
290       end
291       unless @@items[key].class <= BotConfigArrayValue
292         m.reply "config key #{key} is not an array"
293         return
294       end
295       begin
296         @@items[key].add(value)
297       rescue ArgumentError => e
298         m.reply "failed to add #{value} to #{key}: #{e.message}"
299         return
300       end
301       handle_get(m,{:key => key})
302       m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
303     end
304
305     def handle_rm(m, params)
306       key = params[:key].to_s.intern
307       value = params[:value]
308       unless @@items.has_key?(key)
309         m.reply "no such config key #{key}"
310         return
311       end
312       unless @@items[key].class <= BotConfigArrayValue
313         m.reply "config key #{key} is not an array"
314         return
315       end
316       begin
317         @@items[key].rm(value)
318       rescue ArgumentError => e
319         m.reply "failed to remove #{value} from #{key}: #{e.message}"
320         return
321       end
322       handle_get(m,{:key => key})
323       m.reply "this config change will take effect on the next restart" if @@items[key].requires_restart
324     end
325
326     def handle_help(m, params)
327       topic = params[:topic]
328       case topic
329       when false
330         m.reply "config module - bot configuration. usage: list, desc, get, set, unset, add, rm"
331       when "list"
332         m.reply "config list => list configuration modules, config list <module> => list configuration keys for module <module>"
333       when "get"
334         m.reply "config get <key> => get configuration value for key <key>"
335       when "unset"
336         m.reply "reset key <key> to the default"
337       when "set"
338         m.reply "config set <key> <value> => set configuration value for key <key> to <value>"
339       when "desc"
340         m.reply "config desc <key> => describe what key <key> configures"
341       when "add"
342         m.reply "config add <value> to <key> => add value <value> to key <key> if <key> is an array"
343       when "rm"
344         m.reply "config rm <value> from <key> => remove value <value> from key <key> if <key> is an array"
345       else
346         m.reply "no help for config #{topic}"
347       end
348     end
349     def usage(m,params)
350       m.reply "incorrect usage, try '#{@@bot.nick}: help config'"
351     end
352
353     # bot:: parent bot class
354     # create a new config hash from #{botclass}/conf.rbot
355     def initialize(bot)
356       @@bot = bot
357
358       # respond to config messages, to provide runtime configuration
359       # management
360       # messages will be:
361       #  get
362       #  set
363       #  unset
364       #  desc
365       #  and for arrays:
366       #    add TODO
367       #    remove TODO
368       @handler = MessageMapper.new(self)
369       @handler.map 'config list :module', :action => 'handle_list',
370                    :defaults => {:module => false}
371       @handler.map 'config get :key', :action => 'handle_get'
372       @handler.map 'config desc :key', :action => 'handle_desc'
373       @handler.map 'config describe :key', :action => 'handle_desc'
374       @handler.map 'config set :key *value', :action => 'handle_set'
375       @handler.map 'config add :value to :key', :action => 'handle_add'
376       @handler.map 'config rm :value from :key', :action => 'handle_rm'
377       @handler.map 'config del :value from :key', :action => 'handle_rm'
378       @handler.map 'config delete :value from :key', :action => 'handle_rm'
379       @handler.map 'config unset :key', :action => 'handle_unset'
380       @handler.map 'config reset :key', :action => 'handle_unset'
381       @handler.map 'config help :topic', :action => 'handle_help',
382                    :defaults => {:topic => false}
383       @handler.map 'help config :topic', :action => 'handle_help',
384                    :defaults => {:topic => false}
385       
386       if(File.exist?("#{@@bot.botclass}/conf.yaml"))
387         begin
388           newconfig = YAML::load_file("#{@@bot.botclass}/conf.yaml")
389           newconfig.each { |key, val|
390             @@config[key.intern] = val
391           }
392           return
393         rescue
394           error "failed to read conf.yaml: #{$!}"
395         end
396       end
397       # if we got here, we need to run the first-run wizard
398       BotConfigWizard.new(@@bot).run
399       # save newly created config
400       save
401     end
402
403     # write current configuration to #{botclass}/conf.yaml
404     def save
405       begin
406         debug "Writing new conf.yaml ..."
407         File.open("#{@@bot.botclass}/conf.yaml.new", "w") do |file|
408           savehash = {}
409           @@config.each { |key, val|
410             savehash[key.to_s] = val
411           }
412           file.puts savehash.to_yaml
413         end
414         debug "Officializing conf.yaml ..."
415         File.rename("#{@@bot.botclass}/conf.yaml.new",
416                     "#{@@bot.botclass}/conf.yaml")
417       rescue => e
418         error "failed to write configuration file conf.yaml! #{$!}"
419         error "#{e.class}: #{e}"
420         error e.backtrace.join("\n")
421       end
422     end
423
424     def privmsg(m)
425       @handler.handle(m)
426     end
427   end
428
429   class BotConfigWizard
430     def initialize(bot)
431       @bot = bot
432       @questions = BotConfig.items.values.find_all {|i| i.wizard }
433     end
434     
435     def run()
436       puts "First time rbot configuration wizard"
437       puts "===================================="
438       puts "This is the first time you have run rbot with a config directory of:"
439       puts @bot.botclass
440       puts "This wizard will ask you a few questions to get you started."
441       puts "The rest of rbot's configuration can be manipulated via IRC once"
442       puts "rbot is connected and you are auth'd."
443       puts "-----------------------------------"
444
445       return unless @questions
446       @questions.sort{|a,b| a.order <=> b.order }.each do |q|
447         puts q.desc
448         begin
449           print q.key.to_s + " [#{q.to_s}]: "
450           response = STDIN.gets
451           response.chop!
452           unless response.empty?
453             q.set_string response, false
454           end
455           puts "configured #{q.key} => #{q.to_s}"
456           puts "-----------------------------------"
457         rescue ArgumentError => e
458           puts "failed to set #{q.key}: #{e.message}"
459           retry
460         end
461       end
462     end
463   end
464 end