~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

(gz) Remove bzrlib/util/elementtree/ package (Martin Packman)

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
17
18
 
18
19
# TODO: Define arguments by objects, rather than just using names.
19
20
# Those objects can specify the expected type of the argument, which
36
37
    cmdline,
37
38
    debug,
38
39
    errors,
 
40
    i18n,
39
41
    option,
40
42
    osutils,
41
43
    trace,
44
46
""")
45
47
 
46
48
from bzrlib.hooks import Hooks
 
49
from bzrlib.i18n import gettext
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
50
53
from bzrlib import registry
51
 
from bzrlib.symbol_versioning import (
52
 
    deprecated_function,
53
 
    deprecated_in,
54
 
    deprecated_method,
55
 
    )
56
54
 
57
55
 
58
56
class CommandInfo(object):
162
160
    return cmd[4:].replace('_','-')
163
161
 
164
162
 
165
 
@deprecated_function(deprecated_in((2, 2, 0)))
166
 
def _builtin_commands():
167
 
    """Return a dict of {name: cmd_class} for builtin commands.
168
 
 
169
 
    :deprecated: Use the builtin_command_registry registry instead
170
 
    """
171
 
    # return dict(name: cmd_class)
172
 
    return dict(builtin_command_registry.items())
173
 
 
174
 
 
175
163
def _register_builtin_commands():
176
164
    if builtin_command_registry.keys():
177
165
        # only load once
237
225
    try:
238
226
        return _get_cmd_object(cmd_name, plugins_override)
239
227
    except KeyError:
240
 
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
 
228
        raise errors.BzrCommandError(gettext('unknown command "%s"') % cmd_name)
241
229
 
242
230
 
243
231
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
408
396
    takes_options = []
409
397
    encoding_type = 'strict'
410
398
    invoked_as = None
 
399
    l10n = True
411
400
 
412
401
    hidden = False
413
402
 
439
428
        """
440
429
        self._operation.cleanup_now()
441
430
 
442
 
    @deprecated_method(deprecated_in((2, 1, 0)))
443
 
    def _maybe_expand_globs(self, file_list):
444
 
        """Glob expand file_list if the platform does not do that itself.
445
 
 
446
 
        Not used anymore, now that the bzr command-line parser globs on
447
 
        Windows.
448
 
 
449
 
        :return: A possibly empty list of unicode paths.
450
 
 
451
 
        Introduced in bzrlib 0.18.
452
 
        """
453
 
        return file_list
454
 
 
455
431
    def _usage(self):
456
432
        """Return single-line grammar for this command.
457
433
 
485
461
            usage help (e.g. Purpose, Usage, Options) with a
486
462
            message explaining how to obtain full help.
487
463
        """
 
464
        if self.l10n:
 
465
            i18n.install()  # Install i18n only for get_help_text for now.
488
466
        doc = self.help()
489
 
        if not doc:
490
 
            doc = "No help for this command."
 
467
        if doc:
 
468
            # Note: If self.gettext() translates ':Usage:\n', the section will
 
469
            # be shown after "Description" section and we don't want to
 
470
            # translate the usage string.
 
471
            # Though, bzr export-pot don't exports :Usage: section and it must
 
472
            # not be translated.
 
473
            doc = self.gettext(doc)
 
474
        else:
 
475
            doc = gettext("No help for this command.")
491
476
 
492
477
        # Extract the summary (purpose) and sections out from the text
493
478
        purpose,sections,order = self._get_help_parts(doc)
500
485
 
501
486
        # The header is the purpose and usage
502
487
        result = ""
503
 
        result += ':Purpose: %s\n' % purpose
 
488
        result += gettext(':Purpose: %s\n') % (purpose,)
504
489
        if usage.find('\n') >= 0:
505
 
            result += ':Usage:\n%s\n' % usage
 
490
            result += gettext(':Usage:\n%s\n') % (usage,)
506
491
        else:
507
 
            result += ':Usage:   %s\n' % usage
 
492
            result += gettext(':Usage:   %s\n') % (usage,)
508
493
        result += '\n'
509
494
 
510
495
        # Add the options
512
497
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
513
498
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
514
499
        # 20090319
515
 
        options = option.get_optparser(self.options()).format_option_help()
 
500
        parser = option.get_optparser(self.options())
 
501
        options = parser.format_option_help()
516
502
        # FIXME: According to the spec, ReST option lists actually don't
517
503
        # support options like --1.14 so that causes syntax errors (in Sphinx
518
504
        # at least).  As that pattern always appears in the commands that
522
508
        if not plain and options.find('  --1.14  ') != -1:
523
509
            options = options.replace(' format:\n', ' format::\n\n', 1)
524
510
        if options.startswith('Options:'):
525
 
            result += ':' + options
526
 
        elif options.startswith('options:'):
527
 
            # Python 2.4 version of optparse
528
 
            result += ':Options:' + options[len('options:'):]
 
511
            result += gettext(':Options:%s') % (options[len('options:'):],)
529
512
        else:
530
513
            result += options
531
514
        result += '\n'
536
519
            if sections.has_key(None):
537
520
                text = sections.pop(None)
538
521
                text = '\n  '.join(text.splitlines())
539
 
                result += ':%s:\n  %s\n\n' % ('Description',text)
 
522
                result += gettext(':Description:\n  %s\n\n') % (text,)
540
523
 
541
524
            # Add the custom sections (e.g. Examples). Note that there's no need
542
525
            # to indent these as they must be indented already in the source.
543
526
            if sections:
544
527
                for label in order:
545
 
                    if sections.has_key(label):
546
 
                        result += ':%s:\n%s\n' % (label,sections[label])
 
528
                    if label in sections:
 
529
                        result += ':%s:\n%s\n' % (label, sections[label])
547
530
                result += '\n'
548
531
        else:
549
 
            result += ("See bzr help %s for more details and examples.\n\n"
 
532
            result += (gettext("See bzr help %s for more details and examples.\n\n")
550
533
                % self.name())
551
534
 
552
535
        # Add the aliases, source (plug-in) and see also links, if any
553
536
        if self.aliases:
554
 
            result += ':Aliases:  '
 
537
            result += gettext(':Aliases:  ')
555
538
            result += ', '.join(self.aliases) + '\n'
556
539
        plugin_name = self.plugin_name()
557
540
        if plugin_name is not None:
558
 
            result += ':From:     plugin "%s"\n' % plugin_name
 
541
            result += gettext(':From:     plugin "%s"\n') % plugin_name
559
542
        see_also = self.get_see_also(additional_see_also)
560
543
        if see_also:
561
544
            if not plain and see_also_as_links:
567
550
                        see_also_links.append(item)
568
551
                    else:
569
552
                        # Use a Sphinx link for this entry
570
 
                        link_text = ":doc:`%s <%s-help>`" % (item, item)
 
553
                        link_text = gettext(":doc:`{0} <{1}-help>`").format(
 
554
                                                                    item, item)
571
555
                        see_also_links.append(link_text)
572
556
                see_also = see_also_links
573
 
            result += ':See also: '
574
 
            result += ', '.join(see_also) + '\n'
 
557
            result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
575
558
 
576
559
        # If this will be rendered as plain text, convert it
577
560
        if plain:
658
641
    def run_argv_aliases(self, argv, alias_argv=None):
659
642
        """Parse the command line and run with extra aliases in alias_argv."""
660
643
        args, opts = parse_args(self, argv, alias_argv)
 
644
        self._setup_outf()
661
645
 
662
646
        # Process the standard options
663
647
        if 'help' in opts:  # e.g. bzr add --help
664
 
            sys.stdout.write(self.get_help_text())
 
648
            self.outf.write(self.get_help_text())
665
649
            return 0
666
650
        if 'usage' in opts:  # e.g. bzr add --usage
667
 
            sys.stdout.write(self.get_help_text(verbose=False))
 
651
            self.outf.write(self.get_help_text(verbose=False))
668
652
            return 0
669
653
        trace.set_verbosity_level(option._verbosity_level)
670
654
        if 'verbose' in self.supported_std_options:
675
659
            opts['quiet'] = trace.is_quiet()
676
660
        elif opts.has_key('quiet'):
677
661
            del opts['quiet']
678
 
 
679
662
        # mix arguments and options into one dictionary
680
663
        cmdargs = _match_argform(self.name(), self.takes_args, args)
681
664
        cmdopts = {}
685
668
        all_cmd_args = cmdargs.copy()
686
669
        all_cmd_args.update(cmdopts)
687
670
 
688
 
        self._setup_outf()
689
 
 
690
671
        try:
691
672
            return self.run(**all_cmd_args)
692
673
        finally:
715
696
                del self._operation
716
697
        self.run = run
717
698
 
718
 
    @deprecated_method(deprecated_in((2, 2, 0)))
719
 
    def run_direct(self, *args, **kwargs):
720
 
        """Deprecated thunk from bzrlib 2.1."""
721
 
        return self.run(*args, **kwargs)
722
 
 
723
699
    def run(self):
724
700
        """Actually run the command.
725
701
 
751
727
            return None
752
728
        return getdoc(self)
753
729
 
 
730
    def gettext(self, message):
 
731
        """Returns the gettext function used to translate this command's help.
 
732
 
 
733
        Commands provided by plugins should override this to use their
 
734
        own i18n system.
 
735
        """
 
736
        return i18n.gettext_per_paragraph(message)
 
737
 
754
738
    def name(self):
755
739
        """Return the canonical name for this command.
756
740
 
827
811
    try:
828
812
        options, args = parser.parse_args(args)
829
813
    except UnicodeEncodeError,e:
830
 
        raise errors.BzrCommandError('Only ASCII permitted in option names')
 
814
        raise errors.BzrCommandError(
 
815
            gettext('Only ASCII permitted in option names'))
831
816
 
832
817
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
833
818
                 v is not option.OptionParser.DEFAULT_VALUE])
851
836
                argdict[argname + '_list'] = None
852
837
        elif ap[-1] == '+':
853
838
            if not args:
854
 
                raise errors.BzrCommandError("command %r needs one or more %s"
855
 
                                             % (cmd, argname.upper()))
 
839
                raise errors.BzrCommandError(gettext(
 
840
                      "command {0!r} needs one or more {1}").format(
 
841
                      cmd, argname.upper()))
856
842
            else:
857
843
                argdict[argname + '_list'] = args[:]
858
844
                args = []
859
845
        elif ap[-1] == '$': # all but one
860
846
            if len(args) < 2:
861
 
                raise errors.BzrCommandError("command %r needs one or more %s"
862
 
                                             % (cmd, argname.upper()))
 
847
                raise errors.BzrCommandError(
 
848
                      gettext("command {0!r} needs one or more {1}").format(
 
849
                                             cmd, argname.upper()))
863
850
            argdict[argname + '_list'] = args[:-1]
864
851
            args[:-1] = []
865
852
        else:
866
853
            # just a plain arg
867
854
            argname = ap
868
855
            if not args:
869
 
                raise errors.BzrCommandError("command %r requires argument %s"
870
 
                               % (cmd, argname.upper()))
 
856
                raise errors.BzrCommandError(
 
857
                     gettext("command {0!r} requires argument {1}").format(
 
858
                               cmd, argname.upper()))
871
859
            else:
872
860
                argdict[argname] = args.pop(0)
873
861
 
874
862
    if args:
875
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
876
 
                                     % (cmd, args[0]))
 
863
        raise errors.BzrCommandError( gettext(
 
864
                              "extra argument to command {0}: {1}").format(
 
865
                                       cmd, args[0]) )
877
866
 
878
867
    return argdict
879
868
 
962
951
 
963
952
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
964
953
    from bzrlib.lsprof import profile
965
 
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
 
954
    ret, stats = profile(exception_to_return_code, the_callable,
 
955
                         *args, **kwargs)
966
956
    stats.sort()
967
957
    if filename is None:
968
958
        stats.pprint()
969
959
    else:
970
960
        stats.save(filename)
971
 
        trace.note('Profile data written to "%s".', filename)
 
961
        trace.note(gettext('Profile data written to "%s".'), filename)
972
962
    return ret
973
963
 
974
964
 
975
 
@deprecated_function(deprecated_in((2, 2, 0)))
976
 
def shlex_split_unicode(unsplit):
977
 
    return cmdline.split(unsplit)
978
 
 
979
 
 
980
965
def get_alias(cmd, config=None):
981
966
    """Return an expanded alias, or None if no alias exists.
982
967
 
1041
1026
    argv = _specified_or_unicode_argv(argv)
1042
1027
    trace.mutter("bzr arguments: %r", argv)
1043
1028
 
1044
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
1045
 
                opt_no_aliases = False
 
1029
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
 
1030
            opt_no_l10n = opt_no_aliases = False
1046
1031
    opt_lsprof_file = opt_coverage_dir = None
1047
1032
 
1048
1033
    # --no-plugins is handled specially at a very early stage. We need
1051
1036
 
1052
1037
    argv_copy = []
1053
1038
    i = 0
 
1039
    override_config = []
1054
1040
    while i < len(argv):
1055
1041
        a = argv[i]
1056
1042
        if a == '--profile':
1065
1051
            opt_no_plugins = True
1066
1052
        elif a == '--no-aliases':
1067
1053
            opt_no_aliases = True
 
1054
        elif a == '--no-l10n':
 
1055
            opt_no_l10n = True
1068
1056
        elif a == '--builtin':
1069
1057
            opt_builtin = True
1070
1058
        elif a == '--concurrency':
1077
1065
            pass # already handled in startup script Bug #588277
1078
1066
        elif a.startswith('-D'):
1079
1067
            debug.debug_flags.add(a[2:])
 
1068
        elif a.startswith('-O'):
 
1069
            override_config.append(a[2:])
1080
1070
        else:
1081
1071
            argv_copy.append(a)
1082
1072
        i += 1
1083
1073
 
 
1074
    bzrlib.global_state.cmdline_overrides._from_cmdline(override_config)
 
1075
 
1084
1076
    debug.set_debug_flags_from_config()
1085
1077
 
1086
1078
    if not opt_no_plugins:
1106
1098
 
1107
1099
    cmd = argv.pop(0)
1108
1100
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
 
1101
    if opt_no_l10n:
 
1102
        cmd.l10n = False
1109
1103
    run = cmd_obj.run_argv_aliases
1110
1104
    run_argv = [argv, alias_argv]
1111
1105
 
1136
1130
        if 'memory' in debug.debug_flags:
1137
1131
            trace.debug_memory('Process status after command:', short=False)
1138
1132
        option._verbosity_level = saved_verbosity_level
 
1133
        # Reset the overrides 
 
1134
        bzrlib.global_state.cmdline_overrides._reset()
1139
1135
 
1140
1136
 
1141
1137
def display_command(func):
1170
1166
        "bzr plugin commands")
1171
1167
    Command.hooks.install_named_hook("get_command", _get_external_command,
1172
1168
        "bzr external command lookup")
1173
 
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
1174
 
        "bzr plugin-provider-db check")
 
1169
    Command.hooks.install_named_hook("get_missing_command",
 
1170
                                     _try_plugin_provider,
 
1171
                                     "bzr plugin-provider-db check")
1175
1172
 
1176
1173
 
1177
1174