~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugin.py

  • Committer: Robert Collins
  • Date: 2007-07-04 08:08:13 UTC
  • mfrom: (2572 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2587.
  • Revision ID: robertc@robertcollins.net-20070704080813-wzebx0r88fvwj5rq
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
 
1
# Copyright (C) 2004, 2005 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
"""bzr python plugin support
19
 
 
20
 
Any python module in $BZR_PLUGIN_PATH will be imported upon initialization of
21
 
bzrlib. The module will be imported as 'bzrlib.plugins.$BASENAME(PLUGIN)'.
22
 
In the plugin's main body, it should update any bzrlib registries it wants to
23
 
extend; for example, to add new commands, import bzrlib.commands and add your
24
 
new command to the plugin_cmds variable.
 
18
"""bzr python plugin support.
 
19
 
 
20
When load_plugins() is invoked, any python module in any directory in
 
21
$BZR_PLUGIN_PATH will be imported.  The module will be imported as
 
22
'bzrlib.plugins.$BASENAME(PLUGIN)'.  In the plugin's main body, it should
 
23
update any bzrlib registries it wants to extend; for example, to add new
 
24
commands, import bzrlib.commands and add your new command to the plugin_cmds
 
25
variable.
 
26
 
 
27
BZR_PLUGIN_PATH is also honoured for any plugins imported via
 
28
'import bzrlib.plugins.PLUGINNAME', as long as set_plugins_path has been 
 
29
called.
25
30
"""
26
31
 
27
 
# TODO: Refactor this to make it more testable.  The main problem at the
28
 
# moment is that loading plugins affects the global process state -- for bzr
29
 
# in general use it's a reasonable assumption that all plugins are loaded at
30
 
# startup and then stay loaded, but this is less good for testing.
31
 
32
 
# Several specific issues:
33
 
#  - plugins can't be unloaded and will continue to effect later tests
34
 
#  - load_plugins does nothing if called a second time
35
 
#  - plugin hooks can't be removed
36
 
#
37
 
# Our options are either to remove these restrictions, or work around them by
38
 
# loading the plugins into a different space than the one running the tests.
39
 
# That could be either a separate Python interpreter or perhaps a new
40
 
# namespace inside this interpreter.
41
 
 
42
 
import imp
43
32
import os
44
33
import sys
 
34
 
 
35
from bzrlib.lazy_import import lazy_import
 
36
lazy_import(globals(), """
 
37
import imp
 
38
import re
45
39
import types
46
 
 
47
 
import bzrlib
48
 
from bzrlib.config import config_dir
49
 
from bzrlib.trace import log_error, mutter, warning, \
50
 
        log_exception_quietly
51
 
from bzrlib.errors import BzrError
52
 
from bzrlib import plugins
53
 
from bzrlib.osutils import pathjoin
54
 
 
55
 
DEFAULT_PLUGIN_PATH = pathjoin(config_dir(), 'plugins')
56
 
 
 
40
import zipimport
 
41
 
 
42
from bzrlib import (
 
43
    config,
 
44
    osutils,
 
45
    plugins,
 
46
    )
 
47
""")
 
48
 
 
49
from bzrlib.trace import mutter, warning, log_exception_quietly
 
50
 
 
51
 
 
52
DEFAULT_PLUGIN_PATH = None
57
53
_loaded = False
58
54
 
 
55
def get_default_plugin_path():
 
56
    """Get the DEFAULT_PLUGIN_PATH"""
 
57
    global DEFAULT_PLUGIN_PATH
 
58
    if DEFAULT_PLUGIN_PATH is None:
 
59
        DEFAULT_PLUGIN_PATH = osutils.pathjoin(config.config_dir(), 'plugins')
 
60
    return DEFAULT_PLUGIN_PATH
 
61
 
59
62
 
60
63
def all_plugins():
61
64
    """Return a dictionary of the plugins."""
62
65
    result = {}
63
 
    for name, plugin in bzrlib.plugins.__dict__.items():
 
66
    for name, plugin in plugins.__dict__.items():
64
67
        if isinstance(plugin, types.ModuleType):
65
68
            result[name] = plugin
66
69
    return result
77
80
    _loaded = True
78
81
 
79
82
 
 
83
def set_plugins_path():
 
84
    """Set the path for plugins to be loaded from."""
 
85
    path = os.environ.get('BZR_PLUGIN_PATH',
 
86
                          get_default_plugin_path()).split(os.pathsep)
 
87
    # search the plugin path before the bzrlib installed dir
 
88
    path.append(os.path.dirname(plugins.__file__))
 
89
    plugins.__path__ = path
 
90
    return path
 
91
 
 
92
 
80
93
def load_plugins():
81
94
    """Load bzrlib plugins.
82
95
 
92
105
    if _loaded:
93
106
        # People can make sure plugins are loaded, they just won't be twice
94
107
        return
95
 
        #raise BzrError("plugins already initialized")
96
108
    _loaded = True
97
109
 
98
 
    dirs = os.environ.get('BZR_PLUGIN_PATH', DEFAULT_PLUGIN_PATH).split(os.pathsep)
99
 
    dirs.insert(0, os.path.dirname(plugins.__file__))
100
 
 
101
 
    load_from_dirs(dirs)
102
 
 
103
 
 
104
 
def load_from_dirs(dirs):
 
110
    # scan for all plugins in the path.
 
111
    load_from_path(set_plugins_path())
 
112
 
 
113
 
 
114
def load_from_path(dirs):
105
115
    """Load bzrlib plugins found in each dir in dirs.
106
116
 
107
117
    Loading a plugin means importing it into the python interpreter.
110
120
 
111
121
    Plugins are loaded into bzrlib.plugins.NAME, and can be found there
112
122
    for future reference.
 
123
 
 
124
    The python module path for bzrlib.plugins will be modified to be 'dirs'.
113
125
    """
 
126
    plugins.__path__ = dirs
 
127
    for d in dirs:
 
128
        if not d:
 
129
            continue
 
130
        mutter('looking for plugins in %s', d)
 
131
        if os.path.isdir(d):
 
132
            load_from_dir(d)
 
133
        else:
 
134
            # it might be a zip: try loading from the zip.
 
135
            load_from_zip(d)
 
136
            continue
 
137
 
 
138
 
 
139
# backwards compatability: load_from_dirs was the old name
 
140
# This was changed in 0.15
 
141
load_from_dirs = load_from_path
 
142
 
 
143
 
 
144
def load_from_dir(d):
 
145
    """Load the plugins in directory d."""
114
146
    # Get the list of valid python suffixes for __init__.py?
115
147
    # this includes .py, .pyc, and .pyo (depending on if we are running -O)
116
148
    # but it doesn't include compiled modules (.so, .dll, etc)
117
149
    valid_suffixes = [suffix for suffix, mod_type, flags in imp.get_suffixes()
118
150
                              if flags in (imp.PY_SOURCE, imp.PY_COMPILED)]
119
151
    package_entries = ['__init__'+suffix for suffix in valid_suffixes]
120
 
    for d in dirs:
121
 
        if not d:
122
 
            continue
123
 
        mutter('looking for plugins in %s', d)
124
 
        plugin_names = set()
125
 
        if not os.path.isdir(d):
126
 
            continue
127
 
        for f in os.listdir(d):
128
 
            path = pathjoin(d, f)
129
 
            if os.path.isdir(path):
130
 
                for entry in package_entries:
131
 
                    # This directory should be a package, and thus added to
132
 
                    # the list
133
 
                    if os.path.isfile(pathjoin(path, entry)):
134
 
                        break
135
 
                else: # This directory is not a package
136
 
                    continue
137
 
            else:
138
 
                for suffix_info in imp.get_suffixes():
139
 
                    if f.endswith(suffix_info[0]):
140
 
                        f = f[:-len(suffix_info[0])]
141
 
                        if suffix_info[2] == imp.C_EXTENSION and f.endswith('module'):
142
 
                            f = f[:-len('module')]
143
 
                        break
144
 
                else:
145
 
                    continue
146
 
            if getattr(bzrlib.plugins, f, None):
147
 
                mutter('Plugin name %s already loaded', f)
148
 
            else:
149
 
                mutter('add plugin name %s', f)
150
 
                plugin_names.add(f)
151
 
 
152
 
        plugin_names = list(plugin_names)
153
 
        plugin_names.sort()
154
 
        for name in plugin_names:
155
 
            try:
156
 
                plugin_info = imp.find_module(name, [d])
157
 
                mutter('load plugin %r', plugin_info)
158
 
                try:
159
 
                    plugin = imp.load_module('bzrlib.plugins.' + name,
160
 
                                             *plugin_info)
161
 
                    setattr(bzrlib.plugins, name, plugin)
162
 
                finally:
163
 
                    if plugin_info[0] is not None:
164
 
                        plugin_info[0].close()
165
 
 
166
 
                mutter('loaded succesfully')
167
 
            except KeyboardInterrupt:
168
 
                raise
169
 
            except Exception, e:
170
 
                ## import pdb; pdb.set_trace()
 
152
    plugin_names = set()
 
153
    for f in os.listdir(d):
 
154
        path = osutils.pathjoin(d, f)
 
155
        if os.path.isdir(path):
 
156
            for entry in package_entries:
 
157
                # This directory should be a package, and thus added to
 
158
                # the list
 
159
                if os.path.isfile(osutils.pathjoin(path, entry)):
 
160
                    break
 
161
            else: # This directory is not a package
 
162
                continue
 
163
        else:
 
164
            for suffix_info in imp.get_suffixes():
 
165
                if f.endswith(suffix_info[0]):
 
166
                    f = f[:-len(suffix_info[0])]
 
167
                    if suffix_info[2] == imp.C_EXTENSION and f.endswith('module'):
 
168
                        f = f[:-len('module')]
 
169
                    break
 
170
            else:
 
171
                continue
 
172
        if getattr(plugins, f, None):
 
173
            mutter('Plugin name %s already loaded', f)
 
174
        else:
 
175
            # mutter('add plugin name %s', f)
 
176
            plugin_names.add(f)
 
177
    
 
178
    for name in plugin_names:
 
179
        try:
 
180
            exec "import bzrlib.plugins.%s" % name in {}
 
181
        except KeyboardInterrupt:
 
182
            raise
 
183
        except Exception, e:
 
184
            ## import pdb; pdb.set_trace()
 
185
            if re.search('\.|-| ', name):
 
186
                warning('Unable to load plugin %r from %r: '
 
187
                    'It is not a valid python module name.' % (name, d))
 
188
            else:
171
189
                warning('Unable to load plugin %r from %r' % (name, d))
172
 
                log_exception_quietly()
 
190
            log_exception_quietly()
 
191
 
 
192
 
 
193
def load_from_zip(zip_name):
 
194
    """Load all the plugins in a zip."""
 
195
    valid_suffixes = ('.py', '.pyc', '.pyo')    # only python modules/packages
 
196
                                                # is allowed
 
197
    if '.zip' not in zip_name:
 
198
        return
 
199
    try:
 
200
        ziobj = zipimport.zipimporter(zip_name)
 
201
    except zipimport.ZipImportError:
 
202
        # not a valid zip
 
203
        return
 
204
    mutter('Looking for plugins in %r', zip_name)
 
205
    
 
206
    import zipfile
 
207
 
 
208
    # use zipfile to get list of files/dirs inside zip
 
209
    z = zipfile.ZipFile(ziobj.archive)
 
210
    namelist = z.namelist()
 
211
    z.close()
 
212
    
 
213
    if ziobj.prefix:
 
214
        prefix = ziobj.prefix.replace('\\','/')
 
215
        ix = len(prefix)
 
216
        namelist = [name[ix:]
 
217
                    for name in namelist
 
218
                    if name.startswith(prefix)]
 
219
    
 
220
    mutter('Names in archive: %r', namelist)
 
221
    
 
222
    for name in namelist:
 
223
        if not name or name.endswith('/'):
 
224
            continue
 
225
    
 
226
        # '/' is used to separate pathname components inside zip archives
 
227
        ix = name.rfind('/')
 
228
        if ix == -1:
 
229
            head, tail = '', name
 
230
        else:
 
231
            head, tail = name.rsplit('/',1)
 
232
        if '/' in head:
 
233
            # we don't need looking in subdirectories
 
234
            continue
 
235
    
 
236
        base, suffix = osutils.splitext(tail)
 
237
        if suffix not in valid_suffixes:
 
238
            continue
 
239
    
 
240
        if base == '__init__':
 
241
            # package
 
242
            plugin_name = head
 
243
        elif head == '':
 
244
            # module
 
245
            plugin_name = base
 
246
        else:
 
247
            continue
 
248
    
 
249
        if not plugin_name:
 
250
            continue
 
251
        if getattr(plugins, plugin_name, None):
 
252
            mutter('Plugin name %s already loaded', plugin_name)
 
253
            continue
 
254
    
 
255
        try:
 
256
            plugin = ziobj.load_module(plugin_name)
 
257
            setattr(plugins, plugin_name, plugin)
 
258
            mutter('Load plugin %s from zip %r', plugin_name, zip_name)
 
259
        except zipimport.ZipImportError, e:
 
260
            mutter('Unable to load plugin %r from %r: %s',
 
261
                   plugin_name, zip_name, str(e))
 
262
            continue
 
263
        except KeyboardInterrupt:
 
264
            raise
 
265
        except Exception, e:
 
266
            ## import pdb; pdb.set_trace()
 
267
            warning('Unable to load plugin %r from %r'
 
268
                    % (name, zip_name))
 
269
            log_exception_quietly()
 
270
 
 
271
 
 
272
class PluginsHelpIndex(object):
 
273
    """A help index that returns help topics for plugins."""
 
274
 
 
275
    def __init__(self):
 
276
        self.prefix = 'plugins/'
 
277
 
 
278
    def get_topics(self, topic):
 
279
        """Search for topic in the loaded plugins.
 
280
 
 
281
        This will not trigger loading of new plugins.
 
282
 
 
283
        :param topic: A topic to search for.
 
284
        :return: A list which is either empty or contains a single
 
285
            RegisteredTopic entry.
 
286
        """
 
287
        if not topic:
 
288
            return []
 
289
        if topic.startswith(self.prefix):
 
290
            topic = topic[len(self.prefix):]
 
291
        plugin_module_name = 'bzrlib.plugins.%s' % topic
 
292
        try:
 
293
            module = sys.modules[plugin_module_name]
 
294
        except KeyError:
 
295
            return []
 
296
        else:
 
297
            return [ModuleHelpTopic(module)]
 
298
 
 
299
 
 
300
class ModuleHelpTopic(object):
 
301
    """A help topic which returns the docstring for a module."""
 
302
 
 
303
    def __init__(self, module):
 
304
        """Constructor.
 
305
 
 
306
        :param module: The module for which help should be generated.
 
307
        """
 
308
        self.module = module
 
309
 
 
310
    def get_help_text(self, additional_see_also=None):
 
311
        """Return a string with the help for this topic.
 
312
 
 
313
        :param additional_see_also: Additional help topics to be
 
314
            cross-referenced.
 
315
        """
 
316
        if not self.module.__doc__:
 
317
            result = "Plugin '%s' has no docstring.\n" % self.module.__name__
 
318
        else:
 
319
            result = self.module.__doc__
 
320
        if result[-1] != '\n':
 
321
            result += '\n'
 
322
        # there is code duplicated here and in bzrlib/help_topic.py's 
 
323
        # matching Topic code. This should probably be factored in
 
324
        # to a helper function and a common base class.
 
325
        if additional_see_also is not None:
 
326
            see_also = sorted(set(additional_see_also))
 
327
        else:
 
328
            see_also = None
 
329
        if see_also:
 
330
            result += 'See also: '
 
331
            result += ', '.join(see_also)
 
332
            result += '\n'
 
333
        return result
 
334
 
 
335
    def get_help_topic(self):
 
336
        """Return the modules help topic - its __name__ after bzrlib.plugins.."""
 
337
        return self.module.__name__[len('bzrlib.plugins.'):]