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.
25
See the plugin-api developer documentation for information about writing
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
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
36
from bzrlib import osutils
38
35
from bzrlib.lazy_import import lazy_import
40
36
lazy_import(globals(), """
45
42
from bzrlib import (
46
_format_version_tuple,
52
from bzrlib import plugins as _mod_plugins
55
from bzrlib.symbol_versioning import (
49
from bzrlib.trace import mutter, warning, log_exception_quietly
61
52
DEFAULT_PLUGIN_PATH = None
63
_plugins_disabled = False
66
def are_plugins_disabled():
67
return _plugins_disabled
70
@deprecated_function(deprecated_in((2, 0, 0)))
71
55
def get_default_plugin_path():
72
56
"""Get the DEFAULT_PLUGIN_PATH"""
73
57
global DEFAULT_PLUGIN_PATH
76
60
return DEFAULT_PLUGIN_PATH
64
"""Return a dictionary of the plugins."""
66
for name, plugin in plugins.__dict__.items():
67
if isinstance(plugin, types.ModuleType):
79
72
def disable_plugins():
80
73
"""Disable loading plugins.
82
75
Future calls to load_plugins() will be ignored.
84
global _plugins_disabled
85
_plugins_disabled = True
89
def _strip_trailing_sep(path):
90
return path.rstrip("\\/")
93
def set_plugins_path(path=None):
94
"""Set the path for plugins to be loaded from.
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.
101
path = get_standard_plugins_path()
102
_mod_plugins.__path__ = path
77
# TODO: jam 20060131 This should probably also disable
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
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)
113
def get_core_plugin_path():
115
bzr_exe = bool(getattr(sys, 'frozen', None))
116
if bzr_exe: # expand path for bzr.exe
117
# We need to use relative path to system-wide plugin
118
# directory because bzrlib from standalone bzr.exe
119
# could be imported by another standalone program
120
# (e.g. bzr-config; or TortoiseBzr/Olive if/when they
121
# will become standalone exe). [bialix 20071123]
122
# __file__ typically is
123
# C:\Program Files\Bazaar\lib\library.zip\bzrlib\plugin.pyc
124
# then plugins directory is
125
# C:\Program Files\Bazaar\plugins
126
# 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__)
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
143
from distutils.sysconfig import get_python_lib
145
# If distutuils is not available, we just don't know where they are
148
site_path = osutils.pathjoin(get_python_lib(), 'bzrlib', 'plugins')
152
def get_user_plugin_path():
153
return osutils.pathjoin(config.config_dir(), 'plugins')
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.
170
env_paths = os.environ.get('BZR_PLUGIN_PATH', '+user').split(os.pathsep)
171
defaults = ['+core', '+site']
173
# The predefined references
174
refs = dict(core=get_core_plugin_path(),
175
site=get_site_plugin_path(),
176
user=get_user_plugin_path())
178
# Unset paths that should be removed
179
for k,v in refs.iteritems():
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)
189
for p in env_paths + defaults:
190
if p.startswith('+'):
191
# Resolve reference if they are known
195
# Leave them untouched otherwise, user may have paths starting
198
_append_new_path(paths, p)
200
# Get rid of trailing slashes, since Python can't handle them when
201
# it tries to import modules.
202
paths = map(_strip_trailing_sep, paths)
206
def load_plugins(path=None):
207
94
"""Load bzrlib plugins.
209
96
The environment variable BZR_PLUGIN_PATH is considered a delimited
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)
172
if getattr(plugins, f, None):
173
mutter('Plugin name %s already loaded', f)
298
# trace.mutter('add plugin name %s', f)
175
# mutter('add plugin name %s', f)
299
176
plugin_names.add(f)
301
178
for name in plugin_names:
303
180
exec "import bzrlib.plugins.%s" % name in {}
304
181
except KeyboardInterrupt:
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
183
except Exception, e:
312
trace.warning("%s" % e)
313
184
## import pdb; pdb.set_trace()
314
185
if re.search('\.|-| ', name):
315
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))
186
warning('Unable to load plugin %r from %r: '
187
'It is not a valid python module name.' % (name, d))
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)
329
"""Return a dictionary of the plugins.
331
Each item in the dictionary is a PlugIn object.
334
for name, plugin in _mod_plugins.__dict__.items():
335
if isinstance(plugin, types.ModuleType):
336
result[name] = PlugIn(name, plugin)
189
warning('Unable to load plugin %r from %r' % (name, d))
190
log_exception_quietly()
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
197
if '.zip' not in zip_name:
200
ziobj = zipimport.zipimporter(zip_name)
201
except zipimport.ZipImportError:
204
mutter('Looking for plugins in %r', zip_name)
208
# use zipfile to get list of files/dirs inside zip
209
z = zipfile.ZipFile(ziobj.archive)
210
namelist = z.namelist()
214
prefix = ziobj.prefix.replace('\\','/')
216
namelist = [name[ix:]
218
if name.startswith(prefix)]
220
mutter('Names in archive: %r', namelist)
222
for name in namelist:
223
if not name or name.endswith('/'):
226
# '/' is used to separate pathname components inside zip archives
229
head, tail = '', name
231
head, tail = name.rsplit('/',1)
233
# we don't need looking in subdirectories
236
base, suffix = osutils.splitext(tail)
237
if suffix not in valid_suffixes:
240
if base == '__init__':
251
if getattr(plugins, plugin_name, None):
252
mutter('Plugin name %s already loaded', plugin_name)
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))
263
except KeyboardInterrupt:
266
## import pdb; pdb.set_trace()
267
warning('Unable to load plugin %r from %r'
269
log_exception_quietly()
340
272
class PluginsHelpIndex(object):
403
335
def get_help_topic(self):
404
336
"""Return the modules help topic - its __name__ after bzrlib.plugins.."""
405
337
return self.module.__name__[len('bzrlib.plugins.'):]
408
class PlugIn(object):
409
"""The bzrlib representation of a plugin.
411
The PlugIn object provides a way to manipulate a given plugin module.
414
def __init__(self, name, module):
415
"""Construct a plugin for module."""
420
"""Get the path that this plugin was loaded from."""
421
if getattr(self.module, '__path__', None) is not None:
422
return os.path.abspath(self.module.__path__[0])
423
elif getattr(self.module, '__file__', None) is not None:
424
path = os.path.abspath(self.module.__file__)
425
if path[-4:] in ('.pyc', '.pyo'):
426
pypath = path[:-4] + '.py'
427
if os.path.isfile(pypath):
431
return repr(self.module)
434
return "<%s.%s object at %s, name=%s, module=%s>" % (
435
self.__class__.__module__, self.__class__.__name__, id(self),
436
self.name, self.module)
440
def test_suite(self):
441
"""Return the plugin's test suite."""
442
if getattr(self.module, 'test_suite', None) is not None:
443
return self.module.test_suite()
447
def load_plugin_tests(self, loader):
448
"""Return the adapted plugin's test suite.
450
:param loader: The custom loader that should be used to load additional
454
if getattr(self.module, 'load_tests', None) is not None:
455
return loader.loadTestsFromModule(self.module)
459
def version_info(self):
460
"""Return the plugin's version_tuple or None if unknown."""
461
version_info = getattr(self.module, 'version_info', None)
462
if version_info is not None:
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)
469
# The given version_info isn't even iteratible
470
trace.log_exception_quietly()
471
version_info = (version_info,)
474
def _get__version__(self):
475
version_info = self.version_info()
476
if version_info is None or len(version_info) == 0:
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
484
version_string = '.'.join(map(str, version_info))
485
return version_string
487
__version__ = property(_get__version__)