/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
27
27
 
28
28
from bzrlib.lazy_import import lazy_import
29
29
lazy_import(globals(), """
 
30
import codecs
30
31
import errno
31
32
import threading
 
33
from warnings import warn
32
34
 
33
35
import bzrlib
34
36
from bzrlib import (
40
42
    osutils,
41
43
    trace,
42
44
    ui,
 
45
    win32utils,
43
46
    )
44
47
""")
45
48
 
46
 
from bzrlib.hooks import Hooks
 
49
from bzrlib.hooks import HookPoint, Hooks
47
50
# Compatibility - Option used to be in commands.
48
51
from bzrlib.option import Option
49
52
from bzrlib.plugin import disable_plugins, load_plugins
219
222
    Use of all_command_names() is encouraged rather than builtin_command_names
220
223
    and/or plugin_command_names.
221
224
    """
222
 
    _register_builtin_commands()
223
225
    return builtin_command_registry.keys()
224
226
 
225
227
 
273
275
    # Allow plugins to extend commands
274
276
    for hook in Command.hooks['extend_command']:
275
277
        hook(cmd)
276
 
    if getattr(cmd, 'invoked_as', None) is None:
277
 
        cmd.invoked_as = cmd_name
278
278
    return cmd
279
279
 
280
280
 
357
357
    summary, then a complete description of the command.  A grammar
358
358
    description will be inserted.
359
359
 
360
 
    :cvar aliases: Other accepted names for this command.
361
 
 
362
 
    :cvar takes_args: List of argument forms, marked with whether they are
363
 
        optional, repeated, etc.  Examples::
364
 
 
365
 
            ['to_location', 'from_branch?', 'file*']
366
 
 
367
 
        * 'to_location' is required
368
 
        * 'from_branch' is optional
369
 
        * 'file' can be specified 0 or more times
370
 
 
371
 
    :cvar takes_options: List of options that may be given for this command.
372
 
        These can be either strings, referring to globally-defined options, or
373
 
        option objects.  Retrieve through options().
374
 
 
375
 
    :cvar hidden: If true, this command isn't advertised.  This is typically
 
360
    aliases
 
361
        Other accepted names for this command.
 
362
 
 
363
    takes_args
 
364
        List of argument forms, marked with whether they are optional,
 
365
        repeated, etc.
 
366
 
 
367
                Examples:
 
368
 
 
369
                ['to_location', 'from_branch?', 'file*']
 
370
 
 
371
                'to_location' is required
 
372
                'from_branch' is optional
 
373
                'file' can be specified 0 or more times
 
374
 
 
375
    takes_options
 
376
        List of options that may be given for this command.  These can
 
377
        be either strings, referring to globally-defined options,
 
378
        or option objects.  Retrieve through options().
 
379
 
 
380
    hidden
 
381
        If true, this command isn't advertised.  This is typically
376
382
        for commands intended for expert users.
377
383
 
378
 
    :cvar encoding_type: Command objects will get a 'outf' attribute, which has
379
 
        been setup to properly handle encoding of unicode strings.
380
 
        encoding_type determines what will happen when characters cannot be
381
 
        encoded:
382
 
 
383
 
        * strict - abort if we cannot decode
384
 
        * replace - put in a bogus character (typically '?')
385
 
        * exact - do not encode sys.stdout
386
 
 
387
 
        NOTE: by default on Windows, sys.stdout is opened as a text stream,
388
 
        therefore LF line-endings are converted to CRLF.  When a command uses
389
 
        encoding_type = 'exact', then sys.stdout is forced to be a binary
390
 
        stream, and line-endings will not mangled.
391
 
 
392
 
    :cvar invoked_as:
393
 
        A string indicating the real name under which this command was
394
 
        invoked, before expansion of aliases.
395
 
        (This may be None if the command was constructed and run in-process.)
 
384
    encoding_type
 
385
        Command objects will get a 'outf' attribute, which has been
 
386
        setup to properly handle encoding of unicode strings.
 
387
        encoding_type determines what will happen when characters cannot
 
388
        be encoded
 
389
            strict - abort if we cannot decode
 
390
            replace - put in a bogus character (typically '?')
 
391
            exact - do not encode sys.stdout
 
392
 
 
393
            NOTE: by default on Windows, sys.stdout is opened as a text
 
394
            stream, therefore LF line-endings are converted to CRLF.
 
395
            When a command uses encoding_type = 'exact', then
 
396
            sys.stdout is forced to be a binary stream, and line-endings
 
397
            will not mangled.
396
398
 
397
399
    :cvar hooks: An instance of CommandHooks.
398
 
 
399
 
    :cvar __doc__: The help shown by 'bzr help command' for this command.
400
 
        This is set by assigning explicitly to __doc__ so that -OO can
401
 
        be used::
402
 
 
403
 
            class Foo(Command):
404
 
                __doc__ = "My help goes here"
405
400
    """
406
401
    aliases = []
407
402
    takes_args = []
408
403
    takes_options = []
409
404
    encoding_type = 'strict'
410
 
    invoked_as = None
411
405
 
412
406
    hidden = False
413
407
 
414
408
    def __init__(self):
415
409
        """Construct an instance of this command."""
 
410
        if self.__doc__ == Command.__doc__:
 
411
            warn("No help message set for %r" % self)
416
412
        # List of standard options directly supported
417
413
        self.supported_std_options = []
418
414
        self._setup_run()
486
482
            message explaining how to obtain full help.
487
483
        """
488
484
        doc = self.help()
489
 
        if not doc:
490
 
            doc = "No help for this command."
 
485
        if doc is None:
 
486
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
491
487
 
492
488
        # Extract the summary (purpose) and sections out from the text
493
489
        purpose,sections,order = self._get_help_parts(doc)
513
509
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
514
510
        # 20090319
515
511
        options = option.get_optparser(self.options()).format_option_help()
516
 
        # FIXME: According to the spec, ReST option lists actually don't
517
 
        # support options like --1.14 so that causes syntax errors (in Sphinx
518
 
        # at least).  As that pattern always appears in the commands that
519
 
        # break, we trap on that and then format that block of 'format' options
520
 
        # as a literal block. We use the most recent format still listed so we
521
 
        # don't have to do that too often -- vila 20110514
522
 
        if not plain and options.find('  --1.14  ') != -1:
 
512
        # XXX: According to the spec, ReST option lists actually don't support 
 
513
        # options like --1.9 so that causes syntax errors (in Sphinx at least).
 
514
        # As that pattern always appears in the commands that break, we trap
 
515
        # on that and then format that block of 'format' options as a literal
 
516
        # block.
 
517
        if not plain and options.find('  --1.9  ') != -1:
523
518
            options = options.replace(' format:\n', ' format::\n\n', 1)
524
519
        if options.startswith('Options:'):
525
520
            result += ':' + options
687
682
 
688
683
        self._setup_outf()
689
684
 
690
 
        try:
691
 
            return self.run(**all_cmd_args)
692
 
        finally:
693
 
            # reset it, so that other commands run in the same process won't
694
 
            # inherit state. Before we reset it, log any activity, so that it
695
 
            # gets properly tracked.
696
 
            ui.ui_factory.log_transport_activity(
697
 
                display=('bytes' in debug.debug_flags))
698
 
            trace.set_verbosity_level(0)
 
685
        return self.run(**all_cmd_args)
699
686
 
700
687
    def _setup_run(self):
701
688
        """Wrap the defined run method on self with a cleanup.
752
739
        return getdoc(self)
753
740
 
754
741
    def name(self):
755
 
        """Return the canonical name for this command.
756
 
 
757
 
        The name under which it was actually invoked is available in invoked_as.
758
 
        """
759
742
        return _unsquish_command_name(self.__class__.__name__)
760
743
 
761
744
    def plugin_name(self):
779
762
        These are all empty initially, because by default nothing should get
780
763
        notified.
781
764
        """
782
 
        Hooks.__init__(self, "bzrlib.commands", "Command.hooks")
783
 
        self.add_hook('extend_command',
 
765
        Hooks.__init__(self)
 
766
        self.create_hook(HookPoint('extend_command',
784
767
            "Called after creating a command object to allow modifications "
785
768
            "such as adding or removing options, docs etc. Called with the "
786
 
            "new bzrlib.commands.Command object.", (1, 13))
787
 
        self.add_hook('get_command',
 
769
            "new bzrlib.commands.Command object.", (1, 13), None))
 
770
        self.create_hook(HookPoint('get_command',
788
771
            "Called when creating a single command. Called with "
789
772
            "(cmd_or_None, command_name). get_command should either return "
790
773
            "the cmd_or_None parameter, or a replacement Command object that "
791
774
            "should be used for the command. Note that the Command.hooks "
792
775
            "hooks are core infrastructure. Many users will prefer to use "
793
776
            "bzrlib.commands.register_command or plugin_cmds.register_lazy.",
794
 
            (1, 17))
795
 
        self.add_hook('get_missing_command',
 
777
            (1, 17), None))
 
778
        self.create_hook(HookPoint('get_missing_command',
796
779
            "Called when creating a single command if no command could be "
797
780
            "found. Called with (command_name). get_missing_command should "
798
781
            "either return None, or a Command object to be used for the "
799
 
            "command.", (1, 17))
800
 
        self.add_hook('list_commands',
 
782
            "command.", (1, 17), None))
 
783
        self.create_hook(HookPoint('list_commands',
801
784
            "Called when enumerating commands. Called with a set of "
802
785
            "cmd_name strings for all the commands found so far. This set "
803
786
            " is safe to mutate - e.g. to remove a command. "
804
787
            "list_commands should return the updated set of command names.",
805
 
            (1, 17))
 
788
            (1, 17), None))
806
789
 
807
790
Command.hooks = CommandHooks()
808
791
 
822
805
    else:
823
806
        args = argv
824
807
 
825
 
    # for python 2.5 and later, optparse raises this exception if a non-ascii
826
 
    # option name is given.  See http://bugs.python.org/issue2931
827
 
    try:
828
 
        options, args = parser.parse_args(args)
829
 
    except UnicodeEncodeError,e:
830
 
        raise errors.BzrCommandError('Only ASCII permitted in option names')
831
 
 
 
808
    options, args = parser.parse_args(args)
832
809
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
833
810
                 v is not option.OptionParser.DEFAULT_VALUE])
834
811
    return args, opts
1038
1015
        Specify the number of processes that can be run concurrently (selftest).
1039
1016
    """
1040
1017
    trace.mutter("bazaar version: " + bzrlib.__version__)
1041
 
    argv = _specified_or_unicode_argv(argv)
 
1018
    argv = list(argv)
1042
1019
    trace.mutter("bzr arguments: %r", argv)
1043
1020
 
1044
1021
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
1073
1050
        elif a == '--coverage':
1074
1051
            opt_coverage_dir = argv[i + 1]
1075
1052
            i += 1
1076
 
        elif a == '--profile-imports':
1077
 
            pass # already handled in startup script Bug #588277
1078
1053
        elif a.startswith('-D'):
1079
1054
            debug.debug_flags.add(a[2:])
1080
1055
        else:
1102
1077
    if not opt_no_aliases:
1103
1078
        alias_argv = get_alias(argv[0])
1104
1079
        if alias_argv:
 
1080
            user_encoding = osutils.get_user_encoding()
 
1081
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
1105
1082
            argv[0] = alias_argv.pop(0)
1106
1083
 
1107
1084
    cmd = argv.pop(0)
 
1085
    # We want only 'ascii' command names, but the user may have typed
 
1086
    # in a Unicode name. In that case, they should just get a
 
1087
    # 'command not found' error later.
 
1088
 
1108
1089
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
1109
1090
    run = cmd_obj.run_argv_aliases
1110
1091
    run_argv = [argv, alias_argv]
1184
1165
        new_argv = []
1185
1166
        try:
1186
1167
            # ensure all arguments are unicode strings
1187
 
            for a in argv:
 
1168
            for a in argv[1:]:
1188
1169
                if isinstance(a, unicode):
1189
1170
                    new_argv.append(a)
1190
1171
                else:
1206
1187
 
1207
1188
    :return: exit code of bzr command.
1208
1189
    """
1209
 
    if argv is not None:
1210
 
        argv = argv[1:]
 
1190
    argv = _specified_or_unicode_argv(argv)
1211
1191
    _register_builtin_commands()
1212
1192
    ret = run_bzr_catch_errors(argv)
 
1193
    bzrlib.ui.ui_factory.log_transport_activity(
 
1194
        display=('bytes' in debug.debug_flags))
1213
1195
    trace.mutter("return code %d", ret)
1214
1196
    return ret
1215
1197
 
1268
1250
 
1269
1251
 
1270
1252
class Provider(object):
1271
 
    """Generic class to be overriden by plugins"""
 
1253
    '''Generic class to be overriden by plugins'''
1272
1254
 
1273
1255
    def plugin_for_command(self, cmd_name):
1274
 
        """Takes a command and returns the information for that plugin
 
1256
        '''Takes a command and returns the information for that plugin
1275
1257
 
1276
1258
        :return: A dictionary with all the available information
1277
 
            for the requested plugin
1278
 
        """
 
1259
        for the requested plugin
 
1260
        '''
1279
1261
        raise NotImplementedError
1280
1262
 
1281
1263
 
1282
1264
class ProvidersRegistry(registry.Registry):
1283
 
    """This registry exists to allow other providers to exist"""
 
1265
    '''This registry exists to allow other providers to exist'''
1284
1266
 
1285
1267
    def __iter__(self):
1286
1268
        for key, provider in self.iteritems():