~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugin.py

  • Committer: John Arbash Meinel
  • Date: 2010-02-17 17:11:16 UTC
  • mfrom: (4797.2.17 2.1)
  • mto: (4797.2.18 2.1)
  • mto: This revision was merged to the branch mainline in revision 5055.
  • Revision ID: john@arbash-meinel.com-20100217171116-h7t9223ystbnx5h8
merge bzr.2.1 in preparation for NEWS entry.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2007 Canonical Ltd
 
1
# Copyright (C) 2004, 2005, 2007, 2008 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
"""bzr python plugin support.
20
20
When load_plugins() is invoked, any python module in any directory in
21
21
$BZR_PLUGIN_PATH will be imported.  The module will be imported as
22
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.
 
23
update any bzrlib registries it wants to extend.
 
24
 
 
25
See the plugin-api developer documentation for information about writing
 
26
plugins.
26
27
 
27
28
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
'import bzrlib.plugins.PLUGINNAME', as long as set_plugins_path has been
29
30
called.
30
31
"""
31
32
 
32
33
import os
33
34
import sys
34
35
 
 
36
from bzrlib import osutils
 
37
 
35
38
from bzrlib.lazy_import import lazy_import
 
39
 
36
40
lazy_import(globals(), """
37
41
import imp
38
42
import re
39
43
import types
40
 
import zipfile
41
44
 
42
45
from bzrlib import (
 
46
    _format_version_tuple,
43
47
    config,
44
 
    osutils,
 
48
    debug,
 
49
    errors,
 
50
    trace,
45
51
    )
46
52
from bzrlib import plugins as _mod_plugins
47
53
""")
48
54
 
49
 
from bzrlib.symbol_versioning import deprecated_function, zero_ninetyone
50
 
from bzrlib.trace import mutter, warning, log_exception_quietly
 
55
from bzrlib.symbol_versioning import (
 
56
    deprecated_function,
 
57
    deprecated_in,
 
58
    )
51
59
 
52
60
 
53
61
DEFAULT_PLUGIN_PATH = None
54
62
_loaded = False
55
63
 
 
64
@deprecated_function(deprecated_in((2, 0, 0)))
56
65
def get_default_plugin_path():
57
66
    """Get the DEFAULT_PLUGIN_PATH"""
58
67
    global DEFAULT_PLUGIN_PATH
61
70
    return DEFAULT_PLUGIN_PATH
62
71
 
63
72
 
64
 
@deprecated_function(zero_ninetyone)
65
 
def all_plugins():
66
 
    """Return a dictionary of the plugins."""
67
 
    return dict((name, plugin.module) for name, plugin in plugins().items())
68
 
 
69
 
 
70
73
def disable_plugins():
71
74
    """Disable loading plugins.
72
75
 
73
76
    Future calls to load_plugins() will be ignored.
74
77
    """
75
 
    # TODO: jam 20060131 This should probably also disable
76
 
    #       load_from_dirs()
77
 
    global _loaded
78
 
    _loaded = True
 
78
    load_plugins([])
 
79
 
79
80
 
80
81
def _strip_trailing_sep(path):
81
82
    return path.rstrip("\\/")
82
83
 
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)
 
84
 
 
85
def set_plugins_path(path=None):
 
86
    """Set the path for plugins to be loaded from.
 
87
 
 
88
    :param path: The list of paths to search for plugins.  By default,
 
89
        path will be determined using get_standard_plugins_path.
 
90
        if path is [], no plugins can be loaded.
 
91
    """
 
92
    if path is None:
 
93
        path = get_standard_plugins_path()
 
94
    _mod_plugins.__path__ = path
 
95
    return path
 
96
 
 
97
 
 
98
def _append_new_path(paths, new_path):
 
99
    """Append a new path if it set and not already known."""
 
100
    if new_path is not None and new_path not in paths:
 
101
        paths.append(new_path)
 
102
    return paths
 
103
 
 
104
 
 
105
def get_core_plugin_path():
 
106
    core_path = None
 
107
    bzr_exe = bool(getattr(sys, 'frozen', None))
 
108
    if bzr_exe:    # expand path for bzr.exe
 
109
        # We need to use relative path to system-wide plugin
 
110
        # directory because bzrlib from standalone bzr.exe
 
111
        # could be imported by another standalone program
 
112
        # (e.g. bzr-config; or TortoiseBzr/Olive if/when they
 
113
        # will become standalone exe). [bialix 20071123]
 
114
        # __file__ typically is
 
115
        # C:\Program Files\Bazaar\lib\library.zip\bzrlib\plugin.pyc
 
116
        # then plugins directory is
 
117
        # C:\Program Files\Bazaar\plugins
 
118
        # so relative path is ../../../plugins
 
119
        core_path = osutils.abspath(osutils.pathjoin(
 
120
                osutils.dirname(__file__), '../../../plugins'))
 
121
    else:     # don't look inside library.zip
 
122
        # search the plugin path before the bzrlib installed dir
 
123
        core_path = os.path.dirname(_mod_plugins.__file__)
 
124
    return core_path
 
125
 
 
126
 
 
127
def get_site_plugin_path():
 
128
    """Returns the path for the site installed plugins."""
 
129
    if sys.platform == 'win32':
 
130
        # We don't have (yet) a good answer for windows since that is certainly
 
131
        # related to the way we build the installers. -- vila20090821
 
132
        return None
 
133
    site_path = None
 
134
    try:
 
135
        from distutils.sysconfig import get_python_lib
 
136
    except ImportError:
 
137
        # If distutuils is not available, we just don't know where they are
 
138
        pass
 
139
    else:
 
140
        site_path = osutils.pathjoin(get_python_lib(), 'bzrlib', 'plugins')
 
141
    return site_path
 
142
 
 
143
 
 
144
def get_user_plugin_path():
 
145
    return osutils.pathjoin(config.config_dir(), 'plugins')
 
146
 
 
147
 
 
148
def get_standard_plugins_path():
 
149
    """Determine a plugin path suitable for general use."""
 
150
    # Ad-Hoc default: core is not overriden by site but user can overrides both
 
151
    # The rationale is that:
 
152
    # - 'site' comes last, because these plugins should always be available and
 
153
    #   are supposed to be in sync with the bzr installed on site.
 
154
    # - 'core' comes before 'site' so that running bzr from sources or a user
 
155
    #   installed version overrides the site version.
 
156
    # - 'user' comes first, because... user is always right.
 
157
    # - the above rules clearly defines which plugin version will be loaded if
 
158
    #   several exist. Yet, it is sometimes desirable to disable some directory
 
159
    #   so that a set of plugins is disabled as once. This can be done via
 
160
    #   -site, -core, -user.
 
161
 
 
162
    env_paths = os.environ.get('BZR_PLUGIN_PATH', '+user').split(os.pathsep)
 
163
    defaults = ['+core', '+site']
 
164
 
 
165
    # The predefined references
 
166
    refs = dict(core=get_core_plugin_path(),
 
167
                site=get_site_plugin_path(),
 
168
                user=get_user_plugin_path())
 
169
 
 
170
    # Unset paths that should be removed
 
171
    for k,v in refs.iteritems():
 
172
        removed = '-%s' % k
 
173
        # defaults can never mention removing paths as that will make it
 
174
        # impossible for the user to revoke these removals.
 
175
        if removed in env_paths:
 
176
            env_paths.remove(removed)
 
177
            refs[k] = None
 
178
 
 
179
    # Expand references
 
180
    paths = []
 
181
    for p in env_paths + defaults:
 
182
        if p.startswith('+'):
 
183
            # Resolve reference if they are known
 
184
            try:
 
185
                p = refs[p[1:]]
 
186
            except KeyError:
 
187
                # Leave them untouched otherwise, user may have paths starting
 
188
                # with '+'...
 
189
                pass
 
190
        _append_new_path(paths, p)
 
191
 
87
192
    # Get rid of trailing slashes, since Python can't handle them when
88
193
    # it tries to import modules.
89
 
    path = map(_strip_trailing_sep, path)
90
 
    # search the plugin path before the bzrlib installed dir
91
 
    path.append(os.path.dirname(_mod_plugins.__file__))
92
 
    _mod_plugins.__path__ = path
93
 
    return path
94
 
 
95
 
 
96
 
def load_plugins():
 
194
    paths = map(_strip_trailing_sep, paths)
 
195
    return paths
 
196
 
 
197
 
 
198
def load_plugins(path=None):
97
199
    """Load bzrlib plugins.
98
200
 
99
201
    The environment variable BZR_PLUGIN_PATH is considered a delimited
103
205
 
104
206
    load_from_dirs() provides the underlying mechanism and is called with
105
207
    the default directory list to provide the normal behaviour.
 
208
 
 
209
    :param path: The list of paths to search for plugins.  By default,
 
210
        path will be determined using get_standard_plugins_path.
 
211
        if path is [], no plugins can be loaded.
106
212
    """
107
213
    global _loaded
108
214
    if _loaded:
111
217
    _loaded = True
112
218
 
113
219
    # scan for all plugins in the path.
114
 
    load_from_path(set_plugins_path())
 
220
    load_from_path(set_plugins_path(path))
115
221
 
116
222
 
117
223
def load_from_path(dirs):
135
241
    for d in dirs:
136
242
        if not d:
137
243
            continue
138
 
        mutter('looking for plugins in %s', d)
 
244
        trace.mutter('looking for plugins in %s', d)
139
245
        if os.path.isdir(d):
140
246
            load_from_dir(d)
141
 
        else:
142
 
            # it might be a zip: try loading from the zip.
143
 
            load_from_zip(d)
144
 
            continue
145
247
 
146
248
 
147
249
# backwards compatability: load_from_dirs was the old name
150
252
 
151
253
 
152
254
def load_from_dir(d):
153
 
    """Load the plugins in directory d."""
 
255
    """Load the plugins in directory d.
 
256
 
 
257
    d must be in the plugins module path already.
 
258
    """
154
259
    # Get the list of valid python suffixes for __init__.py?
155
260
    # this includes .py, .pyc, and .pyo (depending on if we are running -O)
156
261
    # but it doesn't include compiled modules (.so, .dll, etc)
177
282
                    break
178
283
            else:
179
284
                continue
180
 
        if getattr(_mod_plugins, f, None):
181
 
            mutter('Plugin name %s already loaded', f)
 
285
        if f == '__init__':
 
286
            continue # We don't load __init__.py again in the plugin dir
 
287
        elif getattr(_mod_plugins, f, None):
 
288
            trace.mutter('Plugin name %s already loaded', f)
182
289
        else:
183
 
            # mutter('add plugin name %s', f)
 
290
            # trace.mutter('add plugin name %s', f)
184
291
            plugin_names.add(f)
185
 
    
 
292
 
186
293
    for name in plugin_names:
187
294
        try:
188
295
            exec "import bzrlib.plugins.%s" % name in {}
189
296
        except KeyboardInterrupt:
190
297
            raise
 
298
        except errors.IncompatibleAPI, e:
 
299
            trace.warning("Unable to load plugin %r. It requested API version "
 
300
                "%s of module %s but the minimum exported version is %s, and "
 
301
                "the maximum is %s" %
 
302
                (name, e.wanted, e.api, e.minimum, e.current))
191
303
        except Exception, e:
 
304
            trace.warning("%s" % e)
192
305
            ## import pdb; pdb.set_trace()
193
306
            if re.search('\.|-| ', name):
194
 
                warning('Unable to load plugin %r from %r: '
195
 
                    'It is not a valid python module name.' % (name, d))
 
307
                sanitised_name = re.sub('[-. ]', '_', name)
 
308
                if sanitised_name.startswith('bzr_'):
 
309
                    sanitised_name = sanitised_name[len('bzr_'):]
 
310
                trace.warning("Unable to load %r in %r as a plugin because the "
 
311
                        "file path isn't a valid module name; try renaming "
 
312
                        "it to %r." % (name, d, sanitised_name))
196
313
            else:
197
 
                warning('Unable to load plugin %r from %r' % (name, d))
198
 
            log_exception_quietly()
199
 
 
200
 
 
201
 
def load_from_zip(zip_name):
202
 
    """Load all the plugins in a zip."""
203
 
    valid_suffixes = ('.py', '.pyc', '.pyo')    # only python modules/packages
204
 
                                                # is allowed
205
 
 
206
 
    try:
207
 
        index = zip_name.rindex('.zip')
208
 
    except ValueError:
209
 
        return
210
 
    archive = zip_name[:index+4]
211
 
    prefix = zip_name[index+5:]
212
 
 
213
 
    mutter('Looking for plugins in %r', zip_name)
214
 
 
215
 
    # use zipfile to get list of files/dirs inside zip
216
 
    try:
217
 
        z = zipfile.ZipFile(archive)
218
 
        namelist = z.namelist()
219
 
        z.close()
220
 
    except zipfile.error:
221
 
        # not a valid zip
222
 
        return
223
 
 
224
 
    if prefix:
225
 
        prefix = prefix.replace('\\','/')
226
 
        if prefix[-1] != '/':
227
 
            prefix += '/'
228
 
        ix = len(prefix)
229
 
        namelist = [name[ix:]
230
 
                    for name in namelist
231
 
                    if name.startswith(prefix)]
232
 
 
233
 
    mutter('Names in archive: %r', namelist)
234
 
    
235
 
    for name in namelist:
236
 
        if not name or name.endswith('/'):
237
 
            continue
238
 
    
239
 
        # '/' is used to separate pathname components inside zip archives
240
 
        ix = name.rfind('/')
241
 
        if ix == -1:
242
 
            head, tail = '', name
243
 
        else:
244
 
            head, tail = name.rsplit('/',1)
245
 
        if '/' in head:
246
 
            # we don't need looking in subdirectories
247
 
            continue
248
 
    
249
 
        base, suffix = osutils.splitext(tail)
250
 
        if suffix not in valid_suffixes:
251
 
            continue
252
 
    
253
 
        if base == '__init__':
254
 
            # package
255
 
            plugin_name = head
256
 
        elif head == '':
257
 
            # module
258
 
            plugin_name = base
259
 
        else:
260
 
            continue
261
 
    
262
 
        if not plugin_name:
263
 
            continue
264
 
        if getattr(_mod_plugins, plugin_name, None):
265
 
            mutter('Plugin name %s already loaded', plugin_name)
266
 
            continue
267
 
    
268
 
        try:
269
 
            exec "import bzrlib.plugins.%s" % plugin_name in {}
270
 
            mutter('Load plugin %s from zip %r', plugin_name, zip_name)
271
 
        except KeyboardInterrupt:
272
 
            raise
273
 
        except Exception, e:
274
 
            ## import pdb; pdb.set_trace()
275
 
            warning('Unable to load plugin %r from %r'
276
 
                    % (name, zip_name))
277
 
            log_exception_quietly()
 
314
                trace.warning('Unable to load plugin %r from %r' % (name, d))
 
315
            trace.log_exception_quietly()
 
316
            if 'error' in debug.debug_flags:
 
317
                trace.print_exception(sys.exc_info(), sys.stderr)
278
318
 
279
319
 
280
320
def plugins():
281
321
    """Return a dictionary of the plugins.
282
 
    
 
322
 
283
323
    Each item in the dictionary is a PlugIn object.
284
324
    """
285
325
    result = {}
327
367
        """
328
368
        self.module = module
329
369
 
330
 
    def get_help_text(self, additional_see_also=None):
 
370
    def get_help_text(self, additional_see_also=None, verbose=True):
331
371
        """Return a string with the help for this topic.
332
372
 
333
373
        :param additional_see_also: Additional help topics to be
339
379
            result = self.module.__doc__
340
380
        if result[-1] != '\n':
341
381
            result += '\n'
342
 
        # there is code duplicated here and in bzrlib/help_topic.py's 
 
382
        # there is code duplicated here and in bzrlib/help_topic.py's
343
383
        # matching Topic code. This should probably be factored in
344
384
        # to a helper function and a common base class.
345
385
        if additional_see_also is not None:
373
413
        if getattr(self.module, '__path__', None) is not None:
374
414
            return os.path.abspath(self.module.__path__[0])
375
415
        elif getattr(self.module, '__file__', None) is not None:
376
 
            return os.path.abspath(self.module.__file__)
 
416
            path = os.path.abspath(self.module.__file__)
 
417
            if path[-4:] in ('.pyc', '.pyo'):
 
418
                pypath = path[:-4] + '.py'
 
419
                if os.path.isfile(pypath):
 
420
                    path = pypath
 
421
            return path
377
422
        else:
378
423
            return repr(self.module)
379
424
 
391
436
        else:
392
437
            return None
393
438
 
 
439
    def load_plugin_tests(self, loader):
 
440
        """Return the adapted plugin's test suite.
 
441
 
 
442
        :param loader: The custom loader that should be used to load additional
 
443
            tests.
 
444
 
 
445
        """
 
446
        if getattr(self.module, 'load_tests', None) is not None:
 
447
            return loader.loadTestsFromModule(self.module)
 
448
        else:
 
449
            return None
 
450
 
394
451
    def version_info(self):
395
452
        """Return the plugin's version_tuple or None if unknown."""
396
453
        version_info = getattr(self.module, 'version_info', None)
397
 
        if version_info is not None and len(version_info) == 3:
398
 
            version_info = tuple(version_info) + ('final', 0)
 
454
        if version_info is not None:
 
455
            try:
 
456
                if isinstance(version_info, types.StringType):
 
457
                    version_info = version_info.split('.')
 
458
                elif len(version_info) == 3:
 
459
                    version_info = tuple(version_info) + ('final', 0)
 
460
            except TypeError, e:
 
461
                # The given version_info isn't even iteratible
 
462
                trace.log_exception_quietly()
 
463
                version_info = (version_info,)
399
464
        return version_info
400
 
    
 
465
 
401
466
    def _get__version__(self):
402
467
        version_info = self.version_info()
403
 
        if version_info is None:
 
468
        if version_info is None or len(version_info) == 0:
404
469
            return "unknown"
405
 
        if version_info[3] == 'final':
406
 
            version_string = '%d.%d.%d' % version_info[:3]
407
 
        else:
408
 
            version_string = '%d.%d.%d%s%d' % version_info
 
470
        try:
 
471
            version_string = _format_version_tuple(version_info)
 
472
        except (ValueError, TypeError, IndexError), e:
 
473
            trace.log_exception_quietly()
 
474
            # try to return something usefull for bad plugins, in stead of
 
475
            # stack tracing.
 
476
            version_string = '.'.join(map(str, version_info))
409
477
        return version_string
410
478
 
411
479
    __version__ = property(_get__version__)