]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/config.rb
added rake and updated Gemfile and Gemfile.lock
[user/henk/code/ruby/rbot.git] / lib / rbot / config.rb
index 2495a307331432faef7f28645c45727fb52b06f0..ef63a2feb06c36f1372e75d412d199814b633543 100644 (file)
@@ -1,33 +1,37 @@
 require 'singleton'
 
-module Irc
-
-  require 'yaml'
+require 'yaml'
 
-  unless YAML.respond_to?(:load_file)
-      def YAML.load_file( filepath )
-        File.open( filepath ) do |f|
-          YAML::load( f )
-        end
-      end
+unless YAML.respond_to?(:load_file)
+  def YAML.load_file( filepath )
+    File.open( filepath ) do |f|
+      YAML::load( f )
+    end
   end
+end
+
 
-  class BotConfigValue
+module Irc
+
+class Bot
+module Config
+  class Value
     # allow the definition order to be preserved so that sorting by
-    # definition order is possible. The BotConfigWizard does this to allow
+    # definition order is possible. The Wizard does this to allow
     # the :wizard questions to be in a sensible order.
     @@order = 0
     attr_reader :type
     attr_reader :desc
     attr_reader :key
     attr_reader :wizard
+    attr_reader :store_default
     attr_reader :requires_restart
     attr_reader :requires_rescan
     attr_reader :order
     attr_reader :manager
     attr_reader :auth_path
     def initialize(key, params)
-      @manager = BotConfig::configmanager
+      @manager = Config.manager
       # Keys must be in the form 'module.name'.
       # They will be internally passed around as symbols,
       # but we accept them both in string and symbol form.
@@ -37,7 +41,9 @@ module Irc
       @order = @@order
       @@order += 1
       @key = key.to_sym
-      if params.has_key? :default
+      if @manager.overrides.key?(@key)
+        @default = @manager.overrides[@key]
+      elsif params.has_key? :default
         @default = params[:default]
       else
         @default = false
@@ -47,6 +53,7 @@ module Irc
       @on_change = params[:on_change]
       @validate = params[:validate]
       @wizard = params[:wizard]
+      @store_default = params[:store_default]
       @requires_restart = params[:requires_restart]
       @requires_rescan = params[:requires_rescan]
       @auth_path = "config::key::#{key.sub('.','::')}"
@@ -60,16 +67,20 @@ module Irc
     end
     def get
       return @manager.config[@key] if @manager.config.has_key?(@key)
-      return @default
+      return default
     end
     alias :value :get
     def set(value, on_change = true)
       @manager.config[@key] = value
       @manager.changed = true
       @on_change.call(@manager.bot, value) if on_change && @on_change
+      return self
     end
     def unset
       @manager.config.delete(@key)
+      @manager.changed = true
+      @on_change.call(@manager.bot, value) if @on_change
+      return self
     end
 
     # set string will raise ArgumentErrors on failed parse/validate
@@ -91,46 +102,81 @@ module Irc
       get.to_s
     end
 
-    private
-    def validate(value)
-      return true unless @validate
-      if @validate.instance_of?(Proc)
-        return @validate.call(value)
-      elsif @validate.instance_of?(Regexp)
-        raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
-        return @validate.match(value)
+    protected
+    def validate(val, validator  = @validate)
+      case validator
+      when false, nil
+        return true
+      when Proc
+        return validator.call(val)
+      when Regexp
+        raise ArgumentError, "validation via Regexp only supported for strings!" unless String === val
+        return validator.match(val)
       else
-        raise ArgumentError, "validation type #{@validate.class} not supported"
+        raise ArgumentError, "validation type #{validator.class} not supported"
       end
     end
   end
 
-  class BotConfigStringValue < BotConfigValue
+  class StringValue < Value
   end
 
-  class BotConfigBooleanValue < BotConfigValue
+  class BooleanValue < Value
     def parse(string)
       return true if string == "true"
       return false if string == "false"
-      raise ArgumentError, "#{string} does not match either 'true' or 'false'"
+      if string =~ /^-?\d+$/
+        return string.to_i != 0
+      end
+      raise ArgumentError, "#{string} does not match either 'true' or 'false', and it's not an integer either"
+    end
+    def get
+      r = super
+      if r.kind_of?(Integer)
+        return r != 0
+      else
+        return r
+      end
     end
   end
 
-  class BotConfigIntegerValue < BotConfigValue
+  class IntegerValue < Value
     def parse(string)
+      return 1 if string == "true"
+      return 0 if string == "false"
       raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
       string.to_i
     end
+    def get
+      r = super
+      if r.kind_of?(Integer)
+        return r
+      else
+        return r ? 1 : 0
+      end
+    end
   end
 
-  class BotConfigFloatValue < BotConfigValue
+  class FloatValue < Value
     def parse(string)
       raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
       string.to_f
     end
   end
 
-  class BotConfigArrayValue < BotConfigValue
+  class ArrayValue < Value
+    def initialize(key, params)
+      super
+      @validate_item = params[:validate_item]
+      @validate ||= Proc.new do |v|
+        !v.find { |i| !validate_item(i) }
+      end
+    end
+
+    def validate_item(item)
+      validate(item, @validate_item)
+    end
+
     def parse(string)
       string.split(/,\s+/)
     end
@@ -138,8 +184,13 @@ module Irc
       get.join(", ")
     end
     def add(val)
-      curval = self.get
-      set(curval + [val]) unless curval.include?(val)
+      newval = self.get.dup
+      unless newval.include? val
+        newval << val
+        validate_item(val) or raise ArgumentError, "invalid item: #{val}"
+        validate(newval) or raise ArgumentError, "invalid value: #{newval.inspect}"
+        set(newval)
+      end
     end
     def rm(val)
       curval = self.get
@@ -148,7 +199,7 @@ module Irc
     end
   end
 
-  class BotConfigEnumValue < BotConfigValue
+  class EnumValue < Value
     def initialize(key, params)
       super
       @values = params[:values]
@@ -167,18 +218,19 @@ module Irc
       string
     end
     def desc
-      "#{@desc} [valid values are: " + values.join(", ") + "]"
+      _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')}
     end
   end
 
   # container for bot configuration
-  class BotConfigManagerClass
+  class ManagerClass
 
     include Singleton
 
     attr_reader :bot
     attr_reader :items
     attr_reader :config
+    attr_reader :overrides
     attr_accessor :changed
 
     def initialize
@@ -188,6 +240,21 @@ module Irc
     def reset_config
       @items = Hash.new
       @config = Hash.new(false)
+
+      # We allow default values for config keys to be overridden by
+      # the config file /etc/rbot.conf
+      # The main purpose for this is to allow distro or system-wide
+      # settings such as external program paths (figlet, toilet, ispell)
+      # to be set once for all the bots.
+      @overrides = Hash.new
+      etcfile = "/etc/rbot.conf"
+      if File.exist?(etcfile)
+        log "Loading defaults from #{etcfile}"
+        etcconf = YAML::load_file(etcfile)
+        etcconf.each { |k, v|
+          @overrides[k.to_sym] = v
+        }
+      end
     end
 
     # Associate with bot _bot_
@@ -197,9 +264,10 @@ module Irc
       return unless @bot
 
       @changed = false
-      if(File.exist?("#{@bot.botclass}/conf.yaml"))
+      conf = @bot.path 'conf.yaml'
+      if File.exist? conf
         begin
-          newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
+          newconfig = YAML::load_file conf
           newconfig.each { |key, val|
             @config[key.to_sym] = val
           }
@@ -208,16 +276,24 @@ module Irc
           error "failed to read conf.yaml: #{$!}"
         end
       end
+      # config options with :store_default to true should store
+      # their default value at first run.
+      # Some defaults might change anytime the bot starts
+      #  for instance core.db or authpw
+      @items.values.find_all {|i| i.store_default }.each do |value|
+        @config[value.key] = value.default
+      end
+
       # if we got here, we need to run the first-run wizard
-      BotConfigWizard.new(@bot).run
+      Wizard.new(@bot).run
       # save newly created config
       @changed = true
       save
     end
 
     def register(item)
-      unless item.kind_of?(BotConfigValue)
-        raise ArgumentError,"item must be a BotConfigValue"
+      unless item.kind_of?(Value)
+        raise ArgumentError,"item must be an Irc::Bot::Config::Value"
       end
       @items[item.key] = item
     end
@@ -236,15 +312,19 @@ module Irc
       #        return @config[key]
       #      end
       if @config.has_key?(key.to_sym)
-        warning "Unregistered lookup #{key.to_sym.inspect}"
+        warning _("Unregistered lookup #{key.to_sym.inspect}")
         return @config[key.to_sym]
       end
       return false
     end
 
-    # TODO should I implement this via BotConfigValue or leave it direct?
-    #    def []=(key, value)
-    #    end
+    def []=(key, value)
+      return @items[key.to_sym].set(value) if @items.has_key?(key.to_sym)
+      if @config.has_key?(key.to_sym)
+        warning _("Unregistered lookup #{key.to_sym.inspect}")
+        return @config[key.to_sym] = value
+      end
+    end
 
     # pass everything else through to the hash
     def method_missing(method, *args, &block)
@@ -258,8 +338,10 @@ module Irc
         return
       end
       begin
+       conf = @bot.path 'conf.yaml'
+       fnew = conf + '.new'
         debug "Writing new conf.yaml ..."
-        File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
+        File.open(fnew, "w") do |file|
           savehash = {}
           @config.each { |key, val|
             savehash[key.to_s] = val
@@ -267,8 +349,7 @@ module Irc
           file.puts savehash.to_yaml
         end
         debug "Officializing conf.yaml ..."
-        File.rename("#{@bot.botclass}/conf.yaml.new",
-                    "#{@bot.botclass}/conf.yaml")
+        File.rename(fnew, conf)
         @changed = false
       rescue => e
         error "failed to write configuration file conf.yaml! #{$!}"
@@ -278,39 +359,36 @@ module Irc
     end
   end
 
-  module BotConfig
-    # Returns the only BotConfigManagerClass
-    #
-    def BotConfig.configmanager
-      return BotConfigManagerClass.instance
-    end
+  # Returns the only Irc::Bot::Config::ManagerClass
+  #
+  def Config.manager
+    return ManagerClass.instance
+  end
 
-    # Register a config value
-    def BotConfig.register(item)
-      BotConfig.configmanager.register(item)
-    end
+  # Register a config value
+  def Config.register(item)
+    Config.manager.register(item)
   end
 
-  class BotConfigWizard
+  class Wizard
     def initialize(bot)
       @bot = bot
-      @manager = BotConfig::configmanager
+      @manager = Config.manager
       @questions = @manager.items.values.find_all {|i| i.wizard }
     end
 
     def run()
-      puts "First time rbot configuration wizard"
+      $stdout.sync = true
+      puts _("First time rbot configuration wizard")
       puts "===================================="
-      puts "This is the first time you have run rbot with a config directory of:"
-      puts @bot.botclass
-      puts "This wizard will ask you a few questions to get you started."
-      puts "The rest of rbot's configuration can be manipulated via IRC once"
-      puts "rbot is connected and you are auth'd."
+      puts _("This is the first time you have run rbot with a config directory of: #{@bot.botclass}")
+      puts _("This wizard will ask you a few questions to get you started.")
+      puts _("The rest of rbot's configuration can be manipulated via IRC once rbot is connected and you are auth'd.")
       puts "-----------------------------------"
 
       return unless @questions
       @questions.sort{|a,b| a.order <=> b.order }.each do |q|
-        puts q.desc
+        puts _(q.desc)
         begin
           print q.key.to_s + " [#{q.to_s}]: "
           response = STDIN.gets
@@ -318,10 +396,10 @@ module Irc
           unless response.empty?
             q.set_string response, false
           end
-          puts "configured #{q.key} => #{q.to_s}"
+          puts _("configured #{q.key} => #{q.to_s}")
           puts "-----------------------------------"
         rescue ArgumentError => e
-          puts "failed to set #{q.key}: #{e.message}"
+          puts _("failed to set #{q.key}: #{e.message}")
           retry
         end
       end
@@ -329,3 +407,5 @@ module Irc
   end
 
 end
+end
+end