Ran update_copyright.py.
[be.git] / libbe / util / plugin.py
1 # Copyright (C) 2005-2010 Aaron Bentley <abentley@panoramicfeedback.com>
2 #                         Gianluca Montecchi <gian@grys.it>
3 #                         Marien Zwart <marien.zwart@gmail.com>
4 #                         W. Trevor King <wking@drexel.edu>
5 #
6 # This file is part of Bugs Everywhere.
7 #
8 # Bugs Everywhere is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by the
10 # Free Software Foundation, either version 2 of the License, or (at your
11 # option) any later version.
12 #
13 # Bugs Everywhere is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
20
21 """
22 Allow simple listing and loading of the various becommands and libbe
23 submodules (i.e. "plugins").
24 """
25
26 import os
27 import os.path
28 import sys
29
30
31 _PLUGIN_PATH = os.path.realpath(
32     os.path.dirname(
33         os.path.dirname(
34             os.path.dirname(__file__))))
35 if _PLUGIN_PATH not in sys.path:
36     sys.path.append(_PLUGIN_PATH)
37
38 def import_by_name(modname):
39     """
40     >>> mod = import_by_name('libbe.bugdir')
41     >>> 'BugDir' in dir(mod)
42     True
43     >>> import_by_name('libbe.highly_unlikely')
44     Traceback (most recent call last):
45       ...
46     ImportError: No module named highly_unlikely
47     """
48     module = __import__(modname)
49     components = modname.split('.')
50     for comp in components[1:]:
51         module = getattr(module, comp)
52     return module
53
54 def modnames(prefix):
55     """
56     >>> 'list' in [n for n in modnames('libbe.command')]
57     True
58     >>> 'plugin' in [n for n in modnames('libbe.util')]
59     True
60     """
61     components = prefix.split('.')
62     modfiles = os.listdir(os.path.join(_PLUGIN_PATH, *components))
63     modfiles.sort()
64     for modfile in modfiles:
65         if modfile.startswith('.'):
66             continue # the occasional emacs temporary file
67         if modfile.endswith('.py') and modfile != '__init__.py':
68             yield modfile[:-3]