~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 21:28:56 UTC
  • mto: This revision was merged to the branch mainline in revision 6460.
  • Revision ID: jelmer@samba.org-20120127212856-ewnjgn7fyblphcqw
Migrate mail_client to config stacks.

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, 5))
 
798
        self.add_hook('post_command',
 
799
            "Called after executing a command. Called with the command "
 
800
            "object.", (2, 5))
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
 
978
962
 
979
963
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
980
964
    from bzrlib.lsprof import profile
981
 
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
 
965
    ret, stats = profile(exception_to_return_code, the_callable,
 
966
                         *args, **kwargs)
982
967
    stats.sort()
983
968
    if filename is None:
984
969
        stats.pprint()
985
970
    else:
986
971
        stats.save(filename)
987
 
        trace.note('Profile data written to "%s".', filename)
 
972
        trace.note(gettext('Profile data written to "%s".'), filename)
988
973
    return ret
989
974
 
990
975
 
991
 
@deprecated_function(deprecated_in((2, 2, 0)))
992
 
def shlex_split_unicode(unsplit):
993
 
    return cmdline.split(unsplit)
994
 
 
995
 
 
996
976
def get_alias(cmd, config=None):
997
977
    """Return an expanded alias, or None if no alias exists.
998
978
 
1067
1047
 
1068
1048
    argv_copy = []
1069
1049
    i = 0
 
1050
    override_config = []
1070
1051
    while i < len(argv):
1071
1052
        a = argv[i]
1072
1053
        if a == '--profile':
1095
1076
            pass # already handled in startup script Bug #588277
1096
1077
        elif a.startswith('-D'):
1097
1078
            debug.debug_flags.add(a[2:])
 
1079
        elif a.startswith('-O'):
 
1080
            override_config.append(a[2:])
1098
1081
        else:
1099
1082
            argv_copy.append(a)
1100
1083
        i += 1
1101
1084
 
 
1085
    if bzrlib.global_state is None:
 
1086
        # FIXME: Workaround for users that imported bzrlib but didn't call
 
1087
        # bzrlib.initialize -- vila 2012-01-19
 
1088
        cmdline_overrides = config.CommandLineStore()
 
1089
    else:
 
1090
        cmdline_overrides = bzrlib.global_state.cmdline_overrides
 
1091
    cmdline_overrides._from_cmdline(override_config)
 
1092
 
1102
1093
    debug.set_debug_flags_from_config()
1103
1094
 
1104
1095
    if not opt_no_plugins:
1156
1147
        if 'memory' in debug.debug_flags:
1157
1148
            trace.debug_memory('Process status after command:', short=False)
1158
1149
        option._verbosity_level = saved_verbosity_level
 
1150
        # Reset the overrides 
 
1151
        cmdline_overrides._reset()
1159
1152
 
1160
1153
 
1161
1154
def display_command(func):
1190
1183
        "bzr plugin commands")
1191
1184
    Command.hooks.install_named_hook("get_command", _get_external_command,
1192
1185
        "bzr external command lookup")
1193
 
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
1194
 
        "bzr plugin-provider-db check")
 
1186
    Command.hooks.install_named_hook("get_missing_command",
 
1187
                                     _try_plugin_provider,
 
1188
                                     "bzr plugin-provider-db check")
1195
1189
 
1196
1190
 
1197
1191