]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/config.rb
* config value hook :on_change wasn't called from unset()
[user/henk/code/ruby/rbot.git] / lib / rbot / config.rb
1 require 'singleton'
2
3 module Irc
4
5   require 'yaml'
6
7   unless YAML.respond_to?(:load_file)
8       def YAML.load_file( filepath )
9         File.open( filepath ) do |f|
10           YAML::load( f )
11         end
12       end
13   end
14
15   class BotConfigValue
16     # allow the definition order to be preserved so that sorting by
17     # definition order is possible. The BotConfigWizard does this to allow
18     # the :wizard questions to be in a sensible order.
19     @@order = 0
20     attr_reader :type
21     attr_reader :desc
22     attr_reader :key
23     attr_reader :wizard
24     attr_reader :requires_restart
25     attr_reader :requires_rescan
26     attr_reader :order
27     attr_reader :manager
28     attr_reader :auth_path
29     def initialize(key, params)
30       @manager = BotConfig::configmanager
31       # Keys must be in the form 'module.name'.
32       # They will be internally passed around as symbols,
33       # but we accept them both in string and symbol form.
34       unless key.to_s =~ /^.+\..+$/
35         raise ArgumentError,"key must be of the form 'module.name'"
36       end
37       @order = @@order
38       @@order += 1
39       @key = key.to_sym
40       if params.has_key? :default
41         @default = params[:default]
42       else
43         @default = false
44       end
45       @desc = params[:desc]
46       @type = params[:type] || String
47       @on_change = params[:on_change]
48       @validate = params[:validate]
49       @wizard = params[:wizard]
50       @requires_restart = params[:requires_restart]
51       @requires_rescan = params[:requires_rescan]
52       @auth_path = "config::key::#{key.sub('.','::')}"
53     end
54     def default
55       if @default.instance_of?(Proc)
56         @default.call
57       else
58         @default
59       end
60     end
61     def get
62       return @manager.config[@key] if @manager.config.has_key?(@key)
63       return @default
64     end
65     alias :value :get
66     def set(value, on_change = true)
67       @manager.config[@key] = value
68       @manager.changed = true
69       @on_change.call(@manager.bot, value) if on_change && @on_change
70     end
71     def unset
72       @manager.config.delete(@key)
73       @manager.changed = true
74       @on_change.call(@manager.bot, value) if @on_change
75     end
76
77     # set string will raise ArgumentErrors on failed parse/validate
78     def set_string(string, on_change = true)
79       value = parse string
80       if validate value
81         set value, on_change
82       else
83         raise ArgumentError, "invalid value: #{string}"
84       end
85     end
86
87     # override this. the default will work for strings only
88     def parse(string)
89       string
90     end
91
92     def to_s
93       get.to_s
94     end
95
96     private
97     def validate(value)
98       return true unless @validate
99       if @validate.instance_of?(Proc)
100         return @validate.call(value)
101       elsif @validate.instance_of?(Regexp)
102         raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
103         return @validate.match(value)
104       else
105         raise ArgumentError, "validation type #{@validate.class} not supported"
106       end
107     end
108   end
109
110   class BotConfigStringValue < BotConfigValue
111   end
112
113   class BotConfigBooleanValue < BotConfigValue
114     def parse(string)
115       return true if string == "true"
116       return false if string == "false"
117       raise ArgumentError, "#{string} does not match either 'true' or 'false'"
118     end
119   end
120
121   class BotConfigIntegerValue < BotConfigValue
122     def parse(string)
123       raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
124       string.to_i
125     end
126   end
127
128   class BotConfigFloatValue < BotConfigValue
129     def parse(string)
130       raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
131       string.to_f
132     end
133   end
134
135   class BotConfigArrayValue < BotConfigValue
136     def parse(string)
137       string.split(/,\s+/)
138     end
139     def to_s
140       get.join(", ")
141     end
142     def add(val)
143       curval = self.get
144       set(curval + [val]) unless curval.include?(val)
145     end
146     def rm(val)
147       curval = self.get
148       raise ArgumentError, "value #{val} not present" unless curval.include?(val)
149       set(curval - [val])
150     end
151   end
152
153   class BotConfigEnumValue < BotConfigValue
154     def initialize(key, params)
155       super
156       @values = params[:values]
157     end
158     def values
159       if @values.instance_of?(Proc)
160         return @values.call(@manager.bot)
161       else
162         return @values
163       end
164     end
165     def parse(string)
166       unless values.include?(string)
167         raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
168       end
169       string
170     end
171     def desc
172       "#{@desc} [valid values are: " + values.join(", ") + "]"
173     end
174   end
175
176   # container for bot configuration
177   class BotConfigManagerClass
178
179     include Singleton
180
181     attr_reader :bot
182     attr_reader :items
183     attr_reader :config
184     attr_accessor :changed
185
186     def initialize
187       bot_associate(nil,true)
188     end
189
190     def reset_config
191       @items = Hash.new
192       @config = Hash.new(false)
193     end
194
195     # Associate with bot _bot_
196     def bot_associate(bot, reset=false)
197       reset_config if reset
198       @bot = bot
199       return unless @bot
200
201       @changed = false
202       if(File.exist?("#{@bot.botclass}/conf.yaml"))
203         begin
204           newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
205           newconfig.each { |key, val|
206             @config[key.to_sym] = val
207           }
208           return
209         rescue
210           error "failed to read conf.yaml: #{$!}"
211         end
212       end
213       # if we got here, we need to run the first-run wizard
214       BotConfigWizard.new(@bot).run
215       # save newly created config
216       @changed = true
217       save
218     end
219
220     def register(item)
221       unless item.kind_of?(BotConfigValue)
222         raise ArgumentError,"item must be a BotConfigValue"
223       end
224       @items[item.key] = item
225     end
226
227     # currently we store values in a hash but this could be changed in the
228     # future. We use hash semantics, however.
229     # components that register their config keys and setup defaults are
230     # supported via []
231     def [](key)
232       # return @items[key].value if @items.has_key?(key)
233       return @items[key.to_sym].value if @items.has_key?(key.to_sym)
234       # try to still support unregistered lookups
235       # but warn about them
236       #      if @config.has_key?(key)
237       #        warning "Unregistered lookup #{key.inspect}"
238       #        return @config[key]
239       #      end
240       if @config.has_key?(key.to_sym)
241         warning "Unregistered lookup #{key.to_sym.inspect}"
242         return @config[key.to_sym]
243       end
244       return false
245     end
246
247     # TODO should I implement this via BotConfigValue or leave it direct?
248     #    def []=(key, value)
249     #    end
250
251     # pass everything else through to the hash
252     def method_missing(method, *args, &block)
253       return @config.send(method, *args, &block)
254     end
255
256     # write current configuration to #{botclass}/conf.yaml
257     def save
258       if not @changed
259         debug "Not writing conf.yaml (unchanged)"
260         return
261       end
262       begin
263         debug "Writing new conf.yaml ..."
264         File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
265           savehash = {}
266           @config.each { |key, val|
267             savehash[key.to_s] = val
268           }
269           file.puts savehash.to_yaml
270         end
271         debug "Officializing conf.yaml ..."
272         File.rename("#{@bot.botclass}/conf.yaml.new",
273                     "#{@bot.botclass}/conf.yaml")
274         @changed = false
275       rescue => e
276         error "failed to write configuration file conf.yaml! #{$!}"
277         error "#{e.class}: #{e}"
278         error e.backtrace.join("\n")
279       end
280     end
281   end
282
283   module BotConfig
284     # Returns the only BotConfigManagerClass
285     #
286     def BotConfig.configmanager
287       return BotConfigManagerClass.instance
288     end
289
290     # Register a config value
291     def BotConfig.register(item)
292       BotConfig.configmanager.register(item)
293     end
294   end
295
296   class BotConfigWizard
297     def initialize(bot)
298       @bot = bot
299       @manager = BotConfig::configmanager
300       @questions = @manager.items.values.find_all {|i| i.wizard }
301     end
302
303     def run()
304       puts "First time rbot configuration wizard"
305       puts "===================================="
306       puts "This is the first time you have run rbot with a config directory of:"
307       puts @bot.botclass
308       puts "This wizard will ask you a few questions to get you started."
309       puts "The rest of rbot's configuration can be manipulated via IRC once"
310       puts "rbot is connected and you are auth'd."
311       puts "-----------------------------------"
312
313       return unless @questions
314       @questions.sort{|a,b| a.order <=> b.order }.each do |q|
315         puts q.desc
316         begin
317           print q.key.to_s + " [#{q.to_s}]: "
318           response = STDIN.gets
319           response.chop!
320           unless response.empty?
321             q.set_string response, false
322           end
323           puts "configured #{q.key} => #{q.to_s}"
324           puts "-----------------------------------"
325         rescue ArgumentError => e
326           puts "failed to set #{q.key}: #{e.message}"
327           retry
328         end
329       end
330     end
331   end
332
333 end