]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/commitdiff
+ @bot.path and datafile methods
authorGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Sun, 15 Feb 2009 00:30:51 +0000 (01:30 +0100)
committerGiuseppe Bilotta <giuseppe.bilotta@gmail.com>
Sun, 15 Feb 2009 01:06:27 +0000 (02:06 +0100)
We provide two methods that make it more simple and elegant for
botmodules to define paths relative to the bot's own directory
(botclass) and to the BotModule's (assumed) non-registry directory.

The first method is Irc::Bot#path(), which joins its arguments with the
botclass. This method can be used to access datafiles in the bot
directory with a much cleaner syntax; and since it uses File.join, the
resulting paths are also properly formatted on each platform, which
doesn't hurt.

Each BotModule now also carries a dirname() method that should return the
directory under botclass that holds the BotModule's datafiles. dirname()
defaults to the BotModule's name(), but it can be overridden, e.g. for
backwards compatibility (see the patch for the quotes plugin), or
for BotModules that share their datafiles.

Datafiles can be accessed using the BotModule#datafile() method that
joins the botclass, the dirname() and whatever other argument is passed.

20 files changed:
data/rbot/plugins/alias.rb
data/rbot/plugins/debugger.rb
data/rbot/plugins/factoids.rb
data/rbot/plugins/games/azgame.rb
data/rbot/plugins/games/quiz.rb
data/rbot/plugins/games/shiritori.rb
data/rbot/plugins/karma.rb
data/rbot/plugins/keywords.rb
data/rbot/plugins/lart.rb
data/rbot/plugins/quotes.rb
data/rbot/plugins/salut.rb
lib/rbot/config.rb
lib/rbot/core/auth.rb
lib/rbot/core/irclog.rb
lib/rbot/core/utils/utils.rb
lib/rbot/core/utils/wordlist.rb
lib/rbot/dbhash.rb
lib/rbot/ircbot.rb
lib/rbot/plugins.rb
lib/rbot/registry.rb

index f947d81cf4221ad41e1241eca1185b21e2e08a32..58d0ef01a0831639f03dd98b8aaf06064e2519b2 100644 (file)
@@ -38,8 +38,8 @@ class AliasPlugin < Plugin
 
   def initialize
     super
-    @data_path = "#{@bot.botclass}/alias/"
-    @data_file = "#{@data_path}/aliases.yaml"
+    @data_path = datafile
+    @data_file = File.join(@data_path, 'aliases.yaml')
     # hash of alias => command entries
     data = nil
     aliases = if File.exist?(@data_file) &&
index c83aea4a58e680bbcf11cbb318e5f7d5fa596e99..2895cd0beadf678c3ec01ba3aec2c35e9d22d9c7 100644 (file)
@@ -18,12 +18,16 @@ class DebugPlugin < Plugin
     :default => "",
     :desc => "Directory where profile/string dumps are to be stored")
 
+  def dirname
+    @bot.config['debug.logdir']
+  end
+
   def initialize
     super
     @prev = Hash.new(0)
     @curr = Hash.new(0)
     @delta = Hash.new(0)
-    @file = File.open("#{@bot.botclass}/#{@bot.config['debug.logdir']}/memory_profiler.log",'w')
+    @file = File.open(datafile("memory_profiler.log"), 'w')
     @thread = @bot.timer.add(@bot.config['debug.interval']) {
         begin
           GC.start
@@ -39,7 +43,7 @@ class DebugPlugin < Plugin
           end
 
           if @bot.config['debug.dump_strings']
-            File.open("#{@bot.botclass}/#{@bot.config['debug.logdir']}/memory_profiler_strings.log.#{Time.now.to_i}",'w') do |f|
+            File.open(datafile("memory_profiler_strings.log.#{Time.now.to_i}"), 'w') do |f|
               curr_strings.sort.each do |s|
                 f.puts s
               end
@@ -107,7 +111,7 @@ class DebugPlugin < Plugin
         end
       end
 
-      File.open("#{@bot.botclass}/#{@bot.config['debug.logdir']}/memory_profiler_strings.log.#{Time.now.to_i}",'w') do |f|
+      File.open(datafile("memory_profiler_strings.log.#{Time.now.to_i}"), 'w') do |f|
         curr_strings.sort.each do |s|
           f.puts s
         end
index 3192aa00e450d211de79f7aa9a0cad1ca944a5ac..689b6d78e688d23e5a428f07ae5bdc860a96119e 100644 (file)
@@ -120,7 +120,7 @@ class FactoidsPlugin < Plugin
     super
 
     # TODO config
-    @dir = File.join(@bot.botclass,"factoids")
+    @dir = datafile
     @filename = "factoids.rbot"
     @factoids = FactoidList.new
     @triggers = Set.new
index cb95228d8c0073cec387a726657cd8f5ecefeeeb..6e2526e2718a6306a381815114be4b4e5a29b393 100644 (file)
@@ -150,7 +150,7 @@ class AzGamePlugin < Plugin
     },
     }
 
-    @autoadd_base = "#{@bot.botclass}/azgame/autoadd-"
+    @autoadd_base = datafile "autoadd-"
   end
 
   def initialize_wordlist(params)
index 7577e7ce998b3709ce53b852523265bcce856e6e..9159a4c4fef333b5fca3dd252288d8ec313b4e75 100644 (file)
@@ -186,8 +186,9 @@ class QuizPlugin < Plugin
   def fetch_data( m )
     # Read the winning messages file 
     @win_messages = Array.new
-    if File.exists? "#{@bot.botclass}/quiz/win_messages"
-      IO.foreach("#{@bot.botclass}/quiz/win_messages") { |line| @win_messages << line.chomp }
+    winfile = datafile 'win_messages'
+    if File.exists? winfile
+      IO.foreach(winfile) { |line| @win_messages << line.chomp }
     else
       warning( "win_messages file not found!" )
       # Fill the array with a least one message or code accessing it would fail
@@ -212,13 +213,13 @@ class QuizPlugin < Plugin
           m.reply "Failed to download questions from #{p}, ignoring sources"
         end
       else
-        path = "#{@bot.botclass}/quiz/#{p}"
+        path = datafile p
         debug "Fetching from #{path}"
 
         # Local data
         begin
-          datafile = File.new( path, File::RDONLY )
-          data << "\n\n" << datafile.read
+          file = File.new( path, File::RDONLY )
+          data << "\n\n" << file.read
         rescue
           m.reply "Failed to read from local database file #{p}, skipping."
         end
index 84ee9620d869b566f258529345a0b8c566daad51..0b77871e00556460eb1508681549c6d1de280efc 100644 (file)
@@ -390,7 +390,7 @@ class ShiritoriPlugin < Plugin
       if ruleset.has_key?(:wordlist_file)
         begin
           ruleset[:words] =
-            File.new("#{@bot.botclass}/shiritori/#{ruleset[:wordlist_file]}").grep(
+            File.new(datafile ruleset[:wordlist_file]).grep(
               ruleset[:listen]) {|l| ruleset[:normalize].call l.chomp}
         rescue
           raise "unable to load word list"
index d8d378e332c223ef54ea0997892905610ab73d15..ad5f57a27dc9c1d151f32915fad2a8603eae66fc 100644 (file)
@@ -14,16 +14,17 @@ class KarmaPlugin < Plugin
     @registry.set_default(0)
 
     # import if old file format found
-    if(File.exist?("#{@bot.botclass}/karma.rbot"))
+    oldkarma = @bot.path 'karma.rbot'
+    if File.exist? oldkarma
       log "importing old karma data"
-      IO.foreach("#{@bot.botclass}/karma.rbot") do |line|
+      IO.foreach(oldkarma) do |line|
         if(line =~ /^(\S+)<=>([\d-]+)$/)
           item = $1
           karma = $2.to_i
           @registry[item] = karma
         end
       end
-      File.delete("#{@bot.botclass}/karma.rbot")
+      File.delete oldkarma
     end
   end
 
index 97fe4258e862d86b8001a0fa3d413df596deb212..8671e32f89a58806ef583ad08cfdc5ce47514f04 100644 (file)
@@ -116,9 +116,10 @@ class Keywords < Plugin
     scan
 
     # import old format keywords into DBHash
-    if(File.exist?("#{@bot.botclass}/keywords.rbot"))
+    olds = @bot.path 'keywords.rbot'
+    if File.exist? olds
       log "auto importing old keywords.rbot"
-      IO.foreach("#{@bot.botclass}/keywords.rbot") do |line|
+      IO.foreach(olds) do |line|
         if(line =~ /^(.*?)\s*<=(is|are)?=?>\s*(.*)$/)
           lhs = $1
           mhs = $2
@@ -129,7 +130,7 @@ class Keywords < Plugin
           @keywords[lhs] = Keyword.new(mhs, values).dump
         end
       end
-      File.rename("#{@bot.botclass}/keywords.rbot", "#{@bot.botclass}/keywords.rbot.old")
+      File.rename(olds, olds + ".old")
     end
   end
 
@@ -137,15 +138,12 @@ class Keywords < Plugin
   # have been added
   def scan
     # first scan for old DBHash files, and convert them
-    Dir["#{@bot.botclass}/keywords/*"].each {|f|
+    Dir[datafile '*'].each {|f|
       next unless f =~ /\.db$/
       log "upgrading keyword db #{f} (rbot 0.9.5 or prior) database format"
       newname = f.gsub(/\.db$/, ".kdb")
-      old = BDB::Hash.open f, nil,
-                           "r+", 0600
-      new = BDB::CIBtree.open(newname, nil,
-                              BDB::CREATE | BDB::EXCL,
-                              0600)
+      old = BDB::Hash.open f, nil, "r+", 0600
+      new = BDB::CIBtree.open(newname, nil, BDB::CREATE | BDB::EXCL, 0600)
       old.each {|k,v|
         new[k] = v
       }
@@ -155,7 +153,7 @@ class Keywords < Plugin
     }
 
     # then scan for current DBTree files, and load them
-    Dir["#{@bot.botclass}/keywords/*"].each {|f|
+    Dir[@bot.path 'keywords', '*'].each {|f|
       next unless f =~ /\.kdb$/
       hsh = DBTree.new @bot, f, true
       key = File.basename(f).gsub(/\.kdb$/, "")
@@ -164,7 +162,7 @@ class Keywords < Plugin
     }
 
     # then scan for non DB files, and convert/import them and delete
-    Dir["#{@bot.botclass}/keywords/*"].each {|f|
+    Dir[@bot.path 'keywords', '*'].each {|f|
       next if f =~ /\.kdb$/
       next if f =~ /CVS$/
       log "auto converting keywords from #{f}"
@@ -192,28 +190,28 @@ class Keywords < Plugin
 
   # upgrade data files found in old rbot formats to current
   def upgrade_data
-    if File.exist?("#{@bot.botclass}/keywords.db")
+    olds = @bot.path 'keywords.db'
+    if File.exist? olds
       log "upgrading old keywords (rbot 0.9.5 or prior) database format"
-      old = BDB::Hash.open "#{@bot.botclass}/keywords.db", nil,
-                           "r+", 0600
+      old = BDB::Hash.open olds, nil, "r+", 0600
       old.each {|k,v|
         @keywords[k] = v
       }
       old.close
       @keywords.flush
-      File.rename("#{@bot.botclass}/keywords.db", "#{@bot.botclass}/keywords.db.old")
+      File.rename(olds, olds + ".old")
     end
 
-    if File.exist?("#{@bot.botclass}/keyword.db")
+    olds.replace(@bot.path 'keyword.db')
+    if File.exist? olds
       log "upgrading old keywords (rbot 0.9.9 or prior) database format"
-      old = BDB::CIBtree.open "#{@bot.botclass}/keyword.db", nil,
-                           "r+", 0600
+      old = BDB::CIBtree.open olds, nil, "r+", 0600
       old.each {|k,v|
         @keywords[k] = v
       }
       old.close
       @keywords.flush
-      File.rename("#{@bot.botclass}/keyword.db", "#{@bot.botclass}/keyword.db.old")
+      File.rename(olds, olds + ".old")
     end
   end
 
@@ -223,7 +221,7 @@ class Keywords < Plugin
   end
 
   def oldsave
-    File.open("#{@bot.botclass}/keywords.rbot", "w") do |file|
+    File.open(@bot.path "keywords.rbot", "w") do |file|
       @keywords.each do |key, value|
         file.puts "#{key}<=#{value.type}=>#{value.dump}"
       end
@@ -484,7 +482,7 @@ class Keywords < Plugin
 
     # TODO check factoids config
     # also TODO: runtime export
-    dir = File.join(@bot.botclass,"factoids")
+    dir = @bot.path 'factoids'
     fname = File.join(dir,"keyword_factoids.rbot")
 
     Dir.mkdir(dir) unless FileTest.directory?(dir)
index 0e995efb114ff2928f5dbc09cd3863b53656ceb2..4c9458891b96c3ecc1ba291337da4bf93b26a28f 100644 (file)
@@ -41,12 +41,12 @@ class LartPlugin < Plugin
 
     # We may be on an old installation, so on the first run read non-language-specific larts
     unless defined?(@oldlart)
-      @oldlart = "#{@bot.botclass}/lart/larts"
-      @oldpraise = "#{@bot.botclass}/lart/praise"
+      @oldlart = datafile 'larts'
+      @oldpraise = datafile 'praise'
     end
 
-    @lartfile.replace "#{@bot.botclass}/lart/larts-#{lang}"
-    @praisefile.replace "#{@bot.botclass}/lart/praises-#{lang}"
+    @lartfile.replace(datafile "larts-#{lang}")
+    @praisefile.replace(datafile "praises-#{lang}")
     @larts.clear
     @praises.clear
     if File.exists? @lartfile
@@ -72,8 +72,7 @@ class LartPlugin < Plugin
 
   def save
     return unless @changed
-    Dir.mkdir("#{@bot.botclass}/lart") if not FileTest.directory? "#{@bot.botclass}/lart"
-    # TODO implement safe saving here too
+    Dir.mkdir(datafile) unless FileTest.directory? datafile
     Utils.safe_save(@lartfile) { |file|
       file.puts @larts
     }
index c631527f468f72af43a0cc88e209d7e49d776eb8..2a6467896fe3cb54775906ff8b156d09fb3291ea 100644 (file)
@@ -8,11 +8,15 @@
 define_structure :Quote, :num, :date, :source, :quote
 
 class QuotePlugin < Plugin
+  def dirname
+    'quotes'
+  end
+
   def initialize
     super
     @lists = Hash.new
     @changed = Hash.new
-    Dir["#{@bot.botclass}/quotes/*"].each {|f|
+    Dir[datafile '*'].each {|f|
       next if File.directory?(f)
       channel = File.basename(f)
       @lists[channel] = Array.new if(!@lists.has_key?(channel))
@@ -27,12 +31,12 @@ class QuotePlugin < Plugin
   end
 
   def save
-    Dir.mkdir("#{@bot.botclass}/quotes") if(!FileTest.directory?("#{@bot.botclass}/quotes"))
+    Dir.mkdir(datafile) unless FileTest.directory? datafile
     @lists.each {|channel, quotes|
       begin
         if @changed[channel]
           debug "Writing new quotefile for channel #{channel} ..."
-          Utils.safe_save("#{@bot.botclass}/quotes/#{channel}") {|file|
+          Utils.safe_save(datafile channel) {|file|
             quotes.compact.each {|q| 
               file.puts "#{q.num} | #{q.date} | #{q.source} | #{q.quote}"
             }
index c169d138f6a946bff9b3ddea3cff2e0d7ac6a2ee..e80a02b0910eed9e0a69a4eadfd7d9cb5a5569fa 100644 (file)
@@ -168,7 +168,7 @@ class SalutPlugin < Plugin
     @all_langs = @bot.config['salut.all_languages']
     if @all_langs
       # Get all available languages
-      langs = Dir.new("#{@bot.botclass}/salut").collect {|f|
+      langs = Dir.new(datafile).collect {|f|
         f =~ /salut-([^.]+)/ ? $1 : nil
       }.compact
       langs.each { |lang|
@@ -183,11 +183,11 @@ class SalutPlugin < Plugin
   end
 
   def load_lang(lang)
-    dir = "#{@bot.botclass}/salut"
+    dir = datafile
     if not File.exist?(dir)
       Dir.mkdir(dir)
     end
-    file = "#{@bot.botclass}/salut/salut-#{lang}"
+    file = File.join dir, "salut-#{lang}"
     if File.exist?(file)
       begin
         salutations = Hash.new
@@ -214,7 +214,7 @@ class SalutPlugin < Plugin
   end
 
   def save_lang(lang, val)
-    fn = "#{@bot.botclass}/salut/salut-#{lang}"
+    fn = datafile "salut-#{lang}"
     Utils.safe_save(fn) { |file|
       file.puts val.to_yaml
     }
index 4f81c6951050e89bc5719c664a05a4832a1a38e6..e6145a82ee95637d6a31528bf2a89598c6e0e1b8 100644 (file)
@@ -262,9 +262,10 @@ module Config
       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
           }
@@ -327,8 +328,10 @@ module Config
         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
@@ -336,8 +339,7 @@ module Config
           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! #{$!}"
index 5e80d880081585d874578aa2d41e1b1bbcf00fed..275f5d7e18711a1fa293ddb679edfcdbe9420b4d 100644 (file)
@@ -817,13 +817,13 @@ class AuthModule < CoreBotModule
 
   def auth_export(m, params)
 
-    exportfile = "#{@bot.botclass}/new-auth.users"
+    exportfile = @bot.path "new-auth.users"
 
     what = params[:things]
 
     has_to = what[-2] == "to"
     if has_to
-      exportfile = "#{@bot.botclass}/#{what[-1]}"
+      exportfile = @bot.path what[-1]
       what.slice!(-2,2)
     end
 
@@ -889,13 +889,13 @@ class AuthModule < CoreBotModule
 
   def auth_import(m, params)
 
-    importfile = "#{@bot.botclass}/new-auth.users"
+    importfile = @bot.path "new-auth.users"
 
     what = params[:things]
 
     has_from = what[-2] == "from"
     if has_from
-      importfile = "#{@bot.botclass}/#{what[-1]}"
+      importfile = @bot.path what[-1]
       what.slice!(-2,2)
     end
 
index 88d8b00f8d9c6726a276c7ae3581729039c0ecf6..b848947c00d60761ad59b2776fc2605edc57ebca 100644 (file)
@@ -33,7 +33,9 @@ class IrcLogModule < CoreBotModule
     @queue = Queue.new
     @thread = Thread.new { loggers_thread }
     @logs = Hash.new
-    Dir.mkdir("#{@bot.botclass}/logs") unless File.exist?("#{@bot.botclass}/logs")
+    logdir = @bot.path 'logs'
+    Dir.mkdir(logdir) unless File.exist?(logdir)
+    # TODO what shall we do if the logdir couldn't be created? (e.g. it existed as a file)
     event_irclog_list_changed(@bot.config['irclog.no_log'], @bot.config['irclog.do_log'])
     @fn_format = @bot.config['irclog.filename_format']
   end
@@ -244,7 +246,7 @@ class IrcLogModule < CoreBotModule
   end
 
   def logfilepath(where_str, now)
-    File.join(@bot.botclass, 'logs', now.strftime(@fn_format) % { :where => where_str })
+    @bot.path('logs', now.strftime(@fn_format) % { :where => where_str })
   end
 
   protected
index 5c44cf09f5317aa81ebebd2176b3deb431e7b1b3..8df9626c93ca8f9aab927a0e9ba875cac53b453d 100644 (file)
@@ -169,7 +169,7 @@ module ::Irc
     def Utils.bot=(b)
       debug "initializing utils"
       @@bot = b
-      @@safe_save_dir = "#{@@bot.botclass}/safe_save"
+      @@safe_save_dir = @@bot.path('safe_save')
     end
 
 
index fc3415786ad0ddffc0052a354cd3902917a97339..4e624f9b4e80b9d0aa64a00855ee4c72c5913894 100755 (executable)
@@ -11,7 +11,7 @@ module ::Irc
 class Bot
 class Wordlist
   def self.wordlist_base
-    @@wordlist_base ||= File.join(Utils.bot.botclass, 'wordlists')
+    @@wordlist_base ||= Utils.bot.path 'wordlists'
   end
 
   def self.get(path, options={})
index dd61c7207161e90e8a92347e2d8245b480bca6d7..704dafae31f8b5c5a8130199376fe0097bd3b4f2 100644 (file)
@@ -52,18 +52,20 @@ module Irc
     def initialize(bot, key, absfilename=false)
       @bot = bot
       @key = key
+      relfilename = @bot.path key
+      relfilename << '.db'
       if absfilename && File.exist?(key)
         # db already exists, use it
         @db = DBHash.open_db(key)
-      elsif File.exist?(@bot.botclass + "/#{key}.db")
-        # db already exists, use it
-        @db = DBHash.open_db(@bot.botclass + "/#{key}.db")
       elsif absfilename
         # create empty db
         @db = DBHash.create_db(key)
+      elsif File.exist? relfilename
+        # db already exists, use it
+        @db = DBHash.open_db relfilename
       else
         # create empty db
-        @db = DBHash.create_db(@bot.botclass + "/#{key}.db")
+        @db = DBHash.create_db relfilename
       end
     end
 
@@ -98,27 +100,30 @@ module Irc
       @key = key
       if @@env.nil?
         begin
-          @@env = BDB::Env.open("#{@bot.botclass}", BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER, "set_lg_max" => @@lg_max)
+          @@env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER, "set_lg_max" => @@lg_max)
           debug "DBTree: environment opened with max log size #{@@env.conf['lg_max']}"
         rescue => e
           debug "DBTree: failed to open environment: #{e.pretty_inspect}. Retrying ..."
-          @@env = BDB::Env.open("#{@bot.botclass}", BDB::INIT_TRANSACTION | BDB::CREATE |  BDB::RECOVER)
+          @@env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE |  BDB::RECOVER)
         end
-        #@@env = BDB::Env.open("#{@bot.botclass}", BDB::CREATE | BDB::INIT_MPOOL | BDB::RECOVER)
+        #@@env = BDB::Env.open(@bot.botclass, BDB::CREATE | BDB::INIT_MPOOL | BDB::RECOVER)
       end
 
+      relfilename = @bot.path key
+      relfilename << '.db'
+
       if absfilename && File.exist?(key)
         # db already exists, use it
         @db = DBTree.open_db(key)
       elsif absfilename
         # create empty db
         @db = DBTree.create_db(key)
-      elsif File.exist?(@bot.botclass + "/#{key}.db")
+      elsif File.exist? relfilename
         # db already exists, use it
-        @db = DBTree.open_db(@bot.botclass + "/#{key}.db")
+        @db = DBTree.open_db relfilename
       else
         # create empty db
-        @db = DBTree.create_db(@bot.botclass + "/#{key}.db")
+        @db = DBTree.create_db relfilename
       end
     end
 
index 6ae3e4edfa624d5ea0b69567527c596e076faad1..abf64618a80107c8792c49f802cb70a03e607814 100644 (file)
@@ -791,6 +791,12 @@ class Bot
     end
   end
 
+  # Return a path under the current botclass by joining the mentioned
+  # components. The components are automatically converted to String
+  def path(*components)
+    File.join(@botclass, *(components.map {|c| c.to_s}))
+  end
+
   def setup_plugins_path
     plugdir_default = File.join(Config::datadir, 'plugins')
     plugdir_local = File.join(@botclass, 'plugins')
index 4d51cfc5e845d380cef3b1e588755dfe33353ef5..9d5523e423c9f2a562e588666d1d46787d96a825 100644 (file)
@@ -349,6 +349,20 @@ module Plugins
         @bot.plugins.mark_priorities_dirty
       end
     end
+
+    # Directory name to be joined to the botclass to access data files. By
+    # default this is the plugin name itself, but may be overridden, for
+    # example by plugins that share their datafiles or for backwards
+    # compatibilty
+    def dirname
+      name
+    end
+
+    # Filename for a datafile built joining the botclass, plugin dirname and
+    # actual file name
+    def datafile(*fname)
+      @bot.path dirname, *fname
+    end
   end
 
   # A CoreBotModule is a BotModule that provides core functionality.
index 2ea2e5784441bb01b331556d29cb6ec16bb31df1..05425341a92e682d64d8d09eeb4e58628bcbc16d 100644 (file)
@@ -16,30 +16,30 @@ class Bot
     # NB this function is called _early_ in init(), pretty much all you have to
     # work with is @bot.botclass.
     def upgrade_data
-      if File.exist?("#{@bot.botclass}/registry.db")
+      oldreg = @bot.path 'registry.db'
+      newreg = @bot.path 'plugin_registry.db'
+      if File.exist?(oldreg)
         log _("upgrading old-style (rbot 0.9.5 or earlier) plugin registry to new format")
-        old = BDB::Hash.open("#{@bot.botclass}/registry.db", nil,
-                             "r+", 0600)
-        new = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
-                                BDB::CREATE | BDB::EXCL,
-                                0600)
+        old = BDB::Hash.open(oldreg, nil, "r+", 0600)
+        new = BDB::CIBtree.open(newreg, nil, BDB::CREATE | BDB::EXCL, 0600)
         old.each {|k,v|
           new[k] = v
         }
         old.close
         new.close
-        File.rename("#{@bot.botclass}/registry.db", "#{@bot.botclass}/registry.db.old")
+        File.rename(oldreg, oldreg + ".old")
       end
     end
 
     def upgrade_data2
-      if File.exist?("#{@bot.botclass}/plugin_registry.db")
-        Dir.mkdir("#{@bot.botclass}/registry") unless File.exist?("#{@bot.botclass}/registry")
-        env = BDB::Env.open("#{@bot.botclass}", BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER)# | BDB::TXN_NOSYNC)
+      oldreg = @bot.path 'plugin_registry.db'
+      newdir = @bot.path 'registry'
+      if File.exist?(oldreg)
+        Dir.mkdir(newdir) unless File.exist?(newdir)
+        env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER)# | BDB::TXN_NOSYNC)
         dbs = Hash.new
         log _("upgrading previous (rbot 0.9.9 or earlier) plugin registry to new split format")
-        old = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
-          "r+", 0600, "env" => env)
+        old = BDB::CIBtree.open(oldreg, nil, "r+", 0600, "env" => env)
         old.each {|k,v|
           prefix,key = k.split("/", 2)
           prefix.downcase!
@@ -64,7 +64,7 @@ class Bot
           dbs[prefix][key] = v
         }
         old.close
-        File.rename("#{@bot.botclass}/plugin_registry.db", "#{@bot.botclass}/plugin_registry.db.old")
+        File.rename(oldreg, oldreg + ".old")
         dbs.each {|k,v|
           log _("closing db #{k}")
           v.close
@@ -126,7 +126,7 @@ class Bot
     def initialize(bot, name)
       @bot = bot
       @name = name.downcase
-      @filename = "#{@bot.botclass}/registry/#{@name}"
+      @filename = @bot.path 'registry', @name
       dirs = File.dirname(@filename).split("/")
       dirs.length.times { |i|
         dir = dirs[0,i+1].join("/")+"/"