~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Florian Dorn
  • Date: 2012-04-03 14:49:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6546.
  • Revision ID: florian.dorn@boku.ac.at-20120403144922-b8y59csy8l1rzs5u
updated developer docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
16
 
 
17
 
 
18
 
# TODO: probably should say which arguments are candidates for glob
19
 
# expansion on windows and do that at the command level.
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
20
17
 
21
18
# TODO: Define arguments by objects, rather than just using names.
22
19
# Those objects can specify the expected type of the argument, which
25
22
 
26
23
# TODO: Specific "examples" property on commands for consistent formatting.
27
24
 
28
 
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
 
# the profile output behind so it can be interactively examined?
30
 
 
31
25
import os
32
26
import sys
33
27
 
34
28
from bzrlib.lazy_import import lazy_import
35
29
lazy_import(globals(), """
36
 
import codecs
37
30
import errno
38
 
from warnings import warn
 
31
import threading
39
32
 
40
33
import bzrlib
41
34
from bzrlib import (
 
35
    cleanup,
 
36
    cmdline,
42
37
    debug,
43
38
    errors,
44
39
    option,
45
40
    osutils,
46
 
    registry,
47
41
    trace,
48
 
    win32utils,
 
42
    ui,
49
43
    )
50
44
""")
51
45
 
 
46
from bzrlib.hooks import Hooks
 
47
# Compatibility - Option used to be in commands.
 
48
from bzrlib.option import Option
 
49
from bzrlib.plugin import disable_plugins, load_plugins
 
50
from bzrlib import registry
52
51
from bzrlib.symbol_versioning import (
53
52
    deprecated_function,
 
53
    deprecated_in,
54
54
    deprecated_method,
55
55
    )
56
 
# Compatibility
57
 
from bzrlib.option import Option
58
 
 
59
 
 
60
 
plugin_cmds = {}
 
56
 
 
57
 
 
58
class CommandInfo(object):
 
59
    """Information about a command."""
 
60
 
 
61
    def __init__(self, aliases):
 
62
        """The list of aliases for the command."""
 
63
        self.aliases = aliases
 
64
 
 
65
    @classmethod
 
66
    def from_command(klass, command):
 
67
        """Factory to construct a CommandInfo from a command."""
 
68
        return klass(command.aliases)
 
69
 
 
70
 
 
71
class CommandRegistry(registry.Registry):
 
72
    """Special registry mapping command names to command classes.
 
73
    
 
74
    :ivar overridden_registry: Look in this registry for commands being
 
75
        overridden by this registry.  This can be used to tell plugin commands
 
76
        about the builtin they're decorating.
 
77
    """
 
78
 
 
79
    def __init__(self):
 
80
        registry.Registry.__init__(self)
 
81
        self.overridden_registry = None
 
82
        # map from aliases to the real command that implements the name
 
83
        self._alias_dict = {}
 
84
 
 
85
    def get(self, command_name):
 
86
        real_name = self._alias_dict.get(command_name, command_name)
 
87
        return registry.Registry.get(self, real_name)
 
88
 
 
89
    @staticmethod
 
90
    def _get_name(command_name):
 
91
        if command_name.startswith("cmd_"):
 
92
            return _unsquish_command_name(command_name)
 
93
        else:
 
94
            return command_name
 
95
 
 
96
    def register(self, cmd, decorate=False):
 
97
        """Utility function to help register a command
 
98
 
 
99
        :param cmd: Command subclass to register
 
100
        :param decorate: If true, allow overriding an existing command
 
101
            of the same name; the old command is returned by this function.
 
102
            Otherwise it is an error to try to override an existing command.
 
103
        """
 
104
        k = cmd.__name__
 
105
        k_unsquished = self._get_name(k)
 
106
        try:
 
107
            previous = self.get(k_unsquished)
 
108
        except KeyError:
 
109
            previous = None
 
110
            if self.overridden_registry:
 
111
                try:
 
112
                    previous = self.overridden_registry.get(k_unsquished)
 
113
                except KeyError:
 
114
                    pass
 
115
        info = CommandInfo.from_command(cmd)
 
116
        try:
 
117
            registry.Registry.register(self, k_unsquished, cmd,
 
118
                                       override_existing=decorate, info=info)
 
119
        except KeyError:
 
120
            trace.warning('Two plugins defined the same command: %r' % k)
 
121
            trace.warning('Not loading the one in %r' %
 
122
                sys.modules[cmd.__module__])
 
123
            trace.warning('Previously this command was registered from %r' %
 
124
                sys.modules[previous.__module__])
 
125
        for a in cmd.aliases:
 
126
            self._alias_dict[a] = k_unsquished
 
127
        return previous
 
128
 
 
129
    def register_lazy(self, command_name, aliases, module_name):
 
130
        """Register a command without loading its module.
 
131
 
 
132
        :param command_name: The primary name of the command.
 
133
        :param aliases: A list of aliases for the command.
 
134
        :module_name: The module that the command lives in.
 
135
        """
 
136
        key = self._get_name(command_name)
 
137
        registry.Registry.register_lazy(self, key, module_name, command_name,
 
138
                                        info=CommandInfo(aliases))
 
139
        for a in aliases:
 
140
            self._alias_dict[a] = key
 
141
 
 
142
 
 
143
plugin_cmds = CommandRegistry()
 
144
builtin_command_registry = CommandRegistry()
 
145
plugin_cmds.overridden_registry = builtin_command_registry
61
146
 
62
147
 
63
148
def register_command(cmd, decorate=False):
64
 
    """Utility function to help register a command
 
149
    """Register a plugin command.
65
150
 
66
 
    :param cmd: Command subclass to register
67
 
    :param decorate: If true, allow overriding an existing command
68
 
        of the same name; the old command is returned by this function.
69
 
        Otherwise it is an error to try to override an existing command.
 
151
    Should generally be avoided in favor of lazy registration. 
70
152
    """
71
153
    global plugin_cmds
72
 
    k = cmd.__name__
73
 
    if k.startswith("cmd_"):
74
 
        k_unsquished = _unsquish_command_name(k)
75
 
    else:
76
 
        k_unsquished = k
77
 
    if k_unsquished not in plugin_cmds:
78
 
        plugin_cmds[k_unsquished] = cmd
79
 
        ## trace.mutter('registered plugin command %s', k_unsquished)
80
 
        if decorate and k_unsquished in builtin_command_names():
81
 
            return _builtin_commands()[k_unsquished]
82
 
    elif decorate:
83
 
        result = plugin_cmds[k_unsquished]
84
 
        plugin_cmds[k_unsquished] = cmd
85
 
        return result
86
 
    else:
87
 
        trace.log_error('Two plugins defined the same command: %r' % k)
88
 
        trace.log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
89
 
        trace.log_error('Previously this command was registered from %r' %
90
 
                        sys.modules[plugin_cmds[k_unsquished].__module__])
 
154
    return plugin_cmds.register(cmd, decorate)
91
155
 
92
156
 
93
157
def _squish_command_name(cmd):
98
162
    return cmd[4:].replace('_','-')
99
163
 
100
164
 
 
165
@deprecated_function(deprecated_in((2, 2, 0)))
101
166
def _builtin_commands():
 
167
    """Return a dict of {name: cmd_class} for builtin commands.
 
168
 
 
169
    :deprecated: Use the builtin_command_registry registry instead
 
170
    """
 
171
    # return dict(name: cmd_class)
 
172
    return dict(builtin_command_registry.items())
 
173
 
 
174
 
 
175
def _register_builtin_commands():
 
176
    if builtin_command_registry.keys():
 
177
        # only load once
 
178
        return
102
179
    import bzrlib.builtins
 
180
    for cmd_class in _scan_module_for_commands(bzrlib.builtins).values():
 
181
        builtin_command_registry.register(cmd_class)
 
182
    bzrlib.builtins._register_lazy_builtins()
 
183
 
 
184
 
 
185
def _scan_module_for_commands(module):
103
186
    r = {}
104
 
    builtins = bzrlib.builtins.__dict__
105
 
    for name in builtins:
 
187
    for name, obj in module.__dict__.iteritems():
106
188
        if name.startswith("cmd_"):
107
189
            real_name = _unsquish_command_name(name)
108
 
            r[real_name] = builtins[name]
 
190
            r[real_name] = obj
109
191
    return r
110
 
            
 
192
 
 
193
 
 
194
def _list_bzr_commands(names):
 
195
    """Find commands from bzr's core and plugins.
 
196
    
 
197
    This is not the public interface, just the default hook called by all_command_names.
 
198
    """
 
199
    # to eliminate duplicates
 
200
    names.update(builtin_command_names())
 
201
    names.update(plugin_command_names())
 
202
    return names
 
203
 
 
204
 
 
205
def all_command_names():
 
206
    """Return a set of all command names."""
 
207
    names = set()
 
208
    for hook in Command.hooks['list_commands']:
 
209
        names = hook(names)
 
210
        if names is None:
 
211
            raise AssertionError(
 
212
                'hook %s returned None' % Command.hooks.get_hook_name(hook))
 
213
    return names
 
214
 
111
215
 
112
216
def builtin_command_names():
113
 
    """Return list of builtin command names."""
114
 
    return _builtin_commands().keys()
 
217
    """Return list of builtin command names.
115
218
    
 
219
    Use of all_command_names() is encouraged rather than builtin_command_names
 
220
    and/or plugin_command_names.
 
221
    """
 
222
    _register_builtin_commands()
 
223
    return builtin_command_registry.keys()
 
224
 
116
225
 
117
226
def plugin_command_names():
 
227
    """Returns command names from commands registered by plugins."""
118
228
    return plugin_cmds.keys()
119
229
 
120
230
 
121
 
def _get_cmd_dict(plugins_override=True):
122
 
    """Return name->class mapping for all commands."""
123
 
    d = _builtin_commands()
124
 
    if plugins_override:
125
 
        d.update(plugin_cmds)
126
 
    return d
127
 
 
128
 
    
129
 
def get_all_cmds(plugins_override=True):
130
 
    """Return canonical name and class for all registered commands."""
131
 
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
132
 
        yield k,v
133
 
 
134
 
 
135
231
def get_cmd_object(cmd_name, plugins_override=True):
136
 
    """Return the canonical name and command class for a command.
 
232
    """Return the command object for a command.
137
233
 
138
234
    plugins_override
139
235
        If true, plugin commands can override builtins.
144
240
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
145
241
 
146
242
 
147
 
def _get_cmd_object(cmd_name, plugins_override=True):
148
 
    """Worker for get_cmd_object which raises KeyError rather than BzrCommandError."""
 
243
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
 
244
    """Get a command object.
 
245
 
 
246
    :param cmd_name: The name of the command.
 
247
    :param plugins_override: Allow plugins to override builtins.
 
248
    :param check_missing: Look up commands not found in the regular index via
 
249
        the get_missing_command hook.
 
250
    :return: A Command object instance
 
251
    :raises KeyError: If no command is found.
 
252
    """
 
253
    # We want only 'ascii' command names, but the user may have typed
 
254
    # in a Unicode name. In that case, they should just get a
 
255
    # 'command not found' error later.
 
256
    # In the future, we may actually support Unicode command names.
 
257
    cmd = None
 
258
    # Get a command
 
259
    for hook in Command.hooks['get_command']:
 
260
        cmd = hook(cmd, cmd_name)
 
261
        if cmd is not None and not plugins_override and not cmd.plugin_name():
 
262
            # We've found a non-plugin command, don't permit it to be
 
263
            # overridden.
 
264
            break
 
265
    if cmd is None and check_missing:
 
266
        for hook in Command.hooks['get_missing_command']:
 
267
            cmd = hook(cmd_name)
 
268
            if cmd is not None:
 
269
                break
 
270
    if cmd is None:
 
271
        # No command found.
 
272
        raise KeyError
 
273
    # Allow plugins to extend commands
 
274
    for hook in Command.hooks['extend_command']:
 
275
        hook(cmd)
 
276
    if getattr(cmd, 'invoked_as', None) is None:
 
277
        cmd.invoked_as = cmd_name
 
278
    return cmd
 
279
 
 
280
 
 
281
def _try_plugin_provider(cmd_name):
 
282
    """Probe for a plugin provider having cmd_name."""
 
283
    try:
 
284
        plugin_metadata, provider = probe_for_provider(cmd_name)
 
285
        raise errors.CommandAvailableInPlugin(cmd_name,
 
286
            plugin_metadata, provider)
 
287
    except errors.NoPluginAvailable:
 
288
        pass
 
289
 
 
290
 
 
291
def probe_for_provider(cmd_name):
 
292
    """Look for a provider for cmd_name.
 
293
 
 
294
    :param cmd_name: The command name.
 
295
    :return: plugin_metadata, provider for getting cmd_name.
 
296
    :raises NoPluginAvailable: When no provider can supply the plugin.
 
297
    """
 
298
    # look for providers that provide this command but aren't installed
 
299
    for provider in command_providers_registry:
 
300
        try:
 
301
            return provider.plugin_for_command(cmd_name), provider
 
302
        except errors.NoPluginAvailable:
 
303
            pass
 
304
    raise errors.NoPluginAvailable(cmd_name)
 
305
 
 
306
 
 
307
def _get_bzr_command(cmd_or_None, cmd_name):
 
308
    """Get a command from bzr's core."""
 
309
    try:
 
310
        cmd_class = builtin_command_registry.get(cmd_name)
 
311
    except KeyError:
 
312
        pass
 
313
    else:
 
314
        return cmd_class()
 
315
    return cmd_or_None
 
316
 
 
317
 
 
318
def _get_external_command(cmd_or_None, cmd_name):
 
319
    """Lookup a command that is a shell script."""
 
320
    # Only do external command lookups when no command is found so far.
 
321
    if cmd_or_None is not None:
 
322
        return cmd_or_None
149
323
    from bzrlib.externalcommand import ExternalCommand
150
 
 
151
 
    # We want only 'ascii' command names, but the user may have typed
152
 
    # in a Unicode name. In that case, they should just get a
153
 
    # 'command not found' error later.
154
 
    # In the future, we may actually support Unicode command names.
155
 
 
156
 
    # first look up this command under the specified name
157
 
    cmds = _get_cmd_dict(plugins_override=plugins_override)
158
 
    try:
159
 
        return cmds[cmd_name]()
160
 
    except KeyError:
161
 
        pass
162
 
 
163
 
    # look for any command which claims this as an alias
164
 
    for real_cmd_name, cmd_class in cmds.iteritems():
165
 
        if cmd_name in cmd_class.aliases:
166
 
            return cmd_class()
167
 
 
168
324
    cmd_obj = ExternalCommand.find_command(cmd_name)
169
325
    if cmd_obj:
170
326
        return cmd_obj
171
327
 
172
 
    # look for plugins that provide this command but aren't installed
173
 
    for provider in command_providers_registry:
174
 
        try:
175
 
            plugin_metadata = provider.plugin_for_command(cmd_name)
176
 
        except errors.NoPluginAvailable:
177
 
            pass
178
 
        else:
179
 
            raise errors.CommandAvailableInPlugin(cmd_name, 
180
 
                                                  plugin_metadata, provider)
181
328
 
182
 
    raise KeyError
 
329
def _get_plugin_command(cmd_or_None, cmd_name):
 
330
    """Get a command from bzr's plugins."""
 
331
    try:
 
332
        return plugin_cmds.get(cmd_name)()
 
333
    except KeyError:
 
334
        pass
 
335
    for key in plugin_cmds.keys():
 
336
        info = plugin_cmds.get_info(key)
 
337
        if cmd_name in info.aliases:
 
338
            return plugin_cmds.get(key)()
 
339
    return cmd_or_None
183
340
 
184
341
 
185
342
class Command(object):
200
357
    summary, then a complete description of the command.  A grammar
201
358
    description will be inserted.
202
359
 
203
 
    aliases
204
 
        Other accepted names for this command.
205
 
 
206
 
    takes_args
207
 
        List of argument forms, marked with whether they are optional,
208
 
        repeated, etc.
209
 
 
210
 
                Examples:
211
 
 
212
 
                ['to_location', 'from_branch?', 'file*']
213
 
 
214
 
                'to_location' is required
215
 
                'from_branch' is optional
216
 
                'file' can be specified 0 or more times
217
 
 
218
 
    takes_options
219
 
        List of options that may be given for this command.  These can
220
 
        be either strings, referring to globally-defined options,
221
 
        or option objects.  Retrieve through options().
222
 
 
223
 
    hidden
224
 
        If true, this command isn't advertised.  This is typically
 
360
    :cvar aliases: Other accepted names for this command.
 
361
 
 
362
    :cvar takes_args: List of argument forms, marked with whether they are
 
363
        optional, repeated, etc.  Examples::
 
364
 
 
365
            ['to_location', 'from_branch?', 'file*']
 
366
 
 
367
        * 'to_location' is required
 
368
        * 'from_branch' is optional
 
369
        * 'file' can be specified 0 or more times
 
370
 
 
371
    :cvar takes_options: List of options that may be given for this command.
 
372
        These can be either strings, referring to globally-defined options, or
 
373
        option objects.  Retrieve through options().
 
374
 
 
375
    :cvar hidden: If true, this command isn't advertised.  This is typically
225
376
        for commands intended for expert users.
226
377
 
227
 
    encoding_type
228
 
        Command objects will get a 'outf' attribute, which has been
229
 
        setup to properly handle encoding of unicode strings.
230
 
        encoding_type determines what will happen when characters cannot
231
 
        be encoded
232
 
            strict - abort if we cannot decode
233
 
            replace - put in a bogus character (typically '?')
234
 
            exact - do not encode sys.stdout
235
 
 
236
 
            NOTE: by default on Windows, sys.stdout is opened as a text
237
 
            stream, therefore LF line-endings are converted to CRLF.
238
 
            When a command uses encoding_type = 'exact', then
239
 
            sys.stdout is forced to be a binary stream, and line-endings
240
 
            will not mangled.
241
 
 
 
378
    :cvar encoding_type: Command objects will get a 'outf' attribute, which has
 
379
        been setup to properly handle encoding of unicode strings.
 
380
        encoding_type determines what will happen when characters cannot be
 
381
        encoded:
 
382
 
 
383
        * strict - abort if we cannot decode
 
384
        * replace - put in a bogus character (typically '?')
 
385
        * exact - do not encode sys.stdout
 
386
 
 
387
        NOTE: by default on Windows, sys.stdout is opened as a text stream,
 
388
        therefore LF line-endings are converted to CRLF.  When a command uses
 
389
        encoding_type = 'exact', then sys.stdout is forced to be a binary
 
390
        stream, and line-endings will not mangled.
 
391
 
 
392
    :cvar invoked_as:
 
393
        A string indicating the real name under which this command was
 
394
        invoked, before expansion of aliases.
 
395
        (This may be None if the command was constructed and run in-process.)
 
396
 
 
397
    :cvar hooks: An instance of CommandHooks.
 
398
 
 
399
    :cvar __doc__: The help shown by 'bzr help command' for this command.
 
400
        This is set by assigning explicitly to __doc__ so that -OO can
 
401
        be used::
 
402
 
 
403
            class Foo(Command):
 
404
                __doc__ = "My help goes here"
242
405
    """
243
406
    aliases = []
244
407
    takes_args = []
245
408
    takes_options = []
246
409
    encoding_type = 'strict'
 
410
    invoked_as = None
247
411
 
248
412
    hidden = False
249
 
    
 
413
 
250
414
    def __init__(self):
251
415
        """Construct an instance of this command."""
252
 
        if self.__doc__ == Command.__doc__:
253
 
            warn("No help message set for %r" % self)
254
416
        # List of standard options directly supported
255
417
        self.supported_std_options = []
256
 
 
 
418
        self._setup_run()
 
419
 
 
420
    def add_cleanup(self, cleanup_func, *args, **kwargs):
 
421
        """Register a function to call after self.run returns or raises.
 
422
 
 
423
        Functions will be called in LIFO order.
 
424
        """
 
425
        self._operation.add_cleanup(cleanup_func, *args, **kwargs)
 
426
 
 
427
    def cleanup_now(self):
 
428
        """Execute and empty pending cleanup functions immediately.
 
429
 
 
430
        After cleanup_now all registered cleanups are forgotten.  add_cleanup
 
431
        may be called again after cleanup_now; these cleanups will be called
 
432
        after self.run returns or raises (or when cleanup_now is next called).
 
433
 
 
434
        This is useful for releasing expensive or contentious resources (such
 
435
        as write locks) before doing further work that does not require those
 
436
        resources (such as writing results to self.outf). Note though, that
 
437
        as it releases all resources, this may release locks that the command
 
438
        wants to hold, so use should be done with care.
 
439
        """
 
440
        self._operation.cleanup_now()
 
441
 
 
442
    @deprecated_method(deprecated_in((2, 1, 0)))
257
443
    def _maybe_expand_globs(self, file_list):
258
444
        """Glob expand file_list if the platform does not do that itself.
259
 
        
 
445
 
 
446
        Not used anymore, now that the bzr command-line parser globs on
 
447
        Windows.
 
448
 
260
449
        :return: A possibly empty list of unicode paths.
261
450
 
262
451
        Introduced in bzrlib 0.18.
263
452
        """
264
 
        if not file_list:
265
 
            file_list = []
266
 
        if sys.platform == 'win32':
267
 
            file_list = win32utils.glob_expand(file_list)
268
 
        return list(file_list)
 
453
        return file_list
269
454
 
270
455
    def _usage(self):
271
456
        """Return single-line grammar for this command.
286
471
        return s
287
472
 
288
473
    def get_help_text(self, additional_see_also=None, plain=True,
289
 
                      see_also_as_links=False):
 
474
                      see_also_as_links=False, verbose=True):
290
475
        """Return a text string with help for this command.
291
 
        
 
476
 
292
477
        :param additional_see_also: Additional help topics to be
293
478
            cross-referenced.
294
479
        :param plain: if False, raw help (reStructuredText) is
295
480
            returned instead of plain text.
296
481
        :param see_also_as_links: if True, convert items in 'See also'
297
482
            list to internal links (used by bzr_man rstx generator)
 
483
        :param verbose: if True, display the full help, otherwise
 
484
            leave out the descriptive sections and just display
 
485
            usage help (e.g. Purpose, Usage, Options) with a
 
486
            message explaining how to obtain full help.
298
487
        """
299
488
        doc = self.help()
300
 
        if doc is None:
301
 
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
 
489
        if not doc:
 
490
            doc = "No help for this command."
302
491
 
303
492
        # Extract the summary (purpose) and sections out from the text
304
 
        purpose,sections = self._get_help_parts(doc)
 
493
        purpose,sections,order = self._get_help_parts(doc)
305
494
 
306
495
        # If a custom usage section was provided, use it
307
496
        if sections.has_key('Usage'):
319
508
        result += '\n'
320
509
 
321
510
        # Add the options
 
511
        #
 
512
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
 
513
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
 
514
        # 20090319
322
515
        options = option.get_optparser(self.options()).format_option_help()
 
516
        # FIXME: According to the spec, ReST option lists actually don't
 
517
        # support options like --1.14 so that causes syntax errors (in Sphinx
 
518
        # at least).  As that pattern always appears in the commands that
 
519
        # break, we trap on that and then format that block of 'format' options
 
520
        # as a literal block. We use the most recent format still listed so we
 
521
        # don't have to do that too often -- vila 20110514
 
522
        if not plain and options.find('  --1.14  ') != -1:
 
523
            options = options.replace(' format:\n', ' format::\n\n', 1)
323
524
        if options.startswith('Options:'):
324
525
            result += ':' + options
325
526
        elif options.startswith('options:'):
329
530
            result += options
330
531
        result += '\n'
331
532
 
332
 
        # Add the description, indenting it 2 spaces
333
 
        # to match the indentation of the options
334
 
        if sections.has_key(None):
335
 
            text = sections.pop(None)
336
 
            text = '\n  '.join(text.splitlines())
337
 
            result += ':%s:\n  %s\n\n' % ('Description',text)
 
533
        if verbose:
 
534
            # Add the description, indenting it 2 spaces
 
535
            # to match the indentation of the options
 
536
            if sections.has_key(None):
 
537
                text = sections.pop(None)
 
538
                text = '\n  '.join(text.splitlines())
 
539
                result += ':%s:\n  %s\n\n' % ('Description',text)
338
540
 
339
 
        # Add the custom sections (e.g. Examples). Note that there's no need
340
 
        # to indent these as they must be indented already in the source.
341
 
        if sections:
342
 
            labels = sorted(sections.keys())
343
 
            for label in labels:
344
 
                result += ':%s:\n%s\n\n' % (label,sections[label])
 
541
            # Add the custom sections (e.g. Examples). Note that there's no need
 
542
            # to indent these as they must be indented already in the source.
 
543
            if sections:
 
544
                for label in order:
 
545
                    if sections.has_key(label):
 
546
                        result += ':%s:\n%s\n' % (label,sections[label])
 
547
                result += '\n'
 
548
        else:
 
549
            result += ("See bzr help %s for more details and examples.\n\n"
 
550
                % self.name())
345
551
 
346
552
        # Add the aliases, source (plug-in) and see also links, if any
347
553
        if self.aliases:
360
566
                        # so don't create a real link
361
567
                        see_also_links.append(item)
362
568
                    else:
363
 
                        # Use a reST link for this entry
364
 
                        see_also_links.append("`%s`_" % (item,))
 
569
                        # Use a Sphinx link for this entry
 
570
                        link_text = ":doc:`%s <%s-help>`" % (item, item)
 
571
                        see_also_links.append(link_text)
365
572
                see_also = see_also_links
366
573
            result += ':See also: '
367
574
            result += ', '.join(see_also) + '\n'
376
583
    def _get_help_parts(text):
377
584
        """Split help text into a summary and named sections.
378
585
 
379
 
        :return: (summary,sections) where summary is the top line and
 
586
        :return: (summary,sections,order) where summary is the top line and
380
587
            sections is a dictionary of the rest indexed by section name.
 
588
            order is the order the section appear in the text.
381
589
            A section starts with a heading line of the form ":xxx:".
382
590
            Indented text on following lines is the section value.
383
591
            All text found outside a named section is assigned to the
384
592
            default section which is given the key of None.
385
593
        """
386
 
        def save_section(sections, label, section):
 
594
        def save_section(sections, order, label, section):
387
595
            if len(section) > 0:
388
596
                if sections.has_key(label):
389
597
                    sections[label] += '\n' + section
390
598
                else:
 
599
                    order.append(label)
391
600
                    sections[label] = section
392
601
 
393
602
        lines = text.rstrip().splitlines()
394
603
        summary = lines.pop(0)
395
604
        sections = {}
 
605
        order = []
396
606
        label,section = None,''
397
607
        for line in lines:
398
608
            if line.startswith(':') and line.endswith(':') and len(line) > 2:
399
 
                save_section(sections, label, section)
 
609
                save_section(sections, order, label, section)
400
610
                label,section = line[1:-1],''
401
611
            elif (label is not None) and len(line) > 1 and not line[0].isspace():
402
 
                save_section(sections, label, section)
 
612
                save_section(sections, order, label, section)
403
613
                label,section = None,line
404
614
            else:
405
615
                if len(section) > 0:
406
616
                    section += '\n' + line
407
617
                else:
408
618
                    section = line
409
 
        save_section(sections, label, section)
410
 
        return summary, sections
 
619
        save_section(sections, order, label, section)
 
620
        return summary, sections, order
411
621
 
412
622
    def get_help_topic(self):
413
623
        """Return the commands help topic - its name."""
415
625
 
416
626
    def get_see_also(self, additional_terms=None):
417
627
        """Return a list of help topics that are related to this command.
418
 
        
 
628
 
419
629
        The list is derived from the content of the _see_also attribute. Any
420
630
        duplicates are removed and the result is in lexical order.
421
631
        :param additional_terms: Additional help topics to cross-reference.
442
652
 
443
653
    def _setup_outf(self):
444
654
        """Return a file linked to stdout, which has proper encoding."""
445
 
        # Originally I was using self.stdout, but that looks
446
 
        # *way* too much like sys.stdout
447
 
        if self.encoding_type == 'exact':
448
 
            # force sys.stdout to be binary stream on win32
449
 
            if sys.platform == 'win32':
450
 
                fileno = getattr(sys.stdout, 'fileno', None)
451
 
                if fileno:
452
 
                    import msvcrt
453
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
454
 
            self.outf = sys.stdout
455
 
            return
456
 
 
457
 
        output_encoding = osutils.get_terminal_encoding()
458
 
 
459
 
        self.outf = codecs.getwriter(output_encoding)(sys.stdout,
460
 
                        errors=self.encoding_type)
461
 
        # For whatever reason codecs.getwriter() does not advertise its encoding
462
 
        # it just returns the encoding of the wrapped file, which is completely
463
 
        # bogus. So set the attribute, so we can find the correct encoding later.
464
 
        self.outf.encoding = output_encoding
 
655
        self.outf = ui.ui_factory.make_output_stream(
 
656
            encoding_type=self.encoding_type)
465
657
 
466
658
    def run_argv_aliases(self, argv, alias_argv=None):
467
659
        """Parse the command line and run with extra aliases in alias_argv."""
468
 
        if argv is None:
469
 
            warn("Passing None for [] is deprecated from bzrlib 0.10",
470
 
                 DeprecationWarning, stacklevel=2)
471
 
            argv = []
472
660
        args, opts = parse_args(self, argv, alias_argv)
473
661
 
474
662
        # Process the standard options
475
663
        if 'help' in opts:  # e.g. bzr add --help
476
664
            sys.stdout.write(self.get_help_text())
477
665
            return 0
 
666
        if 'usage' in opts:  # e.g. bzr add --usage
 
667
            sys.stdout.write(self.get_help_text(verbose=False))
 
668
            return 0
478
669
        trace.set_verbosity_level(option._verbosity_level)
479
670
        if 'verbose' in self.supported_std_options:
480
671
            opts['verbose'] = trace.is_verbose()
496
687
 
497
688
        self._setup_outf()
498
689
 
499
 
        return self.run(**all_cmd_args)
 
690
        try:
 
691
            return self.run(**all_cmd_args)
 
692
        finally:
 
693
            # reset it, so that other commands run in the same process won't
 
694
            # inherit state. Before we reset it, log any activity, so that it
 
695
            # gets properly tracked.
 
696
            ui.ui_factory.log_transport_activity(
 
697
                display=('bytes' in debug.debug_flags))
 
698
            trace.set_verbosity_level(0)
 
699
 
 
700
    def _setup_run(self):
 
701
        """Wrap the defined run method on self with a cleanup.
 
702
 
 
703
        This is called by __init__ to make the Command be able to be run
 
704
        by just calling run(), as it could be before cleanups were added.
 
705
 
 
706
        If a different form of cleanups are in use by your Command subclass,
 
707
        you can override this method.
 
708
        """
 
709
        class_run = self.run
 
710
        def run(*args, **kwargs):
 
711
            self._operation = cleanup.OperationWithCleanups(class_run)
 
712
            try:
 
713
                return self._operation.run_simple(*args, **kwargs)
 
714
            finally:
 
715
                del self._operation
 
716
        self.run = run
 
717
 
 
718
    @deprecated_method(deprecated_in((2, 2, 0)))
 
719
    def run_direct(self, *args, **kwargs):
 
720
        """Deprecated thunk from bzrlib 2.1."""
 
721
        return self.run(*args, **kwargs)
500
722
 
501
723
    def run(self):
502
724
        """Actually run the command.
507
729
        Return 0 or None if the command was successful, or a non-zero
508
730
        shell error code if not.  It's OK for this method to allow
509
731
        an exception to raise up.
 
732
 
 
733
        This method is automatically wrapped by Command.__init__ with a 
 
734
        cleanup operation, stored as self._operation. This can be used
 
735
        via self.add_cleanup to perform automatic cleanups at the end of
 
736
        run().
 
737
 
 
738
        The argument for run are assembled by introspection. So for instance,
 
739
        if your command takes an argument files, you would declare::
 
740
 
 
741
            def run(self, files=None):
 
742
                pass
510
743
        """
511
744
        raise NotImplementedError('no implementation of command %r'
512
745
                                  % self.name())
519
752
        return getdoc(self)
520
753
 
521
754
    def name(self):
 
755
        """Return the canonical name for this command.
 
756
 
 
757
        The name under which it was actually invoked is available in invoked_as.
 
758
        """
522
759
        return _unsquish_command_name(self.__class__.__name__)
523
760
 
524
761
    def plugin_name(self):
533
770
            return None
534
771
 
535
772
 
 
773
class CommandHooks(Hooks):
 
774
    """Hooks related to Command object creation/enumeration."""
 
775
 
 
776
    def __init__(self):
 
777
        """Create the default hooks.
 
778
 
 
779
        These are all empty initially, because by default nothing should get
 
780
        notified.
 
781
        """
 
782
        Hooks.__init__(self, "bzrlib.commands", "Command.hooks")
 
783
        self.add_hook('extend_command',
 
784
            "Called after creating a command object to allow modifications "
 
785
            "such as adding or removing options, docs etc. Called with the "
 
786
            "new bzrlib.commands.Command object.", (1, 13))
 
787
        self.add_hook('get_command',
 
788
            "Called when creating a single command. Called with "
 
789
            "(cmd_or_None, command_name). get_command should either return "
 
790
            "the cmd_or_None parameter, or a replacement Command object that "
 
791
            "should be used for the command. Note that the Command.hooks "
 
792
            "hooks are core infrastructure. Many users will prefer to use "
 
793
            "bzrlib.commands.register_command or plugin_cmds.register_lazy.",
 
794
            (1, 17))
 
795
        self.add_hook('get_missing_command',
 
796
            "Called when creating a single command if no command could be "
 
797
            "found. Called with (command_name). get_missing_command should "
 
798
            "either return None, or a Command object to be used for the "
 
799
            "command.", (1, 17))
 
800
        self.add_hook('list_commands',
 
801
            "Called when enumerating commands. Called with a set of "
 
802
            "cmd_name strings for all the commands found so far. This set "
 
803
            " is safe to mutate - e.g. to remove a command. "
 
804
            "list_commands should return the updated set of command names.",
 
805
            (1, 17))
 
806
 
 
807
Command.hooks = CommandHooks()
 
808
 
 
809
 
536
810
def parse_args(command, argv, alias_argv=None):
537
811
    """Parse command line.
538
 
    
 
812
 
539
813
    Arguments and options are parsed at this level before being passed
540
814
    down to specific command handlers.  This routine knows, from a
541
815
    lookup table, something about the available options, what optargs
548
822
    else:
549
823
        args = argv
550
824
 
551
 
    options, args = parser.parse_args(args)
 
825
    # for python 2.5 and later, optparse raises this exception if a non-ascii
 
826
    # option name is given.  See http://bugs.python.org/issue2931
 
827
    try:
 
828
        options, args = parser.parse_args(args)
 
829
    except UnicodeEncodeError,e:
 
830
        raise errors.BzrCommandError('Only ASCII permitted in option names')
 
831
 
552
832
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
553
833
                 v is not option.OptionParser.DEFAULT_VALUE])
554
834
    return args, opts
590
870
                               % (cmd, argname.upper()))
591
871
            else:
592
872
                argdict[argname] = args.pop(0)
593
 
            
 
873
 
594
874
    if args:
595
875
        raise errors.BzrCommandError("extra argument to command %s: %s"
596
876
                                     % (cmd, args[0]))
604
884
 
605
885
    tracer = trace.Trace(count=1, trace=0)
606
886
    sys.settrace(tracer.globaltrace)
607
 
 
608
 
    ret = the_callable(*args, **kwargs)
609
 
 
610
 
    sys.settrace(None)
611
 
    results = tracer.results()
612
 
    results.write_results(show_missing=1, summary=False,
613
 
                          coverdir=dirname)
 
887
    threading.settrace(tracer.globaltrace)
 
888
 
 
889
    try:
 
890
        return exception_to_return_code(the_callable, *args, **kwargs)
 
891
    finally:
 
892
        sys.settrace(None)
 
893
        results = tracer.results()
 
894
        results.write_results(show_missing=1, summary=False,
 
895
                              coverdir=dirname)
614
896
 
615
897
 
616
898
def apply_profiled(the_callable, *args, **kwargs):
621
903
    try:
622
904
        prof = hotshot.Profile(pfname)
623
905
        try:
624
 
            ret = prof.runcall(the_callable, *args, **kwargs) or 0
 
906
            ret = prof.runcall(exception_to_return_code, the_callable, *args,
 
907
                **kwargs) or 0
625
908
        finally:
626
909
            prof.close()
627
910
        stats = hotshot.stats.load(pfname)
636
919
        os.remove(pfname)
637
920
 
638
921
 
 
922
def exception_to_return_code(the_callable, *args, **kwargs):
 
923
    """UI level helper for profiling and coverage.
 
924
 
 
925
    This transforms exceptions into a return value of 3. As such its only
 
926
    relevant to the UI layer, and should never be called where catching
 
927
    exceptions may be desirable.
 
928
    """
 
929
    try:
 
930
        return the_callable(*args, **kwargs)
 
931
    except (KeyboardInterrupt, Exception), e:
 
932
        # used to handle AssertionError and KeyboardInterrupt
 
933
        # specially here, but hopefully they're handled ok by the logger now
 
934
        exc_info = sys.exc_info()
 
935
        exitcode = trace.report_exception(exc_info, sys.stderr)
 
936
        if os.environ.get('BZR_PDB'):
 
937
            print '**** entering debugger'
 
938
            tb = exc_info[2]
 
939
            import pdb
 
940
            if sys.version_info[:2] < (2, 6):
 
941
                # XXX: we want to do
 
942
                #    pdb.post_mortem(tb)
 
943
                # but because pdb.post_mortem gives bad results for tracebacks
 
944
                # from inside generators, we do it manually.
 
945
                # (http://bugs.python.org/issue4150, fixed in Python 2.6)
 
946
 
 
947
                # Setup pdb on the traceback
 
948
                p = pdb.Pdb()
 
949
                p.reset()
 
950
                p.setup(tb.tb_frame, tb)
 
951
                # Point the debugger at the deepest frame of the stack
 
952
                p.curindex = len(p.stack) - 1
 
953
                p.curframe = p.stack[p.curindex][0]
 
954
                # Start the pdb prompt.
 
955
                p.print_stack_entry(p.stack[p.curindex])
 
956
                p.execRcLines()
 
957
                p.cmdloop()
 
958
            else:
 
959
                pdb.post_mortem(tb)
 
960
        return exitcode
 
961
 
 
962
 
639
963
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
640
964
    from bzrlib.lsprof import profile
641
 
    ret, stats = profile(the_callable, *args, **kwargs)
 
965
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
642
966
    stats.sort()
643
967
    if filename is None:
644
968
        stats.pprint()
648
972
    return ret
649
973
 
650
974
 
 
975
@deprecated_function(deprecated_in((2, 2, 0)))
651
976
def shlex_split_unicode(unsplit):
652
 
    import shlex
653
 
    return [u.decode('utf-8') for u in shlex.split(unsplit.encode('utf-8'))]
 
977
    return cmdline.split(unsplit)
654
978
 
655
979
 
656
980
def get_alias(cmd, config=None):
668
992
        config = bzrlib.config.GlobalConfig()
669
993
    alias = config.get_alias(cmd)
670
994
    if (alias):
671
 
        return shlex_split_unicode(alias)
 
995
        return cmdline.split(alias)
672
996
    return None
673
997
 
674
998
 
675
 
def run_bzr(argv):
 
999
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
676
1000
    """Execute a command.
677
1001
 
678
 
    This is similar to main(), but without all the trappings for
679
 
    logging and error handling.  
680
 
    
681
 
    argv
682
 
       The command-line arguments, without the program name from argv[0]
683
 
       These should already be decoded. All library/test code calling
684
 
       run_bzr should be passing valid strings (don't need decoding).
685
 
    
686
 
    Returns a command status or raises an exception.
 
1002
    :param argv: The command-line arguments, without the program name from
 
1003
        argv[0] These should already be decoded. All library/test code calling
 
1004
        run_bzr should be passing valid strings (don't need decoding).
 
1005
    :param load_plugins: What function to call when triggering plugin loading.
 
1006
        This function should take no arguments and cause all plugins to be
 
1007
        loaded.
 
1008
    :param disable_plugins: What function to call when disabling plugin
 
1009
        loading. This function should take no arguments and cause all plugin
 
1010
        loading to be prohibited (so that code paths in your application that
 
1011
        know about some plugins possibly being present will fail to import
 
1012
        those plugins even if they are installed.)
 
1013
    :return: Returns a command exit code or raises an exception.
687
1014
 
688
1015
    Special master options: these must come before the command because
689
1016
    they control how the command is interpreted.
706
1033
 
707
1034
    --coverage
708
1035
        Generate line coverage report in the specified directory.
 
1036
 
 
1037
    --concurrency
 
1038
        Specify the number of processes that can be run concurrently (selftest).
709
1039
    """
710
 
    argv = list(argv)
 
1040
    trace.mutter("bazaar version: " + bzrlib.__version__)
 
1041
    argv = _specified_or_unicode_argv(argv)
711
1042
    trace.mutter("bzr arguments: %r", argv)
712
1043
 
713
1044
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
736
1067
            opt_no_aliases = True
737
1068
        elif a == '--builtin':
738
1069
            opt_builtin = True
 
1070
        elif a == '--concurrency':
 
1071
            os.environ['BZR_CONCURRENCY'] = argv[i + 1]
 
1072
            i += 1
739
1073
        elif a == '--coverage':
740
1074
            opt_coverage_dir = argv[i + 1]
741
1075
            i += 1
 
1076
        elif a == '--profile-imports':
 
1077
            pass # already handled in startup script Bug #588277
742
1078
        elif a.startswith('-D'):
743
1079
            debug.debug_flags.add(a[2:])
744
1080
        else:
745
1081
            argv_copy.append(a)
746
1082
        i += 1
747
1083
 
 
1084
    debug.set_debug_flags_from_config()
 
1085
 
 
1086
    if not opt_no_plugins:
 
1087
        load_plugins()
 
1088
    else:
 
1089
        disable_plugins()
 
1090
 
748
1091
    argv = argv_copy
749
1092
    if (not argv):
750
 
        from bzrlib.builtins import cmd_help
751
 
        cmd_help().run_argv_aliases([])
 
1093
        get_cmd_object('help').run_argv_aliases([])
752
1094
        return 0
753
1095
 
754
1096
    if argv[0] == '--version':
755
 
        from bzrlib.builtins import cmd_version
756
 
        cmd_version().run_argv_aliases([])
 
1097
        get_cmd_object('version').run_argv_aliases([])
757
1098
        return 0
758
 
        
759
 
    if not opt_no_plugins:
760
 
        from bzrlib.plugin import load_plugins
761
 
        load_plugins()
762
 
    else:
763
 
        from bzrlib.plugin import disable_plugins
764
 
        disable_plugins()
765
1099
 
766
1100
    alias_argv = None
767
1101
 
768
1102
    if not opt_no_aliases:
769
1103
        alias_argv = get_alias(argv[0])
770
1104
        if alias_argv:
771
 
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
772
1105
            argv[0] = alias_argv.pop(0)
773
1106
 
774
1107
    cmd = argv.pop(0)
775
 
    # We want only 'ascii' command names, but the user may have typed
776
 
    # in a Unicode name. In that case, they should just get a
777
 
    # 'command not found' error later.
778
 
 
779
1108
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
780
1109
    run = cmd_obj.run_argv_aliases
781
1110
    run_argv = [argv, alias_argv]
782
1111
 
783
1112
    try:
 
1113
        # We can be called recursively (tests for example), but we don't want
 
1114
        # the verbosity level to propagate.
 
1115
        saved_verbosity_level = option._verbosity_level
 
1116
        option._verbosity_level = 0
784
1117
        if opt_lsprof:
785
1118
            if opt_coverage_dir:
786
1119
                trace.warning(
795
1128
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
796
1129
        else:
797
1130
            ret = run(*run_argv)
 
1131
        return ret or 0
 
1132
    finally:
 
1133
        # reset, in case we may do other commands later within the same
 
1134
        # process. Commands that want to execute sub-commands must propagate
 
1135
        # --verbose in their own way.
798
1136
        if 'memory' in debug.debug_flags:
799
 
            try:
800
 
                status_file = file('/proc/%s/status' % os.getpid(), 'rb')
801
 
            except IOError:
802
 
                pass
803
 
            else:
804
 
                status = status_file.read()
805
 
                status_file.close()
806
 
                trace.note("Process status after command:")
807
 
                for line in status.splitlines():
808
 
                    trace.note(line)
809
 
        return ret or 0
810
 
    finally:
811
 
        # reset, in case we may do other commands later within the same process
812
 
        option._verbosity_level = 0
 
1137
            trace.debug_memory('Process status after command:', short=False)
 
1138
        option._verbosity_level = saved_verbosity_level
 
1139
 
813
1140
 
814
1141
def display_command(func):
815
1142
    """Decorator that suppresses pipe/interrupt errors."""
831
1158
    return ignore_pipe
832
1159
 
833
1160
 
834
 
def main(argv):
835
 
    import bzrlib.ui
836
 
    from bzrlib.ui.text import TextUIFactory
837
 
    bzrlib.ui.ui_factory = TextUIFactory()
838
 
     
839
 
    # Is this a final release version? If so, we should suppress warnings
840
 
    if bzrlib.version_info[3] == 'final':
841
 
        from bzrlib import symbol_versioning
842
 
        symbol_versioning.suppress_deprecation_warnings(override=False)
843
 
    try:
844
 
        argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
845
 
    except UnicodeDecodeError:
846
 
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
847
 
                                                            "encoding." % a))
 
1161
def install_bzr_command_hooks():
 
1162
    """Install the hooks to supply bzr's own commands."""
 
1163
    if _list_bzr_commands in Command.hooks["list_commands"]:
 
1164
        return
 
1165
    Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
 
1166
        "bzr commands")
 
1167
    Command.hooks.install_named_hook("get_command", _get_bzr_command,
 
1168
        "bzr commands")
 
1169
    Command.hooks.install_named_hook("get_command", _get_plugin_command,
 
1170
        "bzr plugin commands")
 
1171
    Command.hooks.install_named_hook("get_command", _get_external_command,
 
1172
        "bzr external command lookup")
 
1173
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
 
1174
        "bzr plugin-provider-db check")
 
1175
 
 
1176
 
 
1177
 
 
1178
def _specified_or_unicode_argv(argv):
 
1179
    # For internal or testing use, argv can be passed.  Otherwise, get it from
 
1180
    # the process arguments in a unicode-safe way.
 
1181
    if argv is None:
 
1182
        return osutils.get_unicode_argv()
 
1183
    else:
 
1184
        new_argv = []
 
1185
        try:
 
1186
            # ensure all arguments are unicode strings
 
1187
            for a in argv:
 
1188
                if isinstance(a, unicode):
 
1189
                    new_argv.append(a)
 
1190
                else:
 
1191
                    new_argv.append(a.decode('ascii'))
 
1192
        except UnicodeDecodeError:
 
1193
            raise errors.BzrError("argv should be list of unicode strings.")
 
1194
        return new_argv
 
1195
 
 
1196
 
 
1197
def main(argv=None):
 
1198
    """Main entry point of command-line interface.
 
1199
 
 
1200
    Typically `bzrlib.initialize` should be called first.
 
1201
 
 
1202
    :param argv: list of unicode command-line arguments similar to sys.argv.
 
1203
        argv[0] is script name usually, it will be ignored.
 
1204
        Don't pass here sys.argv because this list contains plain strings
 
1205
        and not unicode; pass None instead.
 
1206
 
 
1207
    :return: exit code of bzr command.
 
1208
    """
 
1209
    if argv is not None:
 
1210
        argv = argv[1:]
 
1211
    _register_builtin_commands()
848
1212
    ret = run_bzr_catch_errors(argv)
849
1213
    trace.mutter("return code %d", ret)
850
1214
    return ret
851
1215
 
852
1216
 
853
1217
def run_bzr_catch_errors(argv):
854
 
    # Note: The except clause logic below should be kept in sync with the
855
 
    # profile() routine in lsprof.py.
856
 
    try:
857
 
        return run_bzr(argv)
858
 
    except (KeyboardInterrupt, Exception), e:
859
 
        # used to handle AssertionError and KeyboardInterrupt
860
 
        # specially here, but hopefully they're handled ok by the logger now
861
 
        exitcode = trace.report_exception(sys.exc_info(), sys.stderr)
862
 
        if os.environ.get('BZR_PDB'):
863
 
            print '**** entering debugger'
864
 
            import pdb
865
 
            pdb.post_mortem(sys.exc_traceback)
866
 
        return exitcode
 
1218
    """Run a bzr command with parameters as described by argv.
 
1219
 
 
1220
    This function assumed that that UI layer is setup, that symbol deprecations
 
1221
    are already applied, and that unicode decoding has already been performed on argv.
 
1222
    """
 
1223
    # done here so that they're covered for every test run
 
1224
    install_bzr_command_hooks()
 
1225
    return exception_to_return_code(run_bzr, argv)
867
1226
 
868
1227
 
869
1228
def run_bzr_catch_user_errors(argv):
872
1231
    This is used for the test suite, and might be useful for other programs
873
1232
    that want to wrap the commandline interface.
874
1233
    """
 
1234
    # done here so that they're covered for every test run
 
1235
    install_bzr_command_hooks()
875
1236
    try:
876
1237
        return run_bzr(argv)
877
1238
    except Exception, e:
899
1260
        if topic and topic.startswith(self.prefix):
900
1261
            topic = topic[len(self.prefix):]
901
1262
        try:
902
 
            cmd = _get_cmd_object(topic)
 
1263
            cmd = _get_cmd_object(topic, check_missing=False)
903
1264
        except KeyError:
904
1265
            return []
905
1266
        else:
907
1268
 
908
1269
 
909
1270
class Provider(object):
910
 
    '''Generic class to be overriden by plugins'''
 
1271
    """Generic class to be overriden by plugins"""
911
1272
 
912
1273
    def plugin_for_command(self, cmd_name):
913
 
        '''Takes a command and returns the information for that plugin
914
 
        
915
 
        :return: A dictionary with all the available information 
916
 
        for the requested plugin
917
 
        '''
 
1274
        """Takes a command and returns the information for that plugin
 
1275
 
 
1276
        :return: A dictionary with all the available information
 
1277
            for the requested plugin
 
1278
        """
918
1279
        raise NotImplementedError
919
1280
 
920
1281
 
921
1282
class ProvidersRegistry(registry.Registry):
922
 
    '''This registry exists to allow other providers to exist'''
 
1283
    """This registry exists to allow other providers to exist"""
923
1284
 
924
1285
    def __iter__(self):
925
1286
        for key, provider in self.iteritems():
926
1287
            yield provider
927
1288
 
928
1289
command_providers_registry = ProvidersRegistry()
929
 
 
930
 
 
931
 
if __name__ == '__main__':
932
 
    sys.exit(main(sys.argv))