util.pluginloader: Add support for multiple plugin directories.
[prosody.git] / util / pluginloader.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local dir_sep, path_sep = package.config:match("^(%S+)%s(%S+)");
10 local plugin_dir = {};
11 for path in (CFG_PLUGINDIR or "./plugins/"):gsub("[/\\]", dir_sep):gmatch("[^"..path_sep.."]+") do
12         path = path..dir_sep; -- add path separator to path end
13         path = path:gsub(dir_sep..dir_sep.."+", dir_sep); -- coalesce multiple separaters
14         plugin_dir[#plugin_dir + 1] = path;
15 end
16
17 local io_open, os_time = io.open, os.time;
18 local loadstring, pairs = loadstring, pairs;
19
20 module "pluginloader"
21
22 local function load_file(name)
23         local file, err;
24         for i=1,#plugin_dir do
25                 file, err = io_open(plugin_dir[i]..name);
26                 if file then break; end
27         end
28         if not file then return file, err; end
29         local content = file:read("*a");
30         file:close();
31         return content, name;
32 end
33
34 function load_resource(plugin, resource, loader)
35         local path, name = plugin:match("([^/]*)/?(.*)");
36         if name == "" then
37                 if not resource then
38                         resource = "mod_"..plugin..".lua";
39                 end
40                 loader = loader or load_file;
41
42                 local content, err = loader(plugin.."/"..resource);
43                 if not content then content, err = loader(resource); end
44                 -- TODO add support for packed plugins
45                 
46                 return content, err;
47         else
48                 if not resource then
49                         resource = "mod_"..name..".lua";
50                 end
51                 loader = loader or load_file;
52
53                 local content, err = loader(plugin.."/"..resource);
54                 if not content then content, err = loader(path.."/"..resource); end
55                 -- TODO add support for packed plugins
56                 
57                 return content, err;
58         end
59 end
60
61 function load_code(plugin, resource)
62         local content, err = load_resource(plugin, resource);
63         if not content then return content, err; end
64         return loadstring(content, "@"..err);
65 end
66
67 return _M;