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