~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

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
32
33
 
33
34
import bzrlib
34
35
from bzrlib import (
 
36
    config,
35
37
    cleanup,
36
38
    cmdline,
37
39
    debug,
50
52
from bzrlib.option import Option
51
53
from bzrlib.plugin import disable_plugins, load_plugins
52
54
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):
164
161
    return cmd[4:].replace('_','-')
165
162
 
166
163
 
167
 
@deprecated_function(deprecated_in((2, 2, 0)))
168
 
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
164
def _register_builtin_commands():
178
165
    if builtin_command_registry.keys():
179
166
        # only load once
239
226
    try:
240
227
        return _get_cmd_object(cmd_name, plugins_override)
241
228
    except KeyError:
242
 
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
 
229
        raise errors.BzrCommandError(gettext('unknown command "%s"') % cmd_name)
243
230
 
244
231
 
245
232
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
442
429
        """
443
430
        self._operation.cleanup_now()
444
431
 
445
 
    @deprecated_method(deprecated_in((2, 1, 0)))
446
 
    def _maybe_expand_globs(self, file_list):
447
 
        """Glob expand file_list if the platform does not do that itself.
448
 
 
449
 
        Not used anymore, now that the bzr command-line parser globs on
450
 
        Windows.
451
 
 
452
 
        :return: A possibly empty list of unicode paths.
453
 
 
454
 
        Introduced in bzrlib 0.18.
455
 
        """
456
 
        return file_list
457
 
 
458
432
    def _usage(self):
459
433
        """Return single-line grammar for this command.
460
434
 
488
462
            usage help (e.g. Purpose, Usage, Options) with a
489
463
            message explaining how to obtain full help.
490
464
        """
491
 
        if self.l10n and not i18n.installed():
 
465
        if self.l10n:
492
466
            i18n.install()  # Install i18n only for get_help_text for now.
493
467
        doc = self.help()
494
468
        if doc:
577
551
                        see_also_links.append(item)
578
552
                    else:
579
553
                        # Use a Sphinx link for this entry
580
 
                        link_text = gettext(":doc:`%s <%s-help>`") % (item, item)
 
554
                        link_text = gettext(":doc:`{0} <{1}-help>`").format(
 
555
                                                                    item, item)
581
556
                        see_also_links.append(link_text)
582
557
                see_also = see_also_links
583
558
            result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
685
660
            opts['quiet'] = trace.is_quiet()
686
661
        elif opts.has_key('quiet'):
687
662
            del opts['quiet']
688
 
 
689
663
        # mix arguments and options into one dictionary
690
664
        cmdargs = _match_argform(self.name(), self.takes_args, args)
691
665
        cmdopts = {}
716
690
        """
717
691
        class_run = self.run
718
692
        def run(*args, **kwargs):
 
693
            for hook in Command.hooks['pre_command']:
 
694
                hook(self)
719
695
            self._operation = cleanup.OperationWithCleanups(class_run)
720
696
            try:
721
697
                return self._operation.run_simple(*args, **kwargs)
722
698
            finally:
723
699
                del self._operation
 
700
                for hook in Command.hooks['post_command']:
 
701
                    hook(self)
724
702
        self.run = run
725
703
 
726
 
    @deprecated_method(deprecated_in((2, 2, 0)))
727
 
    def run_direct(self, *args, **kwargs):
728
 
        """Deprecated thunk from bzrlib 2.1."""
729
 
        return self.run(*args, **kwargs)
730
 
 
731
704
    def run(self):
732
705
        """Actually run the command.
733
706
 
819
792
            " is safe to mutate - e.g. to remove a command. "
820
793
            "list_commands should return the updated set of command names.",
821
794
            (1, 17))
 
795
        self.add_hook('pre_command',
 
796
            "Called prior to executing a command. Called with the command "
 
797
            "object.", (2, 6))
 
798
        self.add_hook('post_command',
 
799
            "Called after executing a command. Called with the command "
 
800
            "object.", (2, 6))
822
801
 
823
802
Command.hooks = CommandHooks()
824
803
 
843
822
    try:
844
823
        options, args = parser.parse_args(args)
845
824
    except UnicodeEncodeError,e:
846
 
        raise errors.BzrCommandError('Only ASCII permitted in option names')
 
825
        raise errors.BzrCommandError(
 
826
            gettext('Only ASCII permitted in option names'))
847
827
 
848
828
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
849
829
                 v is not option.OptionParser.DEFAULT_VALUE])
867
847
                argdict[argname + '_list'] = None
868
848
        elif ap[-1] == '+':
869
849
            if not args:
870
 
                raise errors.BzrCommandError("command %r needs one or more %s"
871
 
                                             % (cmd, argname.upper()))
 
850
                raise errors.BzrCommandError(gettext(
 
851
                      "command {0!r} needs one or more {1}").format(
 
852
                      cmd, argname.upper()))
872
853
            else:
873
854
                argdict[argname + '_list'] = args[:]
874
855
                args = []
875
856
        elif ap[-1] == '$': # all but one
876
857
            if len(args) < 2:
877
 
                raise errors.BzrCommandError("command %r needs one or more %s"
878
 
                                             % (cmd, argname.upper()))
 
858
                raise errors.BzrCommandError(
 
859
                      gettext("command {0!r} needs one or more {1}").format(
 
860
                                             cmd, argname.upper()))
879
861
            argdict[argname + '_list'] = args[:-1]
880
862
            args[:-1] = []
881
863
        else:
882
864
            # just a plain arg
883
865
            argname = ap
884
866
            if not args:
885
 
                raise errors.BzrCommandError("command %r requires argument %s"
886
 
                               % (cmd, argname.upper()))
 
867
                raise errors.BzrCommandError(
 
868
                     gettext("command {0!r} requires argument {1}").format(
 
869
                               cmd, argname.upper()))
887
870
            else:
888
871
                argdict[argname] = args.pop(0)
889
872
 
890
873
    if args:
891
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
892
 
                                     % (cmd, args[0]))
 
874
        raise errors.BzrCommandError( gettext(
 
875
                              "extra argument to command {0}: {1}").format(
 
876
                                       cmd, args[0]) )
893
877
 
894
878
    return argdict
895
879
 
951
935
        exitcode = trace.report_exception(exc_info, sys.stderr)
952
936
        if os.environ.get('BZR_PDB'):
953
937
            print '**** entering debugger'
954
 
            tb = exc_info[2]
955
938
            import pdb
956
 
            if sys.version_info[:2] < (2, 6):
957
 
                # XXX: we want to do
958
 
                #    pdb.post_mortem(tb)
959
 
                # but because pdb.post_mortem gives bad results for tracebacks
960
 
                # from inside generators, we do it manually.
961
 
                # (http://bugs.python.org/issue4150, fixed in Python 2.6)
962
 
 
963
 
                # Setup pdb on the traceback
964
 
                p = pdb.Pdb()
965
 
                p.reset()
966
 
                p.setup(tb.tb_frame, tb)
967
 
                # Point the debugger at the deepest frame of the stack
968
 
                p.curindex = len(p.stack) - 1
969
 
                p.curframe = p.stack[p.curindex][0]
970
 
                # Start the pdb prompt.
971
 
                p.print_stack_entry(p.stack[p.curindex])
972
 
                p.execRcLines()
973
 
                p.cmdloop()
974
 
            else:
975
 
                pdb.post_mortem(tb)
 
939
            pdb.post_mortem(exc_info[2])
976
940
        return exitcode
977
941
 
978
942
 
979
943
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
980
944
    from bzrlib.lsprof import profile
981
 
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
 
945
    ret, stats = profile(exception_to_return_code, the_callable,
 
946
                         *args, **kwargs)
982
947
    stats.sort()
983
948
    if filename is None:
984
949
        stats.pprint()
985
950
    else:
986
951
        stats.save(filename)
987
 
        trace.note('Profile data written to "%s".', filename)
 
952
        trace.note(gettext('Profile data written to "%s".'), filename)
988
953
    return ret
989
954
 
990
955
 
991
 
@deprecated_function(deprecated_in((2, 2, 0)))
992
 
def shlex_split_unicode(unsplit):
993
 
    return cmdline.split(unsplit)
994
 
 
995
 
 
996
956
def get_alias(cmd, config=None):
997
957
    """Return an expanded alias, or None if no alias exists.
998
958
 
1067
1027
 
1068
1028
    argv_copy = []
1069
1029
    i = 0
 
1030
    override_config = []
1070
1031
    while i < len(argv):
1071
1032
        a = argv[i]
1072
1033
        if a == '--profile':
1095
1056
            pass # already handled in startup script Bug #588277
1096
1057
        elif a.startswith('-D'):
1097
1058
            debug.debug_flags.add(a[2:])
 
1059
        elif a.startswith('-O'):
 
1060
            override_config.append(a[2:])
1098
1061
        else:
1099
1062
            argv_copy.append(a)
1100
1063
        i += 1
1101
1064
 
 
1065
    if bzrlib.global_state is None:
 
1066
        # FIXME: Workaround for users that imported bzrlib but didn't call
 
1067
        # bzrlib.initialize -- vila 2012-01-19
 
1068
        cmdline_overrides = config.CommandLineStore()
 
1069
    else:
 
1070
        cmdline_overrides = bzrlib.global_state.cmdline_overrides
 
1071
    cmdline_overrides._from_cmdline(override_config)
 
1072
 
1102
1073
    debug.set_debug_flags_from_config()
1103
1074
 
1104
1075
    if not opt_no_plugins:
1156
1127
        if 'memory' in debug.debug_flags:
1157
1128
            trace.debug_memory('Process status after command:', short=False)
1158
1129
        option._verbosity_level = saved_verbosity_level
 
1130
        # Reset the overrides 
 
1131
        cmdline_overrides._reset()
1159
1132
 
1160
1133
 
1161
1134
def display_command(func):
1190
1163
        "bzr plugin commands")
1191
1164
    Command.hooks.install_named_hook("get_command", _get_external_command,
1192
1165
        "bzr external command lookup")
1193
 
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
1194
 
        "bzr plugin-provider-db check")
 
1166
    Command.hooks.install_named_hook("get_missing_command",
 
1167
                                     _try_plugin_provider,
 
1168
                                     "bzr plugin-provider-db check")
1195
1169
 
1196
1170
 
1197
1171