c10fdf6525ae2e34868a5bf8bf90c3104664d920
[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 = io.open;
18 local envload = require "util.envload".envload;
19
20 module "pluginloader"
21
22 function load_file(names)
23         local file, err, path;
24         for i=1,#plugin_dir do
25                 for j=1,#names do
26                         path = plugin_dir[i]..names[j];
27                         file, err = io_open(path);
28                         if file then
29                                 local content = file:read("*a");
30                                 file:close();
31                                 return content, path;
32                         end
33                 end
34         end
35         return file, err;
36 end
37
38 function load_resource(plugin, resource)
39         resource = resource or "mod_"..plugin..".lua";
40
41         local names = {
42                 "mod_"..plugin.."/"..plugin.."/"..resource; -- mod_hello/hello/mod_hello.lua
43                 "mod_"..plugin.."/"..resource;              -- mod_hello/mod_hello.lua
44                 plugin.."/"..resource;                      -- hello/mod_hello.lua
45                 resource;                                   -- mod_hello.lua
46         };
47
48         return load_file(names);
49 end
50
51 function load_code(plugin, resource, env)
52         local content, err = load_resource(plugin, resource);
53         if not content then return content, err; end
54         local path = err;
55         local f, err = envload(content, "@"..path, env);
56         if not f then return f, err; end
57         return f, path;
58 end
59
60 return _M;