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
17
from __future__ import absolute_import
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
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 (
60
57
class CommandInfo(object):
164
161
return cmd[4:].replace('_','-')
167
@deprecated_function(deprecated_in((2, 2, 0)))
168
def _builtin_commands():
169
"""Return a dict of {name: cmd_class} for builtin commands.
171
:deprecated: Use the builtin_command_registry registry instead
173
# return dict(name: cmd_class)
174
return dict(builtin_command_registry.items())
177
164
def _register_builtin_commands():
178
165
if builtin_command_registry.keys():
240
227
return _get_cmd_object(cmd_name, plugins_override)
242
raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
229
raise errors.BzrCommandError(gettext('unknown command "%s"') % cmd_name)
245
232
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
443
430
self._operation.cleanup_now()
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.
449
Not used anymore, now that the bzr command-line parser globs on
452
:return: A possibly empty list of unicode paths.
454
Introduced in bzrlib 0.18.
458
432
def _usage(self):
459
433
"""Return single-line grammar for this command.
488
462
usage help (e.g. Purpose, Usage, Options) with a
489
463
message explaining how to obtain full help.
491
if self.l10n and not i18n.installed():
492
466
i18n.install() # Install i18n only for get_help_text for now.
493
467
doc = self.help()
577
551
see_also_links.append(item)
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(
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']
689
663
# mix arguments and options into one dictionary
690
664
cmdargs = _match_argform(self.name(), self.takes_args, args)
717
691
class_run = self.run
718
692
def run(*args, **kwargs):
693
for hook in Command.hooks['pre_command']:
719
695
self._operation = cleanup.OperationWithCleanups(class_run)
721
697
return self._operation.run_simple(*args, **kwargs)
723
699
del self._operation
700
for hook in Command.hooks['post_command']:
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)
732
705
"""Actually run the command.
819
792
" is safe to mutate - e.g. to remove a command. "
820
793
"list_commands should return the updated set of command names.",
795
self.add_hook('pre_command',
796
"Called prior to executing a command. Called with the command "
798
self.add_hook('post_command',
799
"Called after executing a command. Called with the command "
823
802
Command.hooks = CommandHooks()
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'))
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] == '+':
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()))
873
854
argdict[argname + '_list'] = 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]
882
864
# just a plain arg
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()))
888
871
argdict[argname] = args.pop(0)
891
raise errors.BzrCommandError("extra argument to command %s: %s"
874
raise errors.BzrCommandError( gettext(
875
"extra argument to command {0}: {1}").format(
951
935
exitcode = trace.report_exception(exc_info, sys.stderr)
952
936
if os.environ.get('BZR_PDB'):
953
937
print '**** entering debugger'
956
if sys.version_info[:2] < (2, 6):
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)
963
# Setup pdb on the traceback
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])
939
pdb.post_mortem(exc_info[2])
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,
983
948
if filename is None:
986
951
stats.save(filename)
987
trace.note('Profile data written to "%s".', filename)
952
trace.note(gettext('Profile data written to "%s".'), filename)
991
@deprecated_function(deprecated_in((2, 2, 0)))
992
def shlex_split_unicode(unsplit):
993
return cmdline.split(unsplit)
996
956
def get_alias(cmd, config=None):
997
957
"""Return an expanded alias, or None if no alias exists.
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:])
1099
1062
argv_copy.append(a)
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()
1070
cmdline_overrides = bzrlib.global_state.cmdline_overrides
1071
cmdline_overrides._from_cmdline(override_config)
1102
1073
debug.set_debug_flags_from_config()
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()
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")