/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
1
# Copyright (C) 2004, 2005, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
13
# You should have received a copy of the GNU General Public License
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
16
17
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
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.
1185.16.83 by mbp at sourcefrog
- notes on testability of plugins
30
"""
31
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
32
import os
1185.16.82 by mbp at sourcefrog
- give a quieter warning if a plugin can't be loaded
33
import sys
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
34
35
from bzrlib.lazy_import import lazy_import
36
lazy_import(globals(), """
37
import imp
2256.2.3 by Robert Collins
Review feedback.
38
import re
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
39
import types
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
40
import zipfile
1185.16.82 by mbp at sourcefrog
- give a quieter warning if a plugin can't be loaded
41
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
42
from bzrlib import (
43
    osutils,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
44
    trace,
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
45
    )
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
46
from bzrlib import plugins as _mod_plugins
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
47
""")
48
3193.7.11 by Alexander Belchenko
merge bzr.dev; update patch for 1.3
49
from bzrlib.symbol_versioning import deprecated_function, one_three
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
50
51
52
DEFAULT_PLUGIN_PATH = None
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
53
_loaded = False
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
54
3224.5.9 by Andrew Bennetts
More initial import hackery.
55
# XXX: copied and pasted from config.py to avoid importing configobj before
56
#      we've installed lazy_regex.
57
def _config_dir():
58
    """Return per-user configuration directory.
59
60
    By default this is ~/.bazaar/
61
    
62
    TODO: Global option --config-dir to override this.
63
    """
64
    base = os.environ.get('BZR_HOME', None)
65
    if sys.platform == 'win32':
66
        if base is None:
67
            base = win32utils.get_appdata_location_unicode()
68
        if base is None:
69
            base = os.environ.get('HOME', None)
70
        if base is None:
71
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
72
                                  ' or HOME set')
73
        return osutils.pathjoin(base, 'bazaar', '2.0')
74
    else:
75
        # cygwin, linux, and darwin all have a $HOME directory
76
        if base is None:
77
            base = os.path.expanduser("~")
78
        return osutils.pathjoin(base, ".bazaar")
79
80
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
81
def get_default_plugin_path():
82
    """Get the DEFAULT_PLUGIN_PATH"""
83
    global DEFAULT_PLUGIN_PATH
84
    if DEFAULT_PLUGIN_PATH is None:
3224.5.9 by Andrew Bennetts
More initial import hackery.
85
        DEFAULT_PLUGIN_PATH = osutils.pathjoin(_config_dir(), 'plugins')
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
86
    return DEFAULT_PLUGIN_PATH
87
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
88
1551.3.11 by Aaron Bentley
Merge from Robert
89
def disable_plugins():
90
    """Disable loading plugins.
91
92
    Future calls to load_plugins() will be ignored.
93
    """
94
    # TODO: jam 20060131 This should probably also disable
95
    #       load_from_dirs()
96
    global _loaded
97
    _loaded = True
98
3010.4.1 by Alexander Belchenko
bzr.exe: enable to search system-wide plugins in "plugins" subdirectory of installation directory
99
2753.1.1 by Ian Clatworthy
(Blake Winton) BZR_PLUGIN_PATH should ignore trailiing slashes
100
def _strip_trailing_sep(path):
2652.2.6 by Blake Winton
Incorporate suggestions from Alexander Belchenko
101
    return path.rstrip("\\/")
1551.3.11 by Aaron Bentley
Merge from Robert
102
3010.4.1 by Alexander Belchenko
bzr.exe: enable to search system-wide plugins in "plugins" subdirectory of installation directory
103
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
104
def set_plugins_path():
105
    """Set the path for plugins to be loaded from."""
106
    path = os.environ.get('BZR_PLUGIN_PATH',
2652.2.5 by Blake Winton
Get rid of CRs.
107
                          get_default_plugin_path()).split(os.pathsep)
3193.7.5 by Alexander Belchenko
deprecate bzrlib.plugins.load_from_zip feature; remove 0.91-deprecated function all_plugins()
108
    bzr_exe = bool(getattr(sys, 'frozen', None))
109
    if bzr_exe:    # expand path for bzr.exe
3193.7.1 by Alexander Belchenko
system-wide plugins for bzr.exe works even if BZR_PLUGIN_PATH env variable is set.
110
        # We need to use relative path to system-wide plugin
111
        # directory because bzrlib from standalone bzr.exe
112
        # could be imported by another standalone program
113
        # (e.g. bzr-config; or TortoiseBzr/Olive if/when they
114
        # will become standalone exe). [bialix 20071123]
115
        # __file__ typically is
116
        # C:\Program Files\Bazaar\lib\library.zip\bzrlib\plugin.pyc
117
        # then plugins directory is
118
        # C:\Program Files\Bazaar\plugins
119
        # so relative path is ../../../plugins
120
        path.append(osutils.abspath(osutils.pathjoin(
121
            osutils.dirname(__file__), '../../../plugins')))
2652.2.5 by Blake Winton
Get rid of CRs.
122
    # Get rid of trailing slashes, since Python can't handle them when
2652.2.4 by Blake Winton
Add a note explaining why I strip the slashes twice.
123
    # it tries to import modules.
2753.1.1 by Ian Clatworthy
(Blake Winton) BZR_PLUGIN_PATH should ignore trailiing slashes
124
    path = map(_strip_trailing_sep, path)
3193.7.5 by Alexander Belchenko
deprecate bzrlib.plugins.load_from_zip feature; remove 0.91-deprecated function all_plugins()
125
    if not bzr_exe:     # don't look inside library.zip
126
        # search the plugin path before the bzrlib installed dir
127
        path.append(os.path.dirname(_mod_plugins.__file__))
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
128
    _mod_plugins.__path__ = path
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
129
    return path
130
131
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
132
def load_plugins():
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
133
    """Load bzrlib plugins.
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
134
135
    The environment variable BZR_PLUGIN_PATH is considered a delimited
136
    set of paths to look through. Each entry is searched for *.py
137
    files (and whatever other extensions are used in the platform,
138
    such as *.pyd).
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
139
140
    load_from_dirs() provides the underlying mechanism and is called with
141
    the default directory list to provide the normal behaviour.
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
142
    """
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
143
    global _loaded
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
144
    if _loaded:
145
        # People can make sure plugins are loaded, they just won't be twice
146
        return
147
    _loaded = True
148
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
149
    # scan for all plugins in the path.
150
    load_from_path(set_plugins_path())
151
152
153
def load_from_path(dirs):
1515 by Robert Collins
* Plugins with the same name in different directories in the bzr plugin
154
    """Load bzrlib plugins found in each dir in dirs.
155
156
    Loading a plugin means importing it into the python interpreter.
157
    The plugin is expected to make calls to register commands when
158
    it's loaded (or perhaps access other hooks in future.)
159
160
    Plugins are loaded into bzrlib.plugins.NAME, and can be found there
161
    for future reference.
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
162
163
    The python module path for bzrlib.plugins will be modified to be 'dirs'.
2652.2.5 by Blake Winton
Get rid of CRs.
164
    """
165
    # We need to strip the trailing separators here as well as in the
166
    # set_plugins_path function because calling code can pass anything in to
167
    # this function, and since it sets plugins.__path__, it should set it to
168
    # something that will be valid for Python to use (in case people try to
2652.2.4 by Blake Winton
Add a note explaining why I strip the slashes twice.
169
    # run "import bzrlib.plugins.PLUGINNAME" after calling this function).
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
170
    _mod_plugins.__path__ = map(_strip_trailing_sep, dirs)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
171
    for d in dirs:
172
        if not d:
173
            continue
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
174
        trace.mutter('looking for plugins in %s', d)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
175
        if os.path.isdir(d):
176
            load_from_dir(d)
177
178
179
# backwards compatability: load_from_dirs was the old name
180
# This was changed in 0.15
181
load_from_dirs = load_from_path
182
183
184
def load_from_dir(d):
185
    """Load the plugins in directory d."""
1864.6.1 by John Arbash Meinel
Use the correct suffixes for loading plugins (bug #51810)
186
    # Get the list of valid python suffixes for __init__.py?
187
    # this includes .py, .pyc, and .pyo (depending on if we are running -O)
188
    # but it doesn't include compiled modules (.so, .dll, etc)
189
    valid_suffixes = [suffix for suffix, mod_type, flags in imp.get_suffixes()
190
                              if flags in (imp.PY_SOURCE, imp.PY_COMPILED)]
191
    package_entries = ['__init__'+suffix for suffix in valid_suffixes]
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
192
    plugin_names = set()
193
    for f in os.listdir(d):
194
        path = osutils.pathjoin(d, f)
195
        if os.path.isdir(path):
196
            for entry in package_entries:
197
                # This directory should be a package, and thus added to
198
                # the list
199
                if os.path.isfile(osutils.pathjoin(path, entry)):
200
                    break
201
            else: # This directory is not a package
202
                continue
203
        else:
204
            for suffix_info in imp.get_suffixes():
205
                if f.endswith(suffix_info[0]):
206
                    f = f[:-len(suffix_info[0])]
207
                    if suffix_info[2] == imp.C_EXTENSION and f.endswith('module'):
208
                        f = f[:-len('module')]
209
                    break
210
            else:
211
                continue
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
212
        if getattr(_mod_plugins, f, None):
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
213
            trace.mutter('Plugin name %s already loaded', f)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
214
        else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
215
            # trace.mutter('add plugin name %s', f)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
216
            plugin_names.add(f)
217
    
218
    for name in plugin_names:
219
        try:
2256.2.3 by Robert Collins
Review feedback.
220
            exec "import bzrlib.plugins.%s" % name in {}
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
221
        except KeyboardInterrupt:
222
            raise
223
        except Exception, e:
224
            ## import pdb; pdb.set_trace()
2256.2.3 by Robert Collins
Review feedback.
225
            if re.search('\.|-| ', name):
2967.4.7 by Daniel Watkins
Converted from nasty chained replaces to re.sub.
226
                sanitised_name = re.sub('[-. ]', '_', name)
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
227
                trace.warning("Unable to load %r in %r as a plugin because file path"
2967.4.10 by Daniel Watkins
Fixed message.
228
                        " isn't a valid module name; try renaming it to %r."
2967.4.6 by Daniel Watkins
Cleaned up dodgy indentation.
229
                        % (name, d, sanitised_name))
2256.2.3 by Robert Collins
Review feedback.
230
            else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
231
                trace.warning('Unable to load plugin %r from %r' % (name, d))
232
            trace.log_exception_quietly()
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
233
234
3193.7.11 by Alexander Belchenko
merge bzr.dev; update patch for 1.3
235
@deprecated_function(one_three)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
236
def load_from_zip(zip_name):
237
    """Load all the plugins in a zip."""
2215.4.1 by Alexander Belchenko
Bugfix #68124: Allow plugins import from zip archives.
238
    valid_suffixes = ('.py', '.pyc', '.pyo')    # only python modules/packages
239
                                                # is allowed
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
240
    try:
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
241
        index = zip_name.rindex('.zip')
242
    except ValueError:
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
243
        return
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
244
    archive = zip_name[:index+4]
245
    prefix = zip_name[index+5:]
246
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
247
    trace.mutter('Looking for plugins in %r', zip_name)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
248
249
    # use zipfile to get list of files/dirs inside zip
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
250
    try:
251
        z = zipfile.ZipFile(archive)
252
        namelist = z.namelist()
253
        z.close()
254
    except zipfile.error:
255
        # not a valid zip
256
        return
257
258
    if prefix:
259
        prefix = prefix.replace('\\','/')
260
        if prefix[-1] != '/':
261
            prefix += '/'
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
262
        ix = len(prefix)
263
        namelist = [name[ix:]
264
                    for name in namelist
265
                    if name.startswith(prefix)]
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
266
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
267
    trace.mutter('Names in archive: %r', namelist)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
268
    
269
    for name in namelist:
270
        if not name or name.endswith('/'):
271
            continue
272
    
273
        # '/' is used to separate pathname components inside zip archives
274
        ix = name.rfind('/')
275
        if ix == -1:
276
            head, tail = '', name
277
        else:
278
            head, tail = name.rsplit('/',1)
279
        if '/' in head:
280
            # we don't need looking in subdirectories
281
            continue
282
    
283
        base, suffix = osutils.splitext(tail)
284
        if suffix not in valid_suffixes:
285
            continue
286
    
287
        if base == '__init__':
288
            # package
289
            plugin_name = head
290
        elif head == '':
291
            # module
292
            plugin_name = base
293
        else:
294
            continue
295
    
296
        if not plugin_name:
297
            continue
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
298
        if getattr(_mod_plugins, plugin_name, None):
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
299
            trace.mutter('Plugin name %s already loaded', plugin_name)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
300
            continue
301
    
2215.4.1 by Alexander Belchenko
Bugfix #68124: Allow plugins import from zip archives.
302
        try:
2610.2.1 by Martin Pool
(Lukas Lalinsky) don't create a duplicate zipimporter, avoiding loading plugins twice
303
            exec "import bzrlib.plugins.%s" % plugin_name in {}
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
304
            trace.mutter('Load plugin %s from zip %r', plugin_name, zip_name)
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
305
        except KeyboardInterrupt:
306
            raise
307
        except Exception, e:
308
            ## import pdb; pdb.set_trace()
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
309
            trace.warning('Unable to load plugin %r from %r'
2256.2.2 by Robert Collins
Allow 'import bzrlib.plugins.NAME' to work when the plugin NAME has not
310
                    % (name, zip_name))
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
311
            trace.log_exception_quietly()
2432.1.24 by Robert Collins
Add plugins as a help index.
312
313
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
314
def plugins():
315
    """Return a dictionary of the plugins.
316
    
317
    Each item in the dictionary is a PlugIn object.
318
    """
319
    result = {}
320
    for name, plugin in _mod_plugins.__dict__.items():
321
        if isinstance(plugin, types.ModuleType):
322
            result[name] = PlugIn(name, plugin)
323
    return result
324
325
2432.1.24 by Robert Collins
Add plugins as a help index.
326
class PluginsHelpIndex(object):
327
    """A help index that returns help topics for plugins."""
328
329
    def __init__(self):
330
        self.prefix = 'plugins/'
331
332
    def get_topics(self, topic):
2432.1.25 by Robert Collins
Return plugin module docstrings for 'bzr help plugin'.
333
        """Search for topic in the loaded plugins.
334
335
        This will not trigger loading of new plugins.
336
337
        :param topic: A topic to search for.
338
        :return: A list which is either empty or contains a single
339
            RegisteredTopic entry.
340
        """
341
        if not topic:
342
            return []
343
        if topic.startswith(self.prefix):
344
            topic = topic[len(self.prefix):]
345
        plugin_module_name = 'bzrlib.plugins.%s' % topic
346
        try:
347
            module = sys.modules[plugin_module_name]
348
        except KeyError:
349
            return []
350
        else:
351
            return [ModuleHelpTopic(module)]
352
353
354
class ModuleHelpTopic(object):
355
    """A help topic which returns the docstring for a module."""
356
357
    def __init__(self, module):
358
        """Constructor.
359
360
        :param module: The module for which help should be generated.
361
        """
362
        self.module = module
363
364
    def get_help_text(self, additional_see_also=None):
365
        """Return a string with the help for this topic.
366
367
        :param additional_see_also: Additional help topics to be
368
            cross-referenced.
369
        """
370
        if not self.module.__doc__:
371
            result = "Plugin '%s' has no docstring.\n" % self.module.__name__
372
        else:
373
            result = self.module.__doc__
374
        if result[-1] != '\n':
375
            result += '\n'
376
        # there is code duplicated here and in bzrlib/help_topic.py's 
377
        # matching Topic code. This should probably be factored in
378
        # to a helper function and a common base class.
379
        if additional_see_also is not None:
380
            see_also = sorted(set(additional_see_also))
381
        else:
382
            see_also = None
383
        if see_also:
384
            result += 'See also: '
385
            result += ', '.join(see_also)
386
            result += '\n'
387
        return result
2432.1.29 by Robert Collins
Add get_help_topic to ModuleHelpTopic.
388
389
    def get_help_topic(self):
2432.1.30 by Robert Collins
Fix the ModuleHelpTopic get_help_topic to be tested with closer to real world data and strip the bzrlib.plugins. prefix from the name.
390
        """Return the modules help topic - its __name__ after bzrlib.plugins.."""
391
        return self.module.__name__[len('bzrlib.plugins.'):]
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
392
393
394
class PlugIn(object):
395
    """The bzrlib representation of a plugin.
396
397
    The PlugIn object provides a way to manipulate a given plugin module.
398
    """
399
400
    def __init__(self, name, module):
401
        """Construct a plugin for module."""
402
        self.name = name
403
        self.module = module
404
405
    def path(self):
406
        """Get the path that this plugin was loaded from."""
407
        if getattr(self.module, '__path__', None) is not None:
408
            return os.path.abspath(self.module.__path__[0])
409
        elif getattr(self.module, '__file__', None) is not None:
3193.2.1 by Alexander Belchenko
show path to plugin module as *.py instead of *.pyc if python source available
410
            path = os.path.abspath(self.module.__file__)
411
            if path[-4:] in ('.pyc', '.pyo'):
412
                pypath = path[:-4] + '.py'
413
                if os.path.isfile(pypath):
414
                    path = pypath
415
            return path
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
416
        else:
417
            return repr(self.module)
418
419
    def __str__(self):
420
        return "<%s.%s object at %s, name=%s, module=%s>" % (
421
            self.__class__.__module__, self.__class__.__name__, id(self),
422
            self.name, self.module)
423
424
    __repr__ = __str__
425
426
    def test_suite(self):
427
        """Return the plugin's test suite."""
428
        if getattr(self.module, 'test_suite', None) is not None:
429
            return self.module.test_suite()
430
        else:
431
            return None
432
433
    def version_info(self):
434
        """Return the plugin's version_tuple or None if unknown."""
435
        version_info = getattr(self.module, 'version_info', None)
436
        if version_info is not None and len(version_info) == 3:
437
            version_info = tuple(version_info) + ('final', 0)
438
        return version_info
439
    
440
    def _get__version__(self):
441
        version_info = self.version_info()
442
        if version_info is None:
443
            return "unknown"
444
        if version_info[3] == 'final':
445
            version_string = '%d.%d.%d' % version_info[:3]
446
        else:
447
            version_string = '%d.%d.%d%s%d' % version_info
448
        return version_string
449
450
    __version__ = property(_get__version__)