164
130
return cmd[4:].replace('_','-')
167
@deprecated_function(deprecated_in((2, 2, 0)))
168
133
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
def _register_builtin_commands():
178
if builtin_command_registry.keys():
181
134
import bzrlib.builtins
182
for cmd_class in _scan_module_for_commands(bzrlib.builtins).values():
183
builtin_command_registry.register(cmd_class)
184
bzrlib.builtins._register_lazy_builtins()
187
def _scan_module_for_commands(module):
189
for name, obj in module.__dict__.iteritems():
136
builtins = bzrlib.builtins.__dict__
137
for name in builtins:
190
138
if name.startswith("cmd_"):
191
139
real_name = _unsquish_command_name(name)
140
r[real_name] = builtins[name]
196
def _list_bzr_commands(names):
197
"""Find commands from bzr's core and plugins.
199
This is not the public interface, just the default hook called by all_command_names.
201
# to eliminate duplicates
202
names.update(builtin_command_names())
203
names.update(plugin_command_names())
207
def all_command_names():
208
"""Return a set of all command names."""
210
for hook in Command.hooks['list_commands']:
213
raise AssertionError(
214
'hook %s returned None' % Command.hooks.get_hook_name(hook))
218
144
def builtin_command_names():
219
"""Return list of builtin command names.
221
Use of all_command_names() is encouraged rather than builtin_command_names
222
and/or plugin_command_names.
224
_register_builtin_commands()
225
return builtin_command_registry.keys()
145
"""Return list of builtin command names."""
146
return _builtin_commands().keys()
228
149
def plugin_command_names():
229
"""Returns command names from commands registered by plugins."""
230
150
return plugin_cmds.keys()
153
def _get_cmd_dict(plugins_override=True):
154
"""Return name->class mapping for all commands."""
155
d = _builtin_commands()
157
d.update(plugin_cmds.iteritems())
161
def get_all_cmds(plugins_override=True):
162
"""Return canonical name and class for all registered commands."""
163
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
233
167
def get_cmd_object(cmd_name, plugins_override=True):
234
"""Return the command object for a command.
168
"""Return the canonical name and command class for a command.
237
171
If true, plugin commands can override builtins.
240
return _get_cmd_object(cmd_name, plugins_override)
174
cmd = _get_cmd_object(cmd_name, plugins_override)
175
# Allow plugins to extend commands
176
for hook in Command.hooks['extend_command']:
242
180
raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
245
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
246
"""Get a command object.
183
def _get_cmd_object(cmd_name, plugins_override=True):
184
"""Worker for get_cmd_object which raises KeyError rather than BzrCommandError."""
185
from bzrlib.externalcommand import ExternalCommand
248
:param cmd_name: The name of the command.
249
:param plugins_override: Allow plugins to override builtins.
250
:param check_missing: Look up commands not found in the regular index via
251
the get_missing_command hook.
252
:return: A Command object instance
253
:raises KeyError: If no command is found.
255
187
# We want only 'ascii' command names, but the user may have typed
256
188
# in a Unicode name. In that case, they should just get a
257
189
# 'command not found' error later.
258
190
# In the future, we may actually support Unicode command names.
261
for hook in Command.hooks['get_command']:
262
cmd = hook(cmd, cmd_name)
263
if cmd is not None and not plugins_override and not cmd.plugin_name():
264
# We've found a non-plugin command, don't permit it to be
267
if cmd is None and check_missing:
268
for hook in Command.hooks['get_missing_command']:
275
# Allow plugins to extend commands
276
for hook in Command.hooks['extend_command']:
278
if getattr(cmd, 'invoked_as', None) is None:
279
cmd.invoked_as = cmd_name
283
def _try_plugin_provider(cmd_name):
284
"""Probe for a plugin provider having cmd_name."""
286
plugin_metadata, provider = probe_for_provider(cmd_name)
287
raise errors.CommandAvailableInPlugin(cmd_name,
288
plugin_metadata, provider)
289
except errors.NoPluginAvailable:
293
def probe_for_provider(cmd_name):
294
"""Look for a provider for cmd_name.
296
:param cmd_name: The command name.
297
:return: plugin_metadata, provider for getting cmd_name.
298
:raises NoPluginAvailable: When no provider can supply the plugin.
300
# look for providers that provide this command but aren't installed
301
for provider in command_providers_registry:
192
# first look up this command under the specified name
303
return provider.plugin_for_command(cmd_name), provider
304
except errors.NoPluginAvailable:
195
return plugin_cmds.get(cmd_name)()
306
raise errors.NoPluginAvailable(cmd_name)
309
def _get_bzr_command(cmd_or_None, cmd_name):
310
"""Get a command from bzr's core."""
198
cmds = _get_cmd_dict(plugins_override=False)
312
cmd_class = builtin_command_registry.get(cmd_name)
200
return cmds[cmd_name]()
320
def _get_external_command(cmd_or_None, cmd_name):
321
"""Lookup a command that is a shell script."""
322
# Only do external command lookups when no command is found so far.
323
if cmd_or_None is not None:
325
from bzrlib.externalcommand import ExternalCommand
204
for key in plugin_cmds.keys():
205
info = plugin_cmds.get_info(key)
206
if cmd_name in info.aliases:
207
return plugin_cmds.get(key)()
208
# look for any command which claims this as an alias
209
for real_cmd_name, cmd_class in cmds.iteritems():
210
if cmd_name in cmd_class.aliases:
326
213
cmd_obj = ExternalCommand.find_command(cmd_name)
331
def _get_plugin_command(cmd_or_None, cmd_name):
332
"""Get a command from bzr's plugins."""
334
return plugin_cmds.get(cmd_name)()
337
for key in plugin_cmds.keys():
338
info = plugin_cmds.get_info(key)
339
if cmd_name in info.aliases:
340
return plugin_cmds.get(key)()
217
# look for plugins that provide this command but aren't installed
218
for provider in command_providers_registry:
220
plugin_metadata = provider.plugin_for_command(cmd_name)
221
except errors.NoPluginAvailable:
224
raise errors.CommandAvailableInPlugin(cmd_name,
225
plugin_metadata, provider)
344
229
class Command(object):
359
244
summary, then a complete description of the command. A grammar
360
245
description will be inserted.
362
:cvar aliases: Other accepted names for this command.
364
:cvar takes_args: List of argument forms, marked with whether they are
365
optional, repeated, etc. Examples::
367
['to_location', 'from_branch?', 'file*']
369
* 'to_location' is required
370
* 'from_branch' is optional
371
* 'file' can be specified 0 or more times
373
:cvar takes_options: List of options that may be given for this command.
374
These can be either strings, referring to globally-defined options, or
375
option objects. Retrieve through options().
377
:cvar hidden: If true, this command isn't advertised. This is typically
248
Other accepted names for this command.
251
List of argument forms, marked with whether they are optional,
256
['to_location', 'from_branch?', 'file*']
258
'to_location' is required
259
'from_branch' is optional
260
'file' can be specified 0 or more times
263
List of options that may be given for this command. These can
264
be either strings, referring to globally-defined options,
265
or option objects. Retrieve through options().
268
If true, this command isn't advertised. This is typically
378
269
for commands intended for expert users.
380
:cvar encoding_type: Command objects will get a 'outf' attribute, which has
381
been setup to properly handle encoding of unicode strings.
382
encoding_type determines what will happen when characters cannot be
385
* strict - abort if we cannot decode
386
* replace - put in a bogus character (typically '?')
387
* exact - do not encode sys.stdout
389
NOTE: by default on Windows, sys.stdout is opened as a text stream,
390
therefore LF line-endings are converted to CRLF. When a command uses
391
encoding_type = 'exact', then sys.stdout is forced to be a binary
392
stream, and line-endings will not mangled.
395
A string indicating the real name under which this command was
396
invoked, before expansion of aliases.
397
(This may be None if the command was constructed and run in-process.)
272
Command objects will get a 'outf' attribute, which has been
273
setup to properly handle encoding of unicode strings.
274
encoding_type determines what will happen when characters cannot
276
strict - abort if we cannot decode
277
replace - put in a bogus character (typically '?')
278
exact - do not encode sys.stdout
280
NOTE: by default on Windows, sys.stdout is opened as a text
281
stream, therefore LF line-endings are converted to CRLF.
282
When a command uses encoding_type = 'exact', then
283
sys.stdout is forced to be a binary stream, and line-endings
399
286
:cvar hooks: An instance of CommandHooks.
401
:cvar __doc__: The help shown by 'bzr help command' for this command.
402
This is set by assigning explicitly to __doc__ so that -OO can
406
__doc__ = "My help goes here"
410
290
takes_options = []
411
291
encoding_type = 'strict'
417
295
def __init__(self):
418
296
"""Construct an instance of this command."""
297
if self.__doc__ == Command.__doc__:
298
warn("No help message set for %r" % self)
419
299
# List of standard options directly supported
420
300
self.supported_std_options = []
423
def add_cleanup(self, cleanup_func, *args, **kwargs):
424
"""Register a function to call after self.run returns or raises.
426
Functions will be called in LIFO order.
428
self._operation.add_cleanup(cleanup_func, *args, **kwargs)
430
def cleanup_now(self):
431
"""Execute and empty pending cleanup functions immediately.
433
After cleanup_now all registered cleanups are forgotten. add_cleanup
434
may be called again after cleanup_now; these cleanups will be called
435
after self.run returns or raises (or when cleanup_now is next called).
437
This is useful for releasing expensive or contentious resources (such
438
as write locks) before doing further work that does not require those
439
resources (such as writing results to self.outf). Note though, that
440
as it releases all resources, this may release locks that the command
441
wants to hold, so use should be done with care.
443
self._operation.cleanup_now()
445
@deprecated_method(deprecated_in((2, 1, 0)))
446
302
def _maybe_expand_globs(self, file_list):
447
303
"""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
305
:return: A possibly empty list of unicode paths.
454
307
Introduced in bzrlib 0.18.
311
if sys.platform == 'win32':
312
file_list = win32utils.glob_expand(file_list)
313
return list(file_list)
458
315
def _usage(self):
459
316
"""Return single-line grammar for this command.
513
361
# The header is the purpose and usage
515
result += gettext(':Purpose: %s\n') % (purpose,)
363
result += ':Purpose: %s\n' % purpose
516
364
if usage.find('\n') >= 0:
517
result += gettext(':Usage:\n%s\n') % (usage,)
365
result += ':Usage:\n%s\n' % usage
519
result += gettext(':Usage: %s\n') % (usage,)
367
result += ':Usage: %s\n' % usage
522
370
# Add the options
524
# XXX: optparse implicitly rewraps the help, and not always perfectly,
525
# so we get <https://bugs.launchpad.net/bzr/+bug/249908>. -- mbp
527
parser = option.get_optparser(self.options())
528
options = parser.format_option_help()
529
# FIXME: According to the spec, ReST option lists actually don't
530
# support options like --1.14 so that causes syntax errors (in Sphinx
531
# at least). As that pattern always appears in the commands that
532
# break, we trap on that and then format that block of 'format' options
533
# as a literal block. We use the most recent format still listed so we
534
# don't have to do that too often -- vila 20110514
535
if not plain and options.find(' --1.14 ') != -1:
536
options = options.replace(' format:\n', ' format::\n\n', 1)
371
options = option.get_optparser(self.options()).format_option_help()
537
372
if options.startswith('Options:'):
538
result += gettext(':Options:%s') % (options[len('options:'):],)
373
result += ':' + options
374
elif options.startswith('options:'):
375
# Python 2.4 version of optparse
376
result += ':Options:' + options[len('options:'):]
540
378
result += options
662
500
def _setup_outf(self):
663
501
"""Return a file linked to stdout, which has proper encoding."""
664
self.outf = ui.ui_factory.make_output_stream(
665
encoding_type=self.encoding_type)
502
# Originally I was using self.stdout, but that looks
503
# *way* too much like sys.stdout
504
if self.encoding_type == 'exact':
505
# force sys.stdout to be binary stream on win32
506
if sys.platform == 'win32':
507
fileno = getattr(sys.stdout, 'fileno', None)
510
msvcrt.setmode(fileno(), os.O_BINARY)
511
self.outf = sys.stdout
514
output_encoding = osutils.get_terminal_encoding()
516
self.outf = codecs.getwriter(output_encoding)(sys.stdout,
517
errors=self.encoding_type)
518
# For whatever reason codecs.getwriter() does not advertise its encoding
519
# it just returns the encoding of the wrapped file, which is completely
520
# bogus. So set the attribute, so we can find the correct encoding later.
521
self.outf.encoding = output_encoding
667
523
def run_argv_aliases(self, argv, alias_argv=None):
668
524
"""Parse the command line and run with extra aliases in alias_argv."""
526
warn("Passing None for [] is deprecated from bzrlib 0.10",
527
DeprecationWarning, stacklevel=2)
669
529
args, opts = parse_args(self, argv, alias_argv)
672
531
# Process the standard options
673
532
if 'help' in opts: # e.g. bzr add --help
674
self.outf.write(self.get_help_text())
533
sys.stdout.write(self.get_help_text())
676
535
if 'usage' in opts: # e.g. bzr add --usage
677
self.outf.write(self.get_help_text(verbose=False))
536
sys.stdout.write(self.get_help_text(verbose=False))
679
538
trace.set_verbosity_level(option._verbosity_level)
680
539
if 'verbose' in self.supported_std_options:
695
554
all_cmd_args = cmdargs.copy()
696
555
all_cmd_args.update(cmdopts)
699
return self.run(**all_cmd_args)
701
# reset it, so that other commands run in the same process won't
702
# inherit state. Before we reset it, log any activity, so that it
703
# gets properly tracked.
704
ui.ui_factory.log_transport_activity(
705
display=('bytes' in debug.debug_flags))
706
trace.set_verbosity_level(0)
708
def _setup_run(self):
709
"""Wrap the defined run method on self with a cleanup.
711
This is called by __init__ to make the Command be able to be run
712
by just calling run(), as it could be before cleanups were added.
714
If a different form of cleanups are in use by your Command subclass,
715
you can override this method.
718
def run(*args, **kwargs):
719
self._operation = cleanup.OperationWithCleanups(class_run)
721
return self._operation.run_simple(*args, **kwargs)
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)
559
return self.run(**all_cmd_args)
732
562
"""Actually run the command.
795
602
These are all empty initially, because by default nothing should get
798
Hooks.__init__(self, "bzrlib.commands", "Command.hooks")
799
self.add_hook('extend_command',
606
self.create_hook(HookPoint('extend_command',
800
607
"Called after creating a command object to allow modifications "
801
608
"such as adding or removing options, docs etc. Called with the "
802
"new bzrlib.commands.Command object.", (1, 13))
803
self.add_hook('get_command',
804
"Called when creating a single command. Called with "
805
"(cmd_or_None, command_name). get_command should either return "
806
"the cmd_or_None parameter, or a replacement Command object that "
807
"should be used for the command. Note that the Command.hooks "
808
"hooks are core infrastructure. Many users will prefer to use "
809
"bzrlib.commands.register_command or plugin_cmds.register_lazy.",
811
self.add_hook('get_missing_command',
812
"Called when creating a single command if no command could be "
813
"found. Called with (command_name). get_missing_command should "
814
"either return None, or a Command object to be used for the "
816
self.add_hook('list_commands',
817
"Called when enumerating commands. Called with a set of "
818
"cmd_name strings for all the commands found so far. This set "
819
" is safe to mutate - e.g. to remove a command. "
820
"list_commands should return the updated set of command names.",
609
"new bzrlib.commands.Command object.", (1, 13), None))
823
611
Command.hooks = CommandHooks()
1008
789
config = bzrlib.config.GlobalConfig()
1009
790
alias = config.get_alias(cmd)
1011
return cmdline.split(alias)
792
return shlex_split_unicode(alias)
1015
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
1016
797
"""Execute a command.
1018
:param argv: The command-line arguments, without the program name from
1019
argv[0] These should already be decoded. All library/test code calling
1020
run_bzr should be passing valid strings (don't need decoding).
1021
:param load_plugins: What function to call when triggering plugin loading.
1022
This function should take no arguments and cause all plugins to be
1024
:param disable_plugins: What function to call when disabling plugin
1025
loading. This function should take no arguments and cause all plugin
1026
loading to be prohibited (so that code paths in your application that
1027
know about some plugins possibly being present will fail to import
1028
those plugins even if they are installed.)
1029
:return: Returns a command exit code or raises an exception.
800
The command-line arguments, without the program name from argv[0]
801
These should already be decoded. All library/test code calling
802
run_bzr should be passing valid strings (don't need decoding).
804
Returns a command status or raises an exception.
1031
806
Special master options: these must come before the command because
1032
807
they control how the command is interpreted.
1178
950
return ignore_pipe
1181
def install_bzr_command_hooks():
1182
"""Install the hooks to supply bzr's own commands."""
1183
if _list_bzr_commands in Command.hooks["list_commands"]:
1185
Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
1187
Command.hooks.install_named_hook("get_command", _get_bzr_command,
1189
Command.hooks.install_named_hook("get_command", _get_plugin_command,
1190
"bzr plugin commands")
1191
Command.hooks.install_named_hook("get_command", _get_external_command,
1192
"bzr external command lookup")
1193
Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
1194
"bzr plugin-provider-db check")
1198
def _specified_or_unicode_argv(argv):
1199
# For internal or testing use, argv can be passed. Otherwise, get it from
1200
# the process arguments in a unicode-safe way.
1202
return osutils.get_unicode_argv()
1206
# ensure all arguments are unicode strings
1208
if isinstance(a, unicode):
1211
new_argv.append(a.decode('ascii'))
1212
except UnicodeDecodeError:
1213
raise errors.BzrError("argv should be list of unicode strings.")
1217
def main(argv=None):
1218
"""Main entry point of command-line interface.
1220
Typically `bzrlib.initialize` should be called first.
1222
:param argv: list of unicode command-line arguments similar to sys.argv.
1223
argv[0] is script name usually, it will be ignored.
1224
Don't pass here sys.argv because this list contains plain strings
1225
and not unicode; pass None instead.
1227
:return: exit code of bzr command.
1229
if argv is not None:
1231
_register_builtin_commands()
955
bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
956
sys.stdin, sys.stdout, sys.stderr)
958
# Is this a final release version? If so, we should suppress warnings
959
if bzrlib.version_info[3] == 'final':
960
from bzrlib import symbol_versioning
961
symbol_versioning.suppress_deprecation_warnings(override=False)
963
user_encoding = osutils.get_user_encoding()
964
argv = [a.decode(user_encoding) for a in argv[1:]]
965
except UnicodeDecodeError:
966
raise errors.BzrError(("Parameter '%r' is unsupported by the current "
1232
968
ret = run_bzr_catch_errors(argv)
1233
969
trace.mutter("return code %d", ret)