~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: John Arbash Meinel
  • Date: 2005-11-30 15:43:57 UTC
  • mto: (1185.50.1 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1518.
  • Revision ID: john@arbash-meinel.com-20051130154357-614206b3a7b83cd0
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.

Show diffs side-by-side

added added

removed removed

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