X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=lib%2Frbot%2Fconfig.rb;h=e6145a82ee95637d6a31528bf2a89598c6e0e1b8;hb=16c921257d38522fd2930b1ee8d52675f0d4f1e0;hp=f6ff76911f2556833ca0e736d2e42b88cbc6d7ae;hpb=992ef2edbf3eed7cb1d7c4c22f72cd203aff2aa5;p=user%2Fhenk%2Fcode%2Fruby%2Frbot.git diff --git a/lib/rbot/config.rb b/lib/rbot/config.rb index f6ff7691..e6145a82 100644 --- a/lib/rbot/config.rb +++ b/lib/rbot/config.rb @@ -1,351 +1,401 @@ -module Irc +require 'singleton' + +require 'yaml' + +unless YAML.respond_to?(:load_file) + def YAML.load_file( filepath ) + File.open( filepath ) do |f| + YAML::load( f ) + end + end +end + - require 'yaml' - require 'rbot/messagemapper' +module Irc - class BotConfigItem +class Bot +module Config + class Value + # allow the definition order to be preserved so that sorting by + # 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 :values + attr_reader :wizard + attr_reader :requires_restart + attr_reader :requires_rescan + attr_reader :order + attr_reader :manager + attr_reader :auth_path def initialize(key, params) - @key = key - if params.has_key? :default + @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. + unless key.to_s =~ /^.+\..+$/ + raise ArgumentError,"key must be of the form 'module.name'" + end + @order = @@order + @@order += 1 + @key = key.to_sym + if @manager.overrides.key?(@key) + @default = @manager.overrides[@key] + elsif params.has_key? :default @default = params[:default] else @default = false end @desc = params[:desc] @type = params[:type] || String - @values = params[:values] @on_change = params[:on_change] + @validate = params[:validate] + @wizard = params[:wizard] + @requires_restart = params[:requires_restart] + @requires_rescan = params[:requires_rescan] + @auth_path = "config::key::#{key.sub('.','::')}" end def default - if @default.class == Proc + if @default.instance_of?(Proc) @default.call else @default end end - def on_change(newvalue) - return unless @on_change - @on_change.call(newvalue) + def get + return @manager.config[@key] if @manager.config.has_key?(@key) + 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 - end - # container for bot configuration - class BotConfig - class Enum + # set string will raise ArgumentErrors on failed parse/validate + def set_string(string, on_change = true) + value = parse string + if validate value + set value, on_change + else + raise ArgumentError, "invalid value: #{string}" + end end - class Password + + # override this. the default will work for strings only + def parse(string) + string end - class Boolean + + def to_s + get.to_s end - - attr_reader :items - @@items = Hash.new - - def BotConfig.register(key, params) - unless params.nil? || params.instance_of?(Hash) - raise ArgumentError,"params must be a hash" + + 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 #{validator.class} not supported" end - raise ArgumentError,"params must contain a period" unless key =~ /^.+\..+$/ - @@items[key] = BotConfigItem.new(key, params) end + end - # currently we store values in a hash but this could be changed in the - # future. We use hash semantics, however. - # components that register their config keys and setup defaults are - # supported via [] - def [](key) - return @config[key] if @config.has_key?(key) - return @@items[key].default if @@items.has_key?(key) - return false + class StringValue < Value + end + + class BooleanValue < Value + def parse(string) + return true if string == "true" + return false if string == "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 - - # pass everything through to the hash - def method_missing(method, *args, &block) - return @config.send(method, *args, &block) + def get + r = super + if r.kind_of?(Integer) + return r != 0 + else + return r + end end + end - def handle_list(m, params) - modules = [] - if params[:module] - @@items.each_key do |key| - mod, name = key.split('.') - next unless mod == params[:module] - modules.push name unless modules.include?(name) - end - if modules.empty? - m.reply "no such module #{params[:module]}" - else - m.reply "module #{params[:module]} contains: " + modules.join(", ") - end + 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 - @@items.each_key do |key| - name = key.split('.').first - modules.push name unless modules.include?(name) - end - m.reply "modules: " + modules.join(", ") + return r ? 1 : 0 end end + end - def handle_get(m, params) - key = params[:key] - unless @@items.has_key?(key) - m.reply "no such config key #{key}" + class FloatValue < Value + def parse(string) + raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/ + string.to_f + end + end + + 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 - value = self[key] - if @@items[key].type == :array - value = self[key].join(", ") - elsif @@items[key].type == :password && !m.private - value = "******" + end + + def validate_item(item) + validate(item, @validate_item) + end + + def parse(string) + string.split(/,\s+/) + end + def to_s + get.join(", ") + end + def add(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 - m.reply "#{key}: #{value}" end + def rm(val) + curval = self.get + raise ArgumentError, "value #{val} not present" unless curval.include?(val) + set(curval - [val]) + end + end - def handle_desc(m, params) - key = params[:key] - unless @@items.has_key?(key) - m.reply "no such config key #{key}" + class EnumValue < Value + def initialize(key, params) + super + @values = params[:values] + end + def values + if @values.instance_of?(Proc) + return @values.call(@manager.bot) + else + return @values end - m.reply "#{key}: #{@@items[key].desc}" + end + def parse(string) + unless values.include?(string) + raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ") + end + string + end + def desc + _("%{desc} [valid values are: %{values}]") % {:desc => @desc, :values => values.join(', ')} + end + end + + # container for bot configuration + class ManagerClass + + include Singleton + + attr_reader :bot + attr_reader :items + attr_reader :config + attr_reader :overrides + attr_accessor :changed + + def initialize + bot_associate(nil,true) end - def handle_unset(m, params) - key = params[:key] - unless @@items.has_key?(key) - m.reply "no such config key #{key}" + 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 - @config.delete(key) - handle_get(m, params) end - def handle_set(m, params) - key = params[:key] - value = params[:value].to_s - unless @@items.has_key?(key) - m.reply "no such config key #{key}" + # Associate with bot _bot_ + def bot_associate(bot, reset=false) + reset_config if reset + @bot = bot + return unless @bot + + @changed = false + conf = @bot.path 'conf.yaml' + if File.exist? conf + begin + newconfig = YAML::load_file conf + newconfig.each { |key, val| + @config[key.to_sym] = val + } + return + rescue + error "failed to read conf.yaml: #{$!}" + end end - item = @@items[key] - puts "item type is #{item.type}" - case item.type - when :string - @config[key] = value - when :password - @config[key] = value - when :integer - @config[key] = value.to_i - when :float - @config[key] = value.to_f - when :array - @config[key] = value.split(/,\s*/) - when :boolean - if value == "true" - @config[key] = true - else - @config[key] = false - end - when :enum - unless item.values.include?(value) - m.reply "invalid value #{value}, allowed values are: " + item.values.join(", ") - return - end - @config[key] = value - else - puts "ACK, unsupported type #{item.type}" - exit 2 + # if we got here, we need to run the first-run wizard + Wizard.new(@bot).run + # save newly created config + @changed = true + save + end + + def register(item) + unless item.kind_of?(Value) + raise ArgumentError,"item must be an Irc::Bot::Config::Value" end - item.on_change(@config[key]) - m.okay + @items[item.key] = item end - # bot:: parent bot class - # create a new config hash from #{botclass}/conf.rbot - def initialize(bot) - @bot = bot - @config = Hash.new(false) + # currently we store values in a hash but this could be changed in the + # future. We use hash semantics, however. + # components that register their config keys and setup defaults are + # supported via [] + def [](key) + # return @items[key].value if @items.has_key?(key) + return @items[key.to_sym].value if @items.has_key?(key.to_sym) + # try to still support unregistered lookups + # but warn about them + # if @config.has_key?(key) + # warning "Unregistered lookup #{key.inspect}" + # return @config[key] + # end + if @config.has_key?(key.to_sym) + warning _("Unregistered lookup #{key.to_sym.inspect}") + return @config[key.to_sym] + end + return false + end - # respond to config messages, to provide runtime configuration - # management - # messages will be: - # get (implied) - # set - # unset - # and for arrays: - # add - # remove - @handler = MessageMapper.new(self) - @handler.map 'config list :module', :action => 'handle_list', - :defaults => {:module => false} - @handler.map 'config get :key', :action => 'handle_get' - @handler.map 'config desc :key', :action => 'handle_desc' - @handler.map 'config describe :key', :action => 'handle_desc' - @handler.map 'config set :key *value', :action => 'handle_set' - @handler.map 'config unset :key', :action => 'handle_unset' - - # TODO - # have this class persist key/values in hash using yaml as it kinda - # already does. - # have other users of the class describe config to it on init, like: - # @config.add(:key => 'server.name', :type => 'string', - # :default => 'localhost', :restart => true, - # :help => 'irc server to connect to') - # that way the config module doesn't have to know about all the other - # classes but can still provide help and defaults. - # Classes don't have to add keys, they can just use config as a - # persistent hash, but then they won't be presented by the config - # module for runtime display/changes. - # (:restart, if true, makes the bot reply to changes with "this change - # will take effect after the next restart) - # :proc => Proc.new {|newvalue| ...} - # (:proc, proc to run on change of setting) - # or maybe, @config.add_key(...) do |newvalue| .... end - # :validate => /regex/ - # (operates on received string before conversion) - # Special handling for arrays so the config module can be used to - # add/remove elements as well as changing the whole thing - # Allow config options to list possible valid values (if type is enum, - # for example). Then things like the language module can list the - # available languages for choosing. - - if(File.exist?("#{@bot.botclass}/conf.yaml")) - newconfig = YAML::load_file("#{@bot.botclass}/conf.yaml") - @config.update(newconfig) - else - # first-run wizard! - wiz = BotConfigWizard.new(@bot) - newconfig = wiz.run(@config) - @config.update(newconfig) + 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 - # write current configuration to #{botclass}/conf.rbot + # pass everything else through to the hash + def method_missing(method, *args, &block) + return @config.send(method, *args, &block) + end + + # write current configuration to #{botclass}/conf.yaml def save - Dir.mkdir("#{@bot.botclass}") if(!File.exist?("#{@bot.botclass}")) - File.open("#{@bot.botclass}/conf.yaml", "w") do |file| - file.puts @config.to_yaml + if not @changed + debug "Not writing conf.yaml (unchanged)" + return + end + begin + conf = @bot.path 'conf.yaml' + fnew = conf + '.new' + debug "Writing new conf.yaml ..." + File.open(fnew, "w") do |file| + savehash = {} + @config.each { |key, val| + savehash[key.to_s] = val + } + file.puts savehash.to_yaml + end + debug "Officializing conf.yaml ..." + File.rename(fnew, conf) + @changed = false + rescue => e + error "failed to write configuration file conf.yaml! #{$!}" + error "#{e.class}: #{e}" + error e.backtrace.join("\n") end end + end - def privmsg(m) - @handler.handle(m) - end + # Returns the only Irc::Bot::Config::ManagerClass + # + def Config.manager + return ManagerClass.instance end - # I don't see a nice way to avoid the first start wizard knowing way too - # much about other modules etc, because it runs early and stuff it - # configures is used to initialise the other modules... - # To minimise this we'll do as little as possible and leave the rest to - # online modification - class BotConfigWizard - - # TODO things to configure.. - # config directory (botclass) - people don't realise they should set - # this. The default... isn't good. - # users? - default *!*@* to 10 - # levels? - need a way to specify a default level, methinks, for - # unconfigured items. - # + # Register a config value + def Config.register(item) + Config.manager.register(item) + end + + class Wizard def initialize(bot) @bot = bot - @questions = [ - { - :question => "What server should the bot connect to?", - :key => "server.name", - :type => :string, - }, - { - :question => "What port should the bot connect to?", - :key => "server.port", - :type => :number, - }, - { - :question => "Does this IRC server require a password for access? Leave blank if not.", - :key => "server.password", - :type => :password, - }, - { - :question => "Would you like rbot to bind to a specific local host or IP? Leave blank if not.", - :key => "server.bindhost", - :type => :string, - }, - { - :question => "What IRC nickname should the bot attempt to use?", - :key => "irc.nick", - :type => :string, - }, - { - :question => "What local user should the bot appear to be?", - :key => "irc.user", - :type => :string, - }, - { - :question => "What channels should the bot always join at startup? List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'", - :prompt => "Channels", - :key => "irc.join_channels", - :type => :string, - }, - { - :question => "Which language file should the bot use?", - :key => "core.language", - :type => :enum, - :items => Dir.new(Config::DATADIR + "/languages").collect {|f| - f =~ /\.lang$/ ? f.gsub(/\.lang$/, "") : nil - }.compact - }, - { - :question => "Enter your password for maxing your auth with the bot (used to associate new hostmasks with your owner-status etc)", - :key => "auth.password", - :type => :password, - }, - ] - end - - def run(defaults) - config = defaults.clone - puts "First time rbot configuration wizard" + @manager = Config.manager + @questions = @manager.items.values.find_all {|i| i.wizard } + end + + def run() + $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 "-----------------------------------" - @questions.each do |q| - puts q[:question] + return unless @questions + @questions.sort{|a,b| a.order <=> b.order }.each do |q| + puts _(q.desc) begin - key = q[:key] - if q[:type] == :enum - puts "valid values are: " + q[:items].join(", ") - end - if (defaults.has_key?(key)) - print q[:key] + " [#{defaults[key]}]: " - else - print q[:key] + " []: " - end + print q.key.to_s + " [#{q.to_s}]: " response = STDIN.gets response.chop! - response = defaults[key] if response == "" && defaults.has_key?(key) - case q[:type] - when :string - when :number - raise "value '#{response}' is not a number" unless (response.class == Fixnum || response =~ /^\d+$/) - response = response.to_i - when :password - when :enum - raise "selected value '#{response}' is not one of the valid values" unless q[:items].include?(response) + unless response.empty? + q.set_string response, false end - config[key] = response - puts "configured #{key} => #{config[key]}" + puts _("configured #{q.key} => #{q.to_s}") puts "-----------------------------------" - rescue RuntimeError => e - puts e.message + rescue ArgumentError => e + puts _("failed to set #{q.key}: #{e.message}") retry end end - return config end end + +end +end end