]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/config.rb
message.rb: logmessage method to retrieve the message for logging purposes
[user/henk/code/ruby/rbot.git] / lib / rbot / config.rb
index ef079429ed0f459d305773d4298c0cf60fcf3530..7ed019fe8dc48ce89c19d15099578a43309cfe77 100644 (file)
@@ -1,20 +1,23 @@
 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
@@ -27,7 +30,7 @@ module Irc
     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.
@@ -65,10 +68,13 @@ module Irc
     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
     end
     def unset
       @manager.config.delete(@key)
+      @manager.changed = true
+      @on_change.call(@manager.bot, value) if @on_change
     end
 
     # set string will raise ArgumentErrors on failed parse/validate
@@ -104,32 +110,53 @@ module Irc
     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 parse(string)
       string.split(/,\s+/)
     end
@@ -147,7 +174,7 @@ module Irc
     end
   end
 
-  class BotConfigEnumValue < BotConfigValue
+  class EnumValue < Value
     def initialize(key, params)
       super
       @values = params[:values]
@@ -166,18 +193,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_accessor :changed
 
     def initialize
       bot_associate(nil,true)
@@ -194,6 +222,7 @@ module Irc
       @bot = bot
       return unless @bot
 
+      @changed = false
       if(File.exist?("#{@bot.botclass}/conf.yaml"))
         begin
           newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml")
@@ -206,14 +235,15 @@ module Irc
         end
       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
@@ -232,13 +262,13 @@ 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?
+    # TODO should I implement this via Value or leave it direct?
     #    def []=(key, value)
     #    end
 
@@ -249,6 +279,10 @@ module Irc
 
     # write current configuration to #{botclass}/conf.yaml
     def save
+      if not @changed
+        debug "Not writing conf.yaml (unchanged)"
+        return
+      end
       begin
         debug "Writing new conf.yaml ..."
         File.open("#{@bot.botclass}/conf.yaml.new", "w") do |file|
@@ -261,6 +295,7 @@ module Irc
         debug "Officializing conf.yaml ..."
         File.rename("#{@bot.botclass}/conf.yaml.new",
                     "#{@bot.botclass}/conf.yaml")
+        @changed = false
       rescue => e
         error "failed to write configuration file conf.yaml! #{$!}"
         error "#{e.class}: #{e}"
@@ -269,39 +304,35 @@ 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"
+      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
@@ -309,10 +340,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
@@ -320,3 +351,5 @@ module Irc
   end
 
 end
+end
+end