/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

s/i18n/l10n/

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
27
27
 
28
28
from bzrlib.lazy_import import lazy_import
29
29
lazy_import(globals(), """
30
 
import codecs
31
30
import errno
32
31
import threading
33
 
from warnings import warn
34
32
 
35
33
import bzrlib
36
34
from bzrlib import (
42
40
    osutils,
43
41
    trace,
44
42
    ui,
45
 
    win32utils,
46
43
    )
47
44
""")
48
45
 
49
 
from bzrlib.hooks import HookPoint, Hooks
 
46
from bzrlib.hooks import Hooks
 
47
from bzrlib.i18n import install as i18n_install, gettext
50
48
# Compatibility - Option used to be in commands.
51
49
from bzrlib.option import Option
52
50
from bzrlib.plugin import disable_plugins, load_plugins
222
220
    Use of all_command_names() is encouraged rather than builtin_command_names
223
221
    and/or plugin_command_names.
224
222
    """
 
223
    _register_builtin_commands()
225
224
    return builtin_command_registry.keys()
226
225
 
227
226
 
275
274
    # Allow plugins to extend commands
276
275
    for hook in Command.hooks['extend_command']:
277
276
        hook(cmd)
 
277
    if getattr(cmd, 'invoked_as', None) is None:
 
278
        cmd.invoked_as = cmd_name
278
279
    return cmd
279
280
 
280
281
 
357
358
    summary, then a complete description of the command.  A grammar
358
359
    description will be inserted.
359
360
 
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
 
361
    :cvar aliases: Other accepted names for this command.
 
362
 
 
363
    :cvar takes_args: List of argument forms, marked with whether they are
 
364
        optional, repeated, etc.  Examples::
 
365
 
 
366
            ['to_location', 'from_branch?', 'file*']
 
367
 
 
368
        * 'to_location' is required
 
369
        * 'from_branch' is optional
 
370
        * 'file' can be specified 0 or more times
 
371
 
 
372
    :cvar takes_options: List of options that may be given for this command.
 
373
        These can be either strings, referring to globally-defined options, or
 
374
        option objects.  Retrieve through options().
 
375
 
 
376
    :cvar hidden: If true, this command isn't advertised.  This is typically
382
377
        for commands intended for expert users.
383
378
 
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.
 
379
    :cvar encoding_type: Command objects will get a 'outf' attribute, which has
 
380
        been setup to properly handle encoding of unicode strings.
 
381
        encoding_type determines what will happen when characters cannot be
 
382
        encoded:
 
383
 
 
384
        * strict - abort if we cannot decode
 
385
        * replace - put in a bogus character (typically '?')
 
386
        * exact - do not encode sys.stdout
 
387
 
 
388
        NOTE: by default on Windows, sys.stdout is opened as a text stream,
 
389
        therefore LF line-endings are converted to CRLF.  When a command uses
 
390
        encoding_type = 'exact', then sys.stdout is forced to be a binary
 
391
        stream, and line-endings will not mangled.
 
392
 
 
393
    :cvar invoked_as:
 
394
        A string indicating the real name under which this command was
 
395
        invoked, before expansion of aliases.
 
396
        (This may be None if the command was constructed and run in-process.)
398
397
 
399
398
    :cvar hooks: An instance of CommandHooks.
 
399
 
 
400
    :cvar __doc__: The help shown by 'bzr help command' for this command.
 
401
        This is set by assigning explicitly to __doc__ so that -OO can
 
402
        be used::
 
403
 
 
404
            class Foo(Command):
 
405
                __doc__ = "My help goes here"
400
406
    """
401
407
    aliases = []
402
408
    takes_args = []
403
409
    takes_options = []
404
410
    encoding_type = 'strict'
 
411
    invoked_as = None
405
412
 
406
413
    hidden = False
407
414
 
408
415
    def __init__(self):
409
416
        """Construct an instance of this command."""
410
 
        if self.__doc__ == Command.__doc__:
411
 
            warn("No help message set for %r" % self)
412
417
        # List of standard options directly supported
413
418
        self.supported_std_options = []
414
419
        self._setup_run()
482
487
            message explaining how to obtain full help.
483
488
        """
484
489
        doc = self.help()
485
 
        if doc is None:
486
 
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
 
490
        if doc:
 
491
            # Note: If cmd_gettext translates ':Usage:\n', the section will
 
492
            # be shown after "Description" section.
 
493
            doc = self.gettext(doc)
 
494
        else:
 
495
            doc = gettext("No help for this command.")
487
496
 
488
497
        # Extract the summary (purpose) and sections out from the text
489
498
        purpose,sections,order = self._get_help_parts(doc)
496
505
 
497
506
        # The header is the purpose and usage
498
507
        result = ""
499
 
        result += ':Purpose: %s\n' % purpose
 
508
        result += gettext(':Purpose: %s') % (purpose,) + '\n'
500
509
        if usage.find('\n') >= 0:
501
 
            result += ':Usage:\n%s\n' % usage
 
510
            result += gettext(':Usage:\n%s') % (usage,) + '\n'
502
511
        else:
503
 
            result += ':Usage:   %s\n' % usage
 
512
            result += gettext(':Usage:   %s') % (usage,) + '\n'
504
513
        result += '\n'
505
514
 
506
515
        # Add the options
508
517
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
509
518
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
510
519
        # 20090319
511
 
        options = option.get_optparser(self.options()).format_option_help()
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:
 
520
        parser = option.get_optparser(self.options(), True)
 
521
        options = parser.format_option_help()
 
522
        # FIXME: According to the spec, ReST option lists actually don't
 
523
        # support options like --1.14 so that causes syntax errors (in Sphinx
 
524
        # at least).  As that pattern always appears in the commands that
 
525
        # break, we trap on that and then format that block of 'format' options
 
526
        # as a literal block. We use the most recent format still listed so we
 
527
        # don't have to do that too often -- vila 20110514
 
528
        if not plain and options.find('  --1.14  ') != -1:
518
529
            options = options.replace(' format:\n', ' format::\n\n', 1)
519
530
        if options.startswith('Options:'):
520
 
            result += ':' + options
521
 
        elif options.startswith('options:'):
522
 
            # Python 2.4 version of optparse
523
 
            result += ':Options:' + options[len('options:'):]
 
531
            result += gettext(':Options:%s') % (options[len('options:'):],)
524
532
        else:
525
533
            result += options
526
534
        result += '\n'
531
539
            if sections.has_key(None):
532
540
                text = sections.pop(None)
533
541
                text = '\n  '.join(text.splitlines())
534
 
                result += ':%s:\n  %s\n\n' % ('Description',text)
 
542
                result += gettext(':Description:\n  %s') % (text,) + '\n\n'
535
543
 
536
544
            # Add the custom sections (e.g. Examples). Note that there's no need
537
545
            # to indent these as they must be indented already in the source.
538
546
            if sections:
539
547
                for label in order:
540
 
                    if sections.has_key(label):
541
 
                        result += ':%s:\n%s\n' % (label,sections[label])
 
548
                    if label in sections:
 
549
                        result += ':%s:\n%s\n' % (label, sections[label])
542
550
                result += '\n'
543
551
        else:
544
 
            result += ("See bzr help %s for more details and examples.\n\n"
 
552
            result += (gettext("See bzr help %s for more details and examples.\n\n")
545
553
                % self.name())
546
554
 
547
555
        # Add the aliases, source (plug-in) and see also links, if any
548
556
        if self.aliases:
549
 
            result += ':Aliases:  '
 
557
            result += gettext(':Aliases:  ')
550
558
            result += ', '.join(self.aliases) + '\n'
551
559
        plugin_name = self.plugin_name()
552
560
        if plugin_name is not None:
553
 
            result += ':From:     plugin "%s"\n' % plugin_name
 
561
            result += gettext(':From:     plugin "%s"\n') % plugin_name
554
562
        see_also = self.get_see_also(additional_see_also)
555
563
        if see_also:
556
564
            if not plain and see_also_as_links:
562
570
                        see_also_links.append(item)
563
571
                    else:
564
572
                        # Use a Sphinx link for this entry
565
 
                        link_text = ":doc:`%s <%s-help>`" % (item, item)
 
573
                        link_text = gettext(":doc:`%s <%s-help>`") % (item, item)
566
574
                        see_also_links.append(link_text)
567
575
                see_also = see_also_links
568
 
            result += ':See also: '
569
 
            result += ', '.join(see_also) + '\n'
 
576
            result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
570
577
 
571
578
        # If this will be rendered as plain text, convert it
572
579
        if plain:
656
663
 
657
664
        # Process the standard options
658
665
        if 'help' in opts:  # e.g. bzr add --help
659
 
            sys.stdout.write(self.get_help_text())
 
666
            self._setup_outf()
 
667
            self.outf.write(self.get_help_text())
660
668
            return 0
661
669
        if 'usage' in opts:  # e.g. bzr add --usage
662
 
            sys.stdout.write(self.get_help_text(verbose=False))
 
670
            self._setup_outf()
 
671
            self.outf.write(self.get_help_text(verbose=False))
663
672
            return 0
664
673
        trace.set_verbosity_level(option._verbosity_level)
665
674
        if 'verbose' in self.supported_std_options:
682
691
 
683
692
        self._setup_outf()
684
693
 
685
 
        return self.run(**all_cmd_args)
 
694
        try:
 
695
            return self.run(**all_cmd_args)
 
696
        finally:
 
697
            # reset it, so that other commands run in the same process won't
 
698
            # inherit state. Before we reset it, log any activity, so that it
 
699
            # gets properly tracked.
 
700
            ui.ui_factory.log_transport_activity(
 
701
                display=('bytes' in debug.debug_flags))
 
702
            trace.set_verbosity_level(0)
686
703
 
687
704
    def _setup_run(self):
688
705
        """Wrap the defined run method on self with a cleanup.
738
755
            return None
739
756
        return getdoc(self)
740
757
 
 
758
    @property
 
759
    def gettext(self):
 
760
        """Returns the gettext function used to translate this command's help.
 
761
 
 
762
        Commands provided by plugins should override this to use their
 
763
        own i18n system.
 
764
        """
 
765
        import bzrlib.i18n
 
766
        return bzrlib.i18n.gettext_per_paragraph
 
767
 
741
768
    def name(self):
 
769
        """Return the canonical name for this command.
 
770
 
 
771
        The name under which it was actually invoked is available in invoked_as.
 
772
        """
742
773
        return _unsquish_command_name(self.__class__.__name__)
743
774
 
744
775
    def plugin_name(self):
762
793
        These are all empty initially, because by default nothing should get
763
794
        notified.
764
795
        """
765
 
        Hooks.__init__(self)
766
 
        self.create_hook(HookPoint('extend_command',
 
796
        Hooks.__init__(self, "bzrlib.commands", "Command.hooks")
 
797
        self.add_hook('extend_command',
767
798
            "Called after creating a command object to allow modifications "
768
799
            "such as adding or removing options, docs etc. Called with the "
769
 
            "new bzrlib.commands.Command object.", (1, 13), None))
770
 
        self.create_hook(HookPoint('get_command',
 
800
            "new bzrlib.commands.Command object.", (1, 13))
 
801
        self.add_hook('get_command',
771
802
            "Called when creating a single command. Called with "
772
803
            "(cmd_or_None, command_name). get_command should either return "
773
804
            "the cmd_or_None parameter, or a replacement Command object that "
774
805
            "should be used for the command. Note that the Command.hooks "
775
806
            "hooks are core infrastructure. Many users will prefer to use "
776
807
            "bzrlib.commands.register_command or plugin_cmds.register_lazy.",
777
 
            (1, 17), None))
778
 
        self.create_hook(HookPoint('get_missing_command',
 
808
            (1, 17))
 
809
        self.add_hook('get_missing_command',
779
810
            "Called when creating a single command if no command could be "
780
811
            "found. Called with (command_name). get_missing_command should "
781
812
            "either return None, or a Command object to be used for the "
782
 
            "command.", (1, 17), None))
783
 
        self.create_hook(HookPoint('list_commands',
 
813
            "command.", (1, 17))
 
814
        self.add_hook('list_commands',
784
815
            "Called when enumerating commands. Called with a set of "
785
816
            "cmd_name strings for all the commands found so far. This set "
786
817
            " is safe to mutate - e.g. to remove a command. "
787
818
            "list_commands should return the updated set of command names.",
788
 
            (1, 17), None))
 
819
            (1, 17))
789
820
 
790
821
Command.hooks = CommandHooks()
791
822
 
805
836
    else:
806
837
        args = argv
807
838
 
808
 
    options, args = parser.parse_args(args)
 
839
    # for python 2.5 and later, optparse raises this exception if a non-ascii
 
840
    # option name is given.  See http://bugs.python.org/issue2931
 
841
    try:
 
842
        options, args = parser.parse_args(args)
 
843
    except UnicodeEncodeError,e:
 
844
        raise errors.BzrCommandError('Only ASCII permitted in option names')
 
845
 
809
846
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
810
847
                 v is not option.OptionParser.DEFAULT_VALUE])
811
848
    return args, opts
1015
1052
        Specify the number of processes that can be run concurrently (selftest).
1016
1053
    """
1017
1054
    trace.mutter("bazaar version: " + bzrlib.__version__)
1018
 
    argv = list(argv)
 
1055
    argv = _specified_or_unicode_argv(argv)
1019
1056
    trace.mutter("bzr arguments: %r", argv)
1020
1057
 
1021
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
1022
 
                opt_no_aliases = False
 
1058
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
 
1059
            opt_no_l10n = opt_no_aliases = False
1023
1060
    opt_lsprof_file = opt_coverage_dir = None
1024
1061
 
1025
1062
    # --no-plugins is handled specially at a very early stage. We need
1042
1079
            opt_no_plugins = True
1043
1080
        elif a == '--no-aliases':
1044
1081
            opt_no_aliases = True
 
1082
        elif a == '--no-l10n':
 
1083
            opt_no_l10n = True
1045
1084
        elif a == '--builtin':
1046
1085
            opt_builtin = True
1047
1086
        elif a == '--concurrency':
1050
1089
        elif a == '--coverage':
1051
1090
            opt_coverage_dir = argv[i + 1]
1052
1091
            i += 1
 
1092
        elif a == '--profile-imports':
 
1093
            pass # already handled in startup script Bug #588277
1053
1094
        elif a.startswith('-D'):
1054
1095
            debug.debug_flags.add(a[2:])
1055
1096
        else:
1057
1098
        i += 1
1058
1099
 
1059
1100
    debug.set_debug_flags_from_config()
 
1101
    if not opt_no_l10n:
 
1102
        # selftest uninstalls i18n later.
 
1103
        i18n_install()
1060
1104
 
1061
1105
    if not opt_no_plugins:
1062
1106
        load_plugins()
1077
1121
    if not opt_no_aliases:
1078
1122
        alias_argv = get_alias(argv[0])
1079
1123
        if alias_argv:
1080
 
            user_encoding = osutils.get_user_encoding()
1081
 
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
1082
1124
            argv[0] = alias_argv.pop(0)
1083
1125
 
1084
1126
    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
 
 
1089
1127
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
1090
1128
    run = cmd_obj.run_argv_aliases
1091
1129
    run_argv = [argv, alias_argv]
1165
1203
        new_argv = []
1166
1204
        try:
1167
1205
            # ensure all arguments are unicode strings
1168
 
            for a in argv[1:]:
 
1206
            for a in argv:
1169
1207
                if isinstance(a, unicode):
1170
1208
                    new_argv.append(a)
1171
1209
                else:
1187
1225
 
1188
1226
    :return: exit code of bzr command.
1189
1227
    """
1190
 
    argv = _specified_or_unicode_argv(argv)
 
1228
    if argv is not None:
 
1229
        argv = argv[1:]
1191
1230
    _register_builtin_commands()
1192
1231
    ret = run_bzr_catch_errors(argv)
1193
 
    bzrlib.ui.ui_factory.log_transport_activity(
1194
 
        display=('bytes' in debug.debug_flags))
1195
1232
    trace.mutter("return code %d", ret)
1196
1233
    return ret
1197
1234
 
1250
1287
 
1251
1288
 
1252
1289
class Provider(object):
1253
 
    '''Generic class to be overriden by plugins'''
 
1290
    """Generic class to be overriden by plugins"""
1254
1291
 
1255
1292
    def plugin_for_command(self, cmd_name):
1256
 
        '''Takes a command and returns the information for that plugin
 
1293
        """Takes a command and returns the information for that plugin
1257
1294
 
1258
1295
        :return: A dictionary with all the available information
1259
 
        for the requested plugin
1260
 
        '''
 
1296
            for the requested plugin
 
1297
        """
1261
1298
        raise NotImplementedError
1262
1299
 
1263
1300
 
1264
1301
class ProvidersRegistry(registry.Registry):
1265
 
    '''This registry exists to allow other providers to exist'''
 
1302
    """This registry exists to allow other providers to exist"""
1266
1303
 
1267
1304
    def __iter__(self):
1268
1305
        for key, provider in self.iteritems():