~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugin.py

  • Committer: Matthew Revell
  • Date: 2008-03-05 14:11:35 UTC
  • mto: This revision was merged to the branch mainline in revision 3263.
  • Revision ID: matthew.revell@canonical.com-20080305141135-96jf8j24b9crru6v
Added an admin-guide directory to doc/en and outlined headings for the admin guide in index.txt

Show diffs side-by-side

added added

removed removed

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