~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Vincent Ladeuil
  • Date: 2009-05-04 14:48:21 UTC
  • mto: (4349.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4350.
  • Revision ID: v.ladeuil+lp@free.fr-20090504144821-39dvqkikmd3zqkdg
Handle servers proposing several authentication schemes.

* bzrlib/transport/http/_urllib2_wrappers.py:
(AbstractAuthHandler.auth_required): Several schemes can be
proposed by the server, try to match each one in turn.
(BasicAuthHandler.auth_match): Delete dead code.

* bzrlib/tests/test_http.py:
(load_tests): Separate proxy and http authentication tests as they
require different server setups.
(TestAuth.create_transport_readonly_server): Simplified by using
parameter provided by load_tests.
(TestAuth.test_changing_nonce): Adapt to new parametrization.
(TestProxyAuth.create_transport_readonly_server): Deleted.

* bzrlib/tests/http_utils.py:
(DigestAndBasicAuthRequestHandler, HTTPBasicAndDigestAuthServer,
ProxyBasicAndDigestAuthServer): Add a test server proposing both
basic and digest auth schemes but accepting only digest as valid.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2008 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
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
 
18
# TODO: probably should say which arguments are candidates for glob
 
19
# expansion on windows and do that at the command level.
 
20
 
18
21
# TODO: Define arguments by objects, rather than just using names.
19
22
# Those objects can specify the expected type of the argument, which
20
23
# would help with validation and shell completion.  They could also provide
22
25
 
23
26
# TODO: Specific "examples" property on commands for consistent formatting.
24
27
 
 
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
 
25
31
import os
26
32
import sys
27
33
 
28
34
from bzrlib.lazy_import import lazy_import
29
35
lazy_import(globals(), """
 
36
import codecs
30
37
import errno
31
 
import threading
 
38
from warnings import warn
32
39
 
33
40
import bzrlib
34
41
from bzrlib import (
35
 
    cleanup,
36
 
    cmdline,
37
42
    debug,
38
43
    errors,
39
 
    i18n,
40
44
    option,
41
45
    osutils,
42
46
    trace,
43
 
    ui,
 
47
    win32utils,
44
48
    )
45
49
""")
46
50
 
47
 
from bzrlib.hooks import Hooks
48
 
from bzrlib.i18n import gettext
49
 
# Compatibility - Option used to be in commands.
 
51
from bzrlib import registry
 
52
# Compatibility
 
53
from bzrlib.hooks import HookPoint, Hooks
50
54
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
55
 
59
56
 
60
57
class CommandInfo(object):
71
68
 
72
69
 
73
70
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
71
 
91
72
    @staticmethod
92
73
    def _get_name(command_name):
108
89
        try:
109
90
            previous = self.get(k_unsquished)
110
91
        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
 
92
            previous = _builtin_commands().get(k_unsquished)
117
93
        info = CommandInfo.from_command(cmd)
118
94
        try:
119
95
            registry.Registry.register(self, k_unsquished, cmd,
120
96
                                       override_existing=decorate, info=info)
121
97
        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
 
98
            trace.log_error('Two plugins defined the same command: %r' % k)
 
99
            trace.log_error('Not loading the one in %r' %
 
100
                            sys.modules[cmd.__module__])
 
101
            trace.log_error('Previously this command was registered from %r' %
 
102
                            sys.modules[previous.__module__])
129
103
        return previous
130
104
 
131
105
    def register_lazy(self, command_name, aliases, module_name):
138
112
        key = self._get_name(command_name)
139
113
        registry.Registry.register_lazy(self, key, module_name, command_name,
140
114
                                        info=CommandInfo(aliases))
141
 
        for a in aliases:
142
 
            self._alias_dict[a] = key
143
115
 
144
116
 
145
117
plugin_cmds = CommandRegistry()
146
 
builtin_command_registry = CommandRegistry()
147
 
plugin_cmds.overridden_registry = builtin_command_registry
148
118
 
149
119
 
150
120
def register_command(cmd, decorate=False):
151
 
    """Register a plugin command.
152
 
 
153
 
    Should generally be avoided in favor of lazy registration. 
154
 
    """
155
121
    global plugin_cmds
156
122
    return plugin_cmds.register(cmd, decorate)
157
123
 
164
130
    return cmd[4:].replace('_','-')
165
131
 
166
132
 
167
 
@deprecated_function(deprecated_in((2, 2, 0)))
168
133
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
134
    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
135
    r = {}
189
 
    for name, obj in module.__dict__.iteritems():
 
136
    builtins = bzrlib.builtins.__dict__
 
137
    for name in builtins:
190
138
        if name.startswith("cmd_"):
191
139
            real_name = _unsquish_command_name(name)
192
 
            r[real_name] = obj
 
140
            r[real_name] = builtins[name]
193
141
    return r
194
142
 
195
143
 
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
 
 
217
 
 
218
144
def builtin_command_names():
219
 
    """Return list of builtin command names.
220
 
    
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()
 
145
    """Return list of builtin command names."""
 
146
    return _builtin_commands().keys()
226
147
 
227
148
 
228
149
def plugin_command_names():
229
 
    """Returns command names from commands registered by plugins."""
230
150
    return plugin_cmds.keys()
231
151
 
232
152
 
 
153
def _get_cmd_dict(plugins_override=True):
 
154
    """Return name->class mapping for all commands."""
 
155
    d = _builtin_commands()
 
156
    if plugins_override:
 
157
        d.update(plugin_cmds.iteritems())
 
158
    return d
 
159
 
 
160
 
 
161
def get_all_cmds(plugins_override=True):
 
162
    """Return canonical name and class for all registered commands."""
 
163
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
164
        yield k,v
 
165
 
 
166
 
233
167
def get_cmd_object(cmd_name, plugins_override=True):
234
 
    """Return the command object for a command.
 
168
    """Return the canonical name and command class for a command.
235
169
 
236
170
    plugins_override
237
171
        If true, plugin commands can override builtins.
238
172
    """
239
173
    try:
240
 
        return _get_cmd_object(cmd_name, plugins_override)
 
174
        cmd = _get_cmd_object(cmd_name, plugins_override)
 
175
        # Allow plugins to extend commands
 
176
        for hook in Command.hooks['extend_command']:
 
177
            hook(cmd)
 
178
        return cmd
241
179
    except KeyError:
242
180
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
243
181
 
244
182
 
245
 
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
246
 
    """Get a command object.
 
183
def _get_cmd_object(cmd_name, plugins_override=True):
 
184
    """Worker for get_cmd_object which raises KeyError rather than BzrCommandError."""
 
185
    from bzrlib.externalcommand import ExternalCommand
247
186
 
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
187
    # We want only 'ascii' command names, but the user may have typed
256
188
    # in a Unicode name. In that case, they should just get a
257
189
    # 'command not found' error later.
258
190
    # 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:
 
191
 
 
192
    # first look up this command under the specified name
 
193
    if plugins_override:
302
194
        try:
303
 
            return provider.plugin_for_command(cmd_name), provider
304
 
        except errors.NoPluginAvailable:
 
195
            return plugin_cmds.get(cmd_name)()
 
196
        except KeyError:
305
197
            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."""
 
198
    cmds = _get_cmd_dict(plugins_override=False)
311
199
    try:
312
 
        cmd_class = builtin_command_registry.get(cmd_name)
 
200
        return cmds[cmd_name]()
313
201
    except KeyError:
314
202
        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
 
    from bzrlib.externalcommand import ExternalCommand
 
203
    if plugins_override:
 
204
        for key in plugin_cmds.keys():
 
205
            info = plugin_cmds.get_info(key)
 
206
            if cmd_name in info.aliases:
 
207
                return plugin_cmds.get(key)()
 
208
    # look for any command which claims this as an alias
 
209
    for real_cmd_name, cmd_class in cmds.iteritems():
 
210
        if cmd_name in cmd_class.aliases:
 
211
            return cmd_class()
 
212
 
326
213
    cmd_obj = ExternalCommand.find_command(cmd_name)
327
214
    if cmd_obj:
328
215
        return cmd_obj
329
216
 
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
 
217
    # look for plugins that provide this command but aren't installed
 
218
    for provider in command_providers_registry:
 
219
        try:
 
220
            plugin_metadata = provider.plugin_for_command(cmd_name)
 
221
        except errors.NoPluginAvailable:
 
222
            pass
 
223
        else:
 
224
            raise errors.CommandAvailableInPlugin(cmd_name,
 
225
                                                  plugin_metadata, provider)
 
226
    raise KeyError
342
227
 
343
228
 
344
229
class Command(object):
359
244
    summary, then a complete description of the command.  A grammar
360
245
    description will be inserted.
361
246
 
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
 
247
    aliases
 
248
        Other accepted names for this command.
 
249
 
 
250
    takes_args
 
251
        List of argument forms, marked with whether they are optional,
 
252
        repeated, etc.
 
253
 
 
254
                Examples:
 
255
 
 
256
                ['to_location', 'from_branch?', 'file*']
 
257
 
 
258
                'to_location' is required
 
259
                'from_branch' is optional
 
260
                'file' can be specified 0 or more times
 
261
 
 
262
    takes_options
 
263
        List of options that may be given for this command.  These can
 
264
        be either strings, referring to globally-defined options,
 
265
        or option objects.  Retrieve through options().
 
266
 
 
267
    hidden
 
268
        If true, this command isn't advertised.  This is typically
378
269
        for commands intended for expert users.
379
270
 
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.)
 
271
    encoding_type
 
272
        Command objects will get a 'outf' attribute, which has been
 
273
        setup to properly handle encoding of unicode strings.
 
274
        encoding_type determines what will happen when characters cannot
 
275
        be encoded
 
276
            strict - abort if we cannot decode
 
277
            replace - put in a bogus character (typically '?')
 
278
            exact - do not encode sys.stdout
 
279
 
 
280
            NOTE: by default on Windows, sys.stdout is opened as a text
 
281
            stream, therefore LF line-endings are converted to CRLF.
 
282
            When a command uses encoding_type = 'exact', then
 
283
            sys.stdout is forced to be a binary stream, and line-endings
 
284
            will not mangled.
398
285
 
399
286
    :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
287
    """
408
288
    aliases = []
409
289
    takes_args = []
410
290
    takes_options = []
411
291
    encoding_type = 'strict'
412
 
    invoked_as = None
413
 
    l10n = True
414
292
 
415
293
    hidden = False
416
294
 
417
295
    def __init__(self):
418
296
        """Construct an instance of this command."""
 
297
        if self.__doc__ == Command.__doc__:
 
298
            warn("No help message set for %r" % self)
419
299
        # List of standard options directly supported
420
300
        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)))
 
301
 
446
302
    def _maybe_expand_globs(self, file_list):
447
303
        """Glob expand file_list if the platform does not do that itself.
448
304
 
449
 
        Not used anymore, now that the bzr command-line parser globs on
450
 
        Windows.
451
 
 
452
305
        :return: A possibly empty list of unicode paths.
453
306
 
454
307
        Introduced in bzrlib 0.18.
455
308
        """
456
 
        return file_list
 
309
        if not file_list:
 
310
            file_list = []
 
311
        if sys.platform == 'win32':
 
312
            file_list = win32utils.glob_expand(file_list)
 
313
        return list(file_list)
457
314
 
458
315
    def _usage(self):
459
316
        """Return single-line grammar for this command.
488
345
            usage help (e.g. Purpose, Usage, Options) with a
489
346
            message explaining how to obtain full help.
490
347
        """
491
 
        if self.l10n and not i18n.installed():
492
 
            i18n.install()  # Install i18n only for get_help_text for now.
493
348
        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.")
 
349
        if doc is None:
 
350
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
503
351
 
504
352
        # Extract the summary (purpose) and sections out from the text
505
353
        purpose,sections,order = self._get_help_parts(doc)
512
360
 
513
361
        # The header is the purpose and usage
514
362
        result = ""
515
 
        result += gettext(':Purpose: %s\n') % (purpose,)
 
363
        result += ':Purpose: %s\n' % purpose
516
364
        if usage.find('\n') >= 0:
517
 
            result += gettext(':Usage:\n%s\n') % (usage,)
 
365
            result += ':Usage:\n%s\n' % usage
518
366
        else:
519
 
            result += gettext(':Usage:   %s\n') % (usage,)
 
367
            result += ':Usage:   %s\n' % usage
520
368
        result += '\n'
521
369
 
522
370
        # 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)
 
371
        options = option.get_optparser(self.options()).format_option_help()
537
372
        if options.startswith('Options:'):
538
 
            result += gettext(':Options:%s') % (options[len('options:'):],)
 
373
            result += ':' + options
 
374
        elif options.startswith('options:'):
 
375
            # Python 2.4 version of optparse
 
376
            result += ':Options:' + options[len('options:'):]
539
377
        else:
540
378
            result += options
541
379
        result += '\n'
546
384
            if sections.has_key(None):
547
385
                text = sections.pop(None)
548
386
                text = '\n  '.join(text.splitlines())
549
 
                result += gettext(':Description:\n  %s\n\n') % (text,)
 
387
                result += ':%s:\n  %s\n\n' % ('Description',text)
550
388
 
551
389
            # Add the custom sections (e.g. Examples). Note that there's no need
552
390
            # to indent these as they must be indented already in the source.
553
391
            if sections:
554
392
                for label in order:
555
 
                    if label in sections:
556
 
                        result += ':%s:\n%s\n' % (label, sections[label])
 
393
                    if sections.has_key(label):
 
394
                        result += ':%s:\n%s\n' % (label,sections[label])
557
395
                result += '\n'
558
396
        else:
559
 
            result += (gettext("See bzr help %s for more details and examples.\n\n")
 
397
            result += ("See bzr help %s for more details and examples.\n\n"
560
398
                % self.name())
561
399
 
562
400
        # Add the aliases, source (plug-in) and see also links, if any
563
401
        if self.aliases:
564
 
            result += gettext(':Aliases:  ')
 
402
            result += ':Aliases:  '
565
403
            result += ', '.join(self.aliases) + '\n'
566
404
        plugin_name = self.plugin_name()
567
405
        if plugin_name is not None:
568
 
            result += gettext(':From:     plugin "%s"\n') % plugin_name
 
406
            result += ':From:     plugin "%s"\n' % plugin_name
569
407
        see_also = self.get_see_also(additional_see_also)
570
408
        if see_also:
571
409
            if not plain and see_also_as_links:
576
414
                        # so don't create a real link
577
415
                        see_also_links.append(item)
578
416
                    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)
 
417
                        # Use a reST link for this entry
 
418
                        see_also_links.append("`%s`_" % (item,))
582
419
                see_also = see_also_links
583
 
            result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
 
420
            result += ':See also: '
 
421
            result += ', '.join(see_also) + '\n'
584
422
 
585
423
        # If this will be rendered as plain text, convert it
586
424
        if plain:
661
499
 
662
500
    def _setup_outf(self):
663
501
        """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)
 
502
        # Originally I was using self.stdout, but that looks
 
503
        # *way* too much like sys.stdout
 
504
        if self.encoding_type == 'exact':
 
505
            # force sys.stdout to be binary stream on win32
 
506
            if sys.platform == 'win32':
 
507
                fileno = getattr(sys.stdout, 'fileno', None)
 
508
                if fileno:
 
509
                    import msvcrt
 
510
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
511
            self.outf = sys.stdout
 
512
            return
 
513
 
 
514
        output_encoding = osutils.get_terminal_encoding()
 
515
 
 
516
        self.outf = codecs.getwriter(output_encoding)(sys.stdout,
 
517
                        errors=self.encoding_type)
 
518
        # For whatever reason codecs.getwriter() does not advertise its encoding
 
519
        # it just returns the encoding of the wrapped file, which is completely
 
520
        # bogus. So set the attribute, so we can find the correct encoding later.
 
521
        self.outf.encoding = output_encoding
666
522
 
667
523
    def run_argv_aliases(self, argv, alias_argv=None):
668
524
        """Parse the command line and run with extra aliases in alias_argv."""
 
525
        if argv is None:
 
526
            warn("Passing None for [] is deprecated from bzrlib 0.10",
 
527
                 DeprecationWarning, stacklevel=2)
 
528
            argv = []
669
529
        args, opts = parse_args(self, argv, alias_argv)
670
 
        self._setup_outf()
671
530
 
672
531
        # Process the standard options
673
532
        if 'help' in opts:  # e.g. bzr add --help
674
 
            self.outf.write(self.get_help_text())
 
533
            sys.stdout.write(self.get_help_text())
675
534
            return 0
676
535
        if 'usage' in opts:  # e.g. bzr add --usage
677
 
            self.outf.write(self.get_help_text(verbose=False))
 
536
            sys.stdout.write(self.get_help_text(verbose=False))
678
537
            return 0
679
538
        trace.set_verbosity_level(option._verbosity_level)
680
539
        if 'verbose' in self.supported_std_options:
695
554
        all_cmd_args = cmdargs.copy()
696
555
        all_cmd_args.update(cmdopts)
697
556
 
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)
 
557
        self._setup_outf()
 
558
 
 
559
        return self.run(**all_cmd_args)
730
560
 
731
561
    def run(self):
732
562
        """Actually run the command.
737
567
        Return 0 or None if the command was successful, or a non-zero
738
568
        shell error code if not.  It's OK for this method to allow
739
569
        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
570
        """
752
571
        raise NotImplementedError('no implementation of command %r'
753
572
                                  % self.name())
759
578
            return None
760
579
        return getdoc(self)
761
580
 
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
581
    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
582
        return _unsquish_command_name(self.__class__.__name__)
776
583
 
777
584
    def plugin_name(self):
795
602
        These are all empty initially, because by default nothing should get
796
603
        notified.
797
604
        """
798
 
        Hooks.__init__(self, "bzrlib.commands", "Command.hooks")
799
 
        self.add_hook('extend_command',
 
605
        Hooks.__init__(self)
 
606
        self.create_hook(HookPoint('extend_command',
800
607
            "Called after creating a command object to allow modifications "
801
608
            "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))
 
609
            "new bzrlib.commands.Command object.", (1, 13), None))
822
610
 
823
611
Command.hooks = CommandHooks()
824
612
 
838
626
    else:
839
627
        args = argv
840
628
 
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
 
 
 
629
    options, args = parser.parse_args(args)
848
630
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
849
631
                 v is not option.OptionParser.DEFAULT_VALUE])
850
632
    return args, opts
900
682
 
901
683
    tracer = trace.Trace(count=1, trace=0)
902
684
    sys.settrace(tracer.globaltrace)
903
 
    threading.settrace(tracer.globaltrace)
904
685
 
905
686
    try:
906
687
        return exception_to_return_code(the_callable, *args, **kwargs)
988
769
    return ret
989
770
 
990
771
 
991
 
@deprecated_function(deprecated_in((2, 2, 0)))
992
772
def shlex_split_unicode(unsplit):
993
 
    return cmdline.split(unsplit)
 
773
    import shlex
 
774
    return [u.decode('utf-8') for u in shlex.split(unsplit.encode('utf-8'))]
994
775
 
995
776
 
996
777
def get_alias(cmd, config=None):
1008
789
        config = bzrlib.config.GlobalConfig()
1009
790
    alias = config.get_alias(cmd)
1010
791
    if (alias):
1011
 
        return cmdline.split(alias)
 
792
        return shlex_split_unicode(alias)
1012
793
    return None
1013
794
 
1014
795
 
1015
 
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
 
796
def run_bzr(argv):
1016
797
    """Execute a command.
1017
798
 
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.
 
799
    argv
 
800
       The command-line arguments, without the program name from argv[0]
 
801
       These should already be decoded. All library/test code calling
 
802
       run_bzr should be passing valid strings (don't need decoding).
 
803
 
 
804
    Returns a command status or raises an exception.
1030
805
 
1031
806
    Special master options: these must come before the command because
1032
807
    they control how the command is interpreted.
1049
824
 
1050
825
    --coverage
1051
826
        Generate line coverage report in the specified directory.
1052
 
 
1053
 
    --concurrency
1054
 
        Specify the number of processes that can be run concurrently (selftest).
1055
827
    """
1056
 
    trace.mutter("bazaar version: " + bzrlib.__version__)
1057
 
    argv = _specified_or_unicode_argv(argv)
 
828
    argv = list(argv)
1058
829
    trace.mutter("bzr arguments: %r", argv)
1059
830
 
1060
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
1061
 
            opt_no_l10n = opt_no_aliases = False
 
831
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
 
832
                opt_no_aliases = False
1062
833
    opt_lsprof_file = opt_coverage_dir = None
1063
834
 
1064
835
    # --no-plugins is handled specially at a very early stage. We need
1081
852
            opt_no_plugins = True
1082
853
        elif a == '--no-aliases':
1083
854
            opt_no_aliases = True
1084
 
        elif a == '--no-l10n':
1085
 
            opt_no_l10n = True
1086
855
        elif a == '--builtin':
1087
856
            opt_builtin = True
1088
 
        elif a == '--concurrency':
1089
 
            os.environ['BZR_CONCURRENCY'] = argv[i + 1]
1090
 
            i += 1
1091
857
        elif a == '--coverage':
1092
858
            opt_coverage_dir = argv[i + 1]
1093
859
            i += 1
1094
 
        elif a == '--profile-imports':
1095
 
            pass # already handled in startup script Bug #588277
1096
860
        elif a.startswith('-D'):
1097
861
            debug.debug_flags.add(a[2:])
1098
862
        else:
1101
865
 
1102
866
    debug.set_debug_flags_from_config()
1103
867
 
 
868
    argv = argv_copy
 
869
    if (not argv):
 
870
        from bzrlib.builtins import cmd_help
 
871
        cmd_help().run_argv_aliases([])
 
872
        return 0
 
873
 
 
874
    if argv[0] == '--version':
 
875
        from bzrlib.builtins import cmd_version
 
876
        cmd_version().run_argv_aliases([])
 
877
        return 0
 
878
 
1104
879
    if not opt_no_plugins:
 
880
        from bzrlib.plugin import load_plugins
1105
881
        load_plugins()
1106
882
    else:
 
883
        from bzrlib.plugin import disable_plugins
1107
884
        disable_plugins()
1108
885
 
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
886
    alias_argv = None
1119
887
 
1120
888
    if not opt_no_aliases:
1121
889
        alias_argv = get_alias(argv[0])
1122
890
        if alias_argv:
 
891
            user_encoding = osutils.get_user_encoding()
 
892
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
1123
893
            argv[0] = alias_argv.pop(0)
1124
894
 
1125
895
    cmd = argv.pop(0)
 
896
    # We want only 'ascii' command names, but the user may have typed
 
897
    # in a Unicode name. In that case, they should just get a
 
898
    # 'command not found' error later.
 
899
 
1126
900
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
1127
 
    if opt_no_l10n:
1128
 
        cmd.l10n = False
1129
901
    run = cmd_obj.run_argv_aliases
1130
902
    run_argv = [argv, alias_argv]
1131
903
 
1148
920
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
1149
921
        else:
1150
922
            ret = run(*run_argv)
 
923
        if 'memory' in debug.debug_flags:
 
924
            trace.debug_memory('Process status after command:', short=False)
1151
925
        return ret or 0
1152
926
    finally:
1153
927
        # reset, in case we may do other commands later within the same
1154
928
        # process. Commands that want to execute sub-commands must propagate
1155
929
        # --verbose in their own way.
1156
 
        if 'memory' in debug.debug_flags:
1157
 
            trace.debug_memory('Process status after command:', short=False)
1158
930
        option._verbosity_level = saved_verbosity_level
1159
931
 
1160
932
 
1178
950
    return ignore_pipe
1179
951
 
1180
952
 
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()
 
953
def main(argv):
 
954
    import bzrlib.ui
 
955
    bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
 
956
        sys.stdin, sys.stdout, sys.stderr)
 
957
 
 
958
    # Is this a final release version? If so, we should suppress warnings
 
959
    if bzrlib.version_info[3] == 'final':
 
960
        from bzrlib import symbol_versioning
 
961
        symbol_versioning.suppress_deprecation_warnings(override=False)
 
962
    try:
 
963
        user_encoding = osutils.get_user_encoding()
 
964
        argv = [a.decode(user_encoding) for a in argv[1:]]
 
965
    except UnicodeDecodeError:
 
966
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
967
                                                            "encoding." % a))
1232
968
    ret = run_bzr_catch_errors(argv)
1233
969
    trace.mutter("return code %d", ret)
1234
970
    return ret
1240
976
    This function assumed that that UI layer is setup, that symbol deprecations
1241
977
    are already applied, and that unicode decoding has already been performed on argv.
1242
978
    """
1243
 
    # done here so that they're covered for every test run
1244
 
    install_bzr_command_hooks()
1245
979
    return exception_to_return_code(run_bzr, argv)
1246
980
 
1247
981
 
1251
985
    This is used for the test suite, and might be useful for other programs
1252
986
    that want to wrap the commandline interface.
1253
987
    """
1254
 
    # done here so that they're covered for every test run
1255
 
    install_bzr_command_hooks()
1256
988
    try:
1257
989
        return run_bzr(argv)
1258
990
    except Exception, e:
1280
1012
        if topic and topic.startswith(self.prefix):
1281
1013
            topic = topic[len(self.prefix):]
1282
1014
        try:
1283
 
            cmd = _get_cmd_object(topic, check_missing=False)
 
1015
            cmd = _get_cmd_object(topic)
1284
1016
        except KeyError:
1285
1017
            return []
1286
1018
        else:
1288
1020
 
1289
1021
 
1290
1022
class Provider(object):
1291
 
    """Generic class to be overriden by plugins"""
 
1023
    '''Generic class to be overriden by plugins'''
1292
1024
 
1293
1025
    def plugin_for_command(self, cmd_name):
1294
 
        """Takes a command and returns the information for that plugin
 
1026
        '''Takes a command and returns the information for that plugin
1295
1027
 
1296
1028
        :return: A dictionary with all the available information
1297
 
            for the requested plugin
1298
 
        """
 
1029
        for the requested plugin
 
1030
        '''
1299
1031
        raise NotImplementedError
1300
1032
 
1301
1033
 
1302
1034
class ProvidersRegistry(registry.Registry):
1303
 
    """This registry exists to allow other providers to exist"""
 
1035
    '''This registry exists to allow other providers to exist'''
1304
1036
 
1305
1037
    def __iter__(self):
1306
1038
        for key, provider in self.iteritems():
1307
1039
            yield provider
1308
1040
 
1309
1041
command_providers_registry = ProvidersRegistry()
 
1042
 
 
1043
 
 
1044
if __name__ == '__main__':
 
1045
    sys.exit(main(sys.argv))