1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
19
# TODO: Define arguments by objects, rather than just using names.
20
# Those objects can specify the expected type of the argument, which
21
# would help with validation and shell completion. They could also provide
22
# help/explanation for that argument in a structured way.
24
# TODO: Specific "examples" property on commands for consistent formatting.
36
from .lazy_import import lazy_import
37
lazy_import(globals(), """
49
from .hooks import Hooks
50
from .i18n import gettext
51
# Compatibility - Option used to be in commands.
52
from .option import Option
53
from .plugin import disable_plugins, load_plugins, plugin_name
54
from . import errors, registry
57
class BzrOptionError(errors.BzrCommandError):
59
_fmt = "Error in command line options"
62
class CommandAvailableInPlugin(Exception):
64
internal_error = False
66
def __init__(self, cmd_name, plugin_metadata, provider):
68
self.plugin_metadata = plugin_metadata
69
self.cmd_name = cmd_name
70
self.provider = provider
74
_fmt = ('"%s" is not a standard brz command. \n'
75
'However, the following official plugin provides this command: %s\n'
76
'You can install it by going to: %s'
77
% (self.cmd_name, self.plugin_metadata['name'],
78
self.plugin_metadata['url']))
83
class CommandInfo(object):
84
"""Information about a command."""
86
def __init__(self, aliases):
87
"""The list of aliases for the command."""
88
self.aliases = aliases
91
def from_command(klass, command):
92
"""Factory to construct a CommandInfo from a command."""
93
return klass(command.aliases)
96
class CommandRegistry(registry.Registry):
97
"""Special registry mapping command names to command classes.
99
:ivar overridden_registry: Look in this registry for commands being
100
overridden by this registry. This can be used to tell plugin commands
101
about the builtin they're decorating.
105
registry.Registry.__init__(self)
106
self.overridden_registry = None
107
# map from aliases to the real command that implements the name
108
self._alias_dict = {}
110
def get(self, command_name):
111
real_name = self._alias_dict.get(command_name, command_name)
112
return registry.Registry.get(self, real_name)
115
def _get_name(command_name):
116
if command_name.startswith("cmd_"):
117
return _unsquish_command_name(command_name)
121
def register(self, cmd, decorate=False):
122
"""Utility function to help register a command
124
:param cmd: Command subclass to register
125
:param decorate: If true, allow overriding an existing command
126
of the same name; the old command is returned by this function.
127
Otherwise it is an error to try to override an existing command.
130
k_unsquished = self._get_name(k)
132
previous = self.get(k_unsquished)
135
if self.overridden_registry:
137
previous = self.overridden_registry.get(k_unsquished)
140
info = CommandInfo.from_command(cmd)
142
registry.Registry.register(self, k_unsquished, cmd,
143
override_existing=decorate, info=info)
145
trace.warning('Two plugins defined the same command: %r' % k)
146
trace.warning('Not loading the one in %r' %
147
sys.modules[cmd.__module__])
148
trace.warning('Previously this command was registered from %r' %
149
sys.modules[previous.__module__])
150
for a in cmd.aliases:
151
self._alias_dict[a] = k_unsquished
154
def register_lazy(self, command_name, aliases, module_name):
155
"""Register a command without loading its module.
157
:param command_name: The primary name of the command.
158
:param aliases: A list of aliases for the command.
159
:module_name: The module that the command lives in.
161
key = self._get_name(command_name)
162
registry.Registry.register_lazy(self, key, module_name, command_name,
163
info=CommandInfo(aliases))
165
self._alias_dict[a] = key
168
plugin_cmds = CommandRegistry()
169
builtin_command_registry = CommandRegistry()
170
plugin_cmds.overridden_registry = builtin_command_registry
173
def register_command(cmd, decorate=False):
174
"""Register a plugin command.
176
Should generally be avoided in favor of lazy registration.
179
return plugin_cmds.register(cmd, decorate)
182
def _squish_command_name(cmd):
183
return 'cmd_' + cmd.replace('-', '_')
186
def _unsquish_command_name(cmd):
187
return cmd[4:].replace('_', '-')
190
def _register_builtin_commands():
191
if builtin_command_registry.keys():
194
import breezy.builtins
195
for cmd_class in _scan_module_for_commands(breezy.builtins):
196
builtin_command_registry.register(cmd_class)
197
breezy.builtins._register_lazy_builtins()
200
def _scan_module_for_commands(module):
201
module_dict = module.__dict__
202
for name in module_dict:
203
if name.startswith("cmd_"):
204
yield module_dict[name]
207
def _list_bzr_commands(names):
208
"""Find commands from bzr's core and plugins.
210
This is not the public interface, just the default hook called by
213
# to eliminate duplicates
214
names.update(builtin_command_names())
215
names.update(plugin_command_names())
219
def all_command_names():
220
"""Return a set of all command names."""
222
for hook in Command.hooks['list_commands']:
225
raise AssertionError(
226
'hook %s returned None' % Command.hooks.get_hook_name(hook))
230
def builtin_command_names():
231
"""Return list of builtin command names.
233
Use of all_command_names() is encouraged rather than builtin_command_names
234
and/or plugin_command_names.
236
_register_builtin_commands()
237
return builtin_command_registry.keys()
240
def plugin_command_names():
241
"""Returns command names from commands registered by plugins."""
242
return plugin_cmds.keys()
245
# Overrides for common mispellings that heuristics get wrong
247
'ic': {'ci': 0}, # heuristic finds nick
251
def guess_command(cmd_name):
252
"""Guess what command a user typoed.
254
:param cmd_name: Command to search for
255
:return: None if no command was found, name of a command otherwise
258
for name in all_command_names():
260
cmd = get_cmd_object(name)
261
names.update(cmd.aliases)
262
# candidate: modified levenshtein distance against cmd_name.
265
for name in sorted(names):
266
matcher = patiencediff.PatienceSequenceMatcher(None, cmd_name, name)
268
opcodes = matcher.get_opcodes()
269
for opcode, l1, l2, r1, r2 in opcodes:
270
if opcode == 'delete':
272
elif opcode == 'replace':
273
distance += max(l2 - l1, r2 - l1)
274
elif opcode == 'insert':
276
elif opcode == 'equal':
277
# Score equal ranges lower, making similar commands of equal
278
# length closer than arbitrary same length commands.
279
distance -= 0.1 * (l2 - l1)
280
costs[name] = distance
281
costs.update(_GUESS_OVERRIDES.get(cmd_name, {}))
282
costs = sorted((costs[key], key) for key in costs)
287
candidate = costs[0][1]
291
def get_cmd_object(cmd_name, plugins_override=True):
292
"""Return the command object for a command.
295
If true, plugin commands can override builtins.
298
return _get_cmd_object(cmd_name, plugins_override)
300
# No command found, see if this was a typo
301
candidate = guess_command(cmd_name)
302
if candidate is not None:
303
raise errors.BzrCommandError(
304
gettext('unknown command "%s". Perhaps you meant "%s"')
305
% (cmd_name, candidate))
306
raise errors.BzrCommandError(gettext('unknown command "%s"')
310
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
311
"""Get a command object.
313
:param cmd_name: The name of the command.
314
:param plugins_override: Allow plugins to override builtins.
315
:param check_missing: Look up commands not found in the regular index via
316
the get_missing_command hook.
317
:return: A Command object instance
318
:raises KeyError: If no command is found.
320
# We want only 'ascii' command names, but the user may have typed
321
# in a Unicode name. In that case, they should just get a
322
# 'command not found' error later.
323
# In the future, we may actually support Unicode command names.
326
for hook in Command.hooks['get_command']:
327
cmd = hook(cmd, cmd_name)
328
if cmd is not None and not plugins_override and not cmd.plugin_name():
329
# We've found a non-plugin command, don't permit it to be
332
if cmd is None and check_missing:
333
for hook in Command.hooks['get_missing_command']:
340
# Allow plugins to extend commands
341
for hook in Command.hooks['extend_command']:
343
if getattr(cmd, 'invoked_as', None) is None:
344
cmd.invoked_as = cmd_name
348
class NoPluginAvailable(errors.BzrError):
352
def _try_plugin_provider(cmd_name):
353
"""Probe for a plugin provider having cmd_name."""
355
plugin_metadata, provider = probe_for_provider(cmd_name)
356
raise CommandAvailableInPlugin(cmd_name, plugin_metadata, provider)
357
except NoPluginAvailable:
361
def probe_for_provider(cmd_name):
362
"""Look for a provider for cmd_name.
364
:param cmd_name: The command name.
365
:return: plugin_metadata, provider for getting cmd_name.
366
:raises NoPluginAvailable: When no provider can supply the plugin.
368
# look for providers that provide this command but aren't installed
369
for provider in command_providers_registry:
371
return provider.plugin_for_command(cmd_name), provider
372
except NoPluginAvailable:
374
raise NoPluginAvailable(cmd_name)
377
def _get_bzr_command(cmd_or_None, cmd_name):
378
"""Get a command from bzr's core."""
380
cmd_class = builtin_command_registry.get(cmd_name)
388
def _get_external_command(cmd_or_None, cmd_name):
389
"""Lookup a command that is a shell script."""
390
# Only do external command lookups when no command is found so far.
391
if cmd_or_None is not None:
393
from breezy.externalcommand import ExternalCommand
394
cmd_obj = ExternalCommand.find_command(cmd_name)
399
def _get_plugin_command(cmd_or_None, cmd_name):
400
"""Get a command from brz's plugins."""
402
return plugin_cmds.get(cmd_name)()
405
for key in plugin_cmds.keys():
406
info = plugin_cmds.get_info(key)
407
if cmd_name in info.aliases:
408
return plugin_cmds.get(key)()
412
class Command(object):
413
"""Base class for commands.
415
Commands are the heart of the command-line brz interface.
417
The command object mostly handles the mapping of command-line
418
parameters into one or more breezy operations, and of the results
421
Commands normally don't have any state. All their arguments are
422
passed in to the run method. (Subclasses may take a different
423
policy if the behaviour of the instance needs to depend on e.g. a
424
shell plugin and not just its Python class.)
426
The docstring for an actual command should give a single-line
427
summary, then a complete description of the command. A grammar
428
description will be inserted.
430
:cvar aliases: Other accepted names for this command.
432
:cvar takes_args: List of argument forms, marked with whether they are
433
optional, repeated, etc. Examples::
435
['to_location', 'from_branch?', 'file*']
437
* 'to_location' is required
438
* 'from_branch' is optional
439
* 'file' can be specified 0 or more times
441
:cvar takes_options: List of options that may be given for this command.
442
These can be either strings, referring to globally-defined options, or
443
option objects. Retrieve through options().
445
:cvar hidden: If true, this command isn't advertised. This is typically
446
for commands intended for expert users.
448
:cvar encoding_type: Command objects will get a 'outf' attribute, which has
449
been setup to properly handle encoding of unicode strings.
450
encoding_type determines what will happen when characters cannot be
453
* strict - abort if we cannot decode
454
* replace - put in a bogus character (typically '?')
455
* exact - do not encode sys.stdout
457
NOTE: by default on Windows, sys.stdout is opened as a text stream,
458
therefore LF line-endings are converted to CRLF. When a command uses
459
encoding_type = 'exact', then sys.stdout is forced to be a binary
460
stream, and line-endings will not mangled.
463
A string indicating the real name under which this command was
464
invoked, before expansion of aliases.
465
(This may be None if the command was constructed and run in-process.)
467
:cvar hooks: An instance of CommandHooks.
469
:cvar __doc__: The help shown by 'brz help command' for this command.
470
This is set by assigning explicitly to __doc__ so that -OO can
474
__doc__ = "My help goes here"
479
encoding_type = 'strict'
486
"""Construct an instance of this command."""
487
# List of standard options directly supported
488
self.supported_std_options = []
491
def add_cleanup(self, cleanup_func, *args, **kwargs):
492
"""Register a function to call after self.run returns or raises.
494
Functions will be called in LIFO order.
496
self._exit_stack.callback(cleanup_func, *args, **kwargs)
498
def cleanup_now(self):
499
"""Execute and empty pending cleanup functions immediately.
501
After cleanup_now all registered cleanups are forgotten. add_cleanup
502
may be called again after cleanup_now; these cleanups will be called
503
after self.run returns or raises (or when cleanup_now is next called).
505
This is useful for releasing expensive or contentious resources (such
506
as write locks) before doing further work that does not require those
507
resources (such as writing results to self.outf). Note though, that
508
as it releases all resources, this may release locks that the command
509
wants to hold, so use should be done with care.
511
self._exit_stack.close()
513
def enter_context(self, cm):
514
return self._exit_stack.enter_context(cm)
517
"""Return single-line grammar for this command.
519
Only describes arguments, not options.
521
s = 'brz ' + self.name() + ' '
522
for aname in self.takes_args:
523
aname = aname.upper()
524
if aname[-1] in ['$', '+']:
525
aname = aname[:-1] + '...'
526
elif aname[-1] == '?':
527
aname = '[' + aname[:-1] + ']'
528
elif aname[-1] == '*':
529
aname = '[' + aname[:-1] + '...]'
531
s = s[:-1] # remove last space
534
def get_help_text(self, additional_see_also=None, plain=True,
535
see_also_as_links=False, verbose=True):
536
"""Return a text string with help for this command.
538
:param additional_see_also: Additional help topics to be
540
:param plain: if False, raw help (reStructuredText) is
541
returned instead of plain text.
542
:param see_also_as_links: if True, convert items in 'See also'
543
list to internal links (used by bzr_man rstx generator)
544
:param verbose: if True, display the full help, otherwise
545
leave out the descriptive sections and just display
546
usage help (e.g. Purpose, Usage, Options) with a
547
message explaining how to obtain full help.
550
i18n.install() # Install i18n only for get_help_text for now.
553
# Note: If self.gettext() translates ':Usage:\n', the section will
554
# be shown after "Description" section and we don't want to
555
# translate the usage string.
556
# Though, brz export-pot don't exports :Usage: section and it must
558
doc = self.gettext(doc)
560
doc = gettext("No help for this command.")
562
# Extract the summary (purpose) and sections out from the text
563
purpose, sections, order = self._get_help_parts(doc)
565
# If a custom usage section was provided, use it
566
if 'Usage' in sections:
567
usage = sections.pop('Usage')
569
usage = self._usage()
571
# The header is the purpose and usage
573
result += gettext(':Purpose: %s\n') % (purpose,)
574
if usage.find('\n') >= 0:
575
result += gettext(':Usage:\n%s\n') % (usage,)
577
result += gettext(':Usage: %s\n') % (usage,)
582
# XXX: optparse implicitly rewraps the help, and not always perfectly,
583
# so we get <https://bugs.launchpad.net/bzr/+bug/249908>. -- mbp
585
parser = option.get_optparser(
586
[v for k, v in sorted(self.options().items())])
587
options = parser.format_option_help()
588
# FIXME: According to the spec, ReST option lists actually don't
589
# support options like --1.14 so that causes syntax errors (in Sphinx
590
# at least). As that pattern always appears in the commands that
591
# break, we trap on that and then format that block of 'format' options
592
# as a literal block. We use the most recent format still listed so we
593
# don't have to do that too often -- vila 20110514
594
if not plain and options.find(' --1.14 ') != -1:
595
options = options.replace(' format:\n', ' format::\n\n', 1)
596
if options.startswith('Options:'):
597
result += gettext(':Options:%s') % (options[len('options:'):],)
603
# Add the description, indenting it 2 spaces
604
# to match the indentation of the options
606
text = sections.pop(None)
607
text = '\n '.join(text.splitlines())
608
result += gettext(':Description:\n %s\n\n') % (text,)
610
# Add the custom sections (e.g. Examples). Note that there's no need
611
# to indent these as they must be indented already in the source.
614
if label in sections:
615
result += ':%s:\n%s\n' % (label, sections[label])
618
result += (gettext("See brz help %s for more details and examples.\n\n")
621
# Add the aliases, source (plug-in) and see also links, if any
623
result += gettext(':Aliases: ')
624
result += ', '.join(self.aliases) + '\n'
625
plugin_name = self.plugin_name()
626
if plugin_name is not None:
627
result += gettext(':From: plugin "%s"\n') % plugin_name
628
see_also = self.get_see_also(additional_see_also)
630
if not plain and see_also_as_links:
632
for item in see_also:
634
# topics doesn't have an independent section
635
# so don't create a real link
636
see_also_links.append(item)
638
# Use a Sphinx link for this entry
639
link_text = gettext(":doc:`{0} <{1}-help>`").format(
641
see_also_links.append(link_text)
642
see_also = see_also_links
643
result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
645
# If this will be rendered as plain text, convert it
647
import breezy.help_topics
648
result = breezy.help_topics.help_as_plain_text(result)
652
def _get_help_parts(text):
653
"""Split help text into a summary and named sections.
655
:return: (summary,sections,order) where summary is the top line and
656
sections is a dictionary of the rest indexed by section name.
657
order is the order the section appear in the text.
658
A section starts with a heading line of the form ":xxx:".
659
Indented text on following lines is the section value.
660
All text found outside a named section is assigned to the
661
default section which is given the key of None.
663
def save_section(sections, order, label, section):
665
if label in sections:
666
sections[label] += '\n' + section
669
sections[label] = section
671
lines = text.rstrip().splitlines()
672
summary = lines.pop(0)
675
label, section = None, ''
677
if line.startswith(':') and line.endswith(':') and len(line) > 2:
678
save_section(sections, order, label, section)
679
label, section = line[1:-1], ''
680
elif (label is not None and len(line) > 1 and
681
not line[0].isspace()):
682
save_section(sections, order, label, section)
683
label, section = None, line
686
section += '\n' + line
689
save_section(sections, order, label, section)
690
return summary, sections, order
692
def get_help_topic(self):
693
"""Return the commands help topic - its name."""
696
def get_see_also(self, additional_terms=None):
697
"""Return a list of help topics that are related to this command.
699
The list is derived from the content of the _see_also attribute. Any
700
duplicates are removed and the result is in lexical order.
701
:param additional_terms: Additional help topics to cross-reference.
702
:return: A list of help topics.
704
see_also = set(getattr(self, '_see_also', []))
706
see_also.update(additional_terms)
707
return sorted(see_also)
710
"""Return dict of valid options for this command.
712
Maps from long option name to option object."""
713
r = Option.STD_OPTIONS.copy()
715
for o in self.takes_options:
716
if isinstance(o, str):
717
o = option.Option.OPTIONS[o]
719
if o.name in std_names:
720
self.supported_std_options.append(o.name)
723
def _setup_outf(self):
724
"""Return a file linked to stdout, which has proper encoding."""
725
self.outf = ui.ui_factory.make_output_stream(
726
encoding_type=self.encoding_type)
728
def run_argv_aliases(self, argv, alias_argv=None):
729
"""Parse the command line and run with extra aliases in alias_argv."""
730
args, opts = parse_args(self, argv, alias_argv)
733
# Process the standard options
734
if 'help' in opts: # e.g. brz add --help
735
self.outf.write(self.get_help_text())
737
if 'usage' in opts: # e.g. brz add --usage
738
self.outf.write(self.get_help_text(verbose=False))
740
trace.set_verbosity_level(option._verbosity_level)
741
if 'verbose' in self.supported_std_options:
742
opts['verbose'] = trace.is_verbose()
743
elif 'verbose' in opts:
745
if 'quiet' in self.supported_std_options:
746
opts['quiet'] = trace.is_quiet()
747
elif 'quiet' in opts:
749
# mix arguments and options into one dictionary
750
cmdargs = _match_argform(self.name(), self.takes_args, args)
752
for k, v in opts.items():
753
cmdopts[k.replace('-', '_')] = v
755
all_cmd_args = cmdargs.copy()
756
all_cmd_args.update(cmdopts)
759
return self.run(**all_cmd_args)
761
# reset it, so that other commands run in the same process won't
762
# inherit state. Before we reset it, log any activity, so that it
763
# gets properly tracked.
764
ui.ui_factory.log_transport_activity(
765
display=('bytes' in debug.debug_flags))
766
trace.set_verbosity_level(0)
768
def _setup_run(self):
769
"""Wrap the defined run method on self with a cleanup.
771
This is called by __init__ to make the Command be able to be run
772
by just calling run(), as it could be before cleanups were added.
774
If a different form of cleanups are in use by your Command subclass,
775
you can override this method.
779
def run(*args, **kwargs):
780
for hook in Command.hooks['pre_command']:
783
with contextlib.ExitStack() as self._exit_stack:
784
return class_run(*args, **kwargs)
786
for hook in Command.hooks['post_command']:
791
"""Actually run the command.
793
This is invoked with the options and arguments bound to
796
Return 0 or None if the command was successful, or a non-zero
797
shell error code if not. It's OK for this method to allow
798
an exception to raise up.
800
This method is automatically wrapped by Command.__init__ with a
801
ExitStack, stored as self._exit_stack. This can be used
802
via self.add_cleanup to perform automatic cleanups at the end of
805
The argument for run are assembled by introspection. So for instance,
806
if your command takes an argument files, you would declare::
808
def run(self, files=None):
811
raise NotImplementedError('no implementation of command %r'
815
"""Return help message for this class."""
816
from inspect import getdoc
817
if self.__doc__ is Command.__doc__:
821
def gettext(self, message):
822
"""Returns the gettext function used to translate this command's help.
824
Commands provided by plugins should override this to use their
827
return i18n.gettext_per_paragraph(message)
830
"""Return the canonical name for this command.
832
The name under which it was actually invoked is available in invoked_as
834
return _unsquish_command_name(self.__class__.__name__)
836
def plugin_name(self):
837
"""Get the name of the plugin that provides this command.
839
:return: The name of the plugin or None if the command is builtin.
841
return plugin_name(self.__module__)
844
class CommandHooks(Hooks):
845
"""Hooks related to Command object creation/enumeration."""
848
"""Create the default hooks.
850
These are all empty initially, because by default nothing should get
853
Hooks.__init__(self, "breezy.commands", "Command.hooks")
856
"Called after creating a command object to allow modifications "
857
"such as adding or removing options, docs etc. Called with the "
858
"new breezy.commands.Command object.", (1, 13))
861
"Called when creating a single command. Called with "
862
"(cmd_or_None, command_name). get_command should either return "
863
"the cmd_or_None parameter, or a replacement Command object that "
864
"should be used for the command. Note that the Command.hooks "
865
"hooks are core infrastructure. Many users will prefer to use "
866
"breezy.commands.register_command or plugin_cmds.register_lazy.",
869
'get_missing_command',
870
"Called when creating a single command if no command could be "
871
"found. Called with (command_name). get_missing_command should "
872
"either return None, or a Command object to be used for the "
876
"Called when enumerating commands. Called with a set of "
877
"cmd_name strings for all the commands found so far. This set "
878
" is safe to mutate - e.g. to remove a command. "
879
"list_commands should return the updated set of command names.",
883
"Called prior to executing a command. Called with the command "
887
"Called after executing a command. Called with the command "
891
Command.hooks = CommandHooks()
894
def parse_args(command, argv, alias_argv=None):
895
"""Parse command line.
897
Arguments and options are parsed at this level before being passed
898
down to specific command handlers. This routine knows, from a
899
lookup table, something about the available options, what optargs
900
they take, and which commands will accept them.
902
# TODO: make it a method of the Command?
903
parser = option.get_optparser(
904
[v for k, v in sorted(command.options().items())])
905
if alias_argv is not None:
906
args = alias_argv + argv
910
# python 2's optparse raises this exception if a non-ascii
911
# option name is given. See http://bugs.python.org/issue2931
913
options, args = parser.parse_args(args)
914
except UnicodeEncodeError:
915
raise errors.BzrCommandError(
916
gettext('Only ASCII permitted in option names'))
918
opts = dict((k, v) for k, v in options.__dict__.items() if
919
v is not option.OptionParser.DEFAULT_VALUE)
923
def _match_argform(cmd, takes_args, args):
926
# step through args and takes_args, allowing appropriate 0-many matches
927
for ap in takes_args:
931
argdict[argname] = args.pop(0)
932
elif ap[-1] == '*': # all remaining arguments
934
argdict[argname + '_list'] = args[:]
937
argdict[argname + '_list'] = None
940
raise errors.BzrCommandError(gettext(
941
"command {0!r} needs one or more {1}").format(
942
cmd, argname.upper()))
944
argdict[argname + '_list'] = args[:]
946
elif ap[-1] == '$': # all but one
948
raise errors.BzrCommandError(
949
gettext("command {0!r} needs one or more {1}").format(
950
cmd, argname.upper()))
951
argdict[argname + '_list'] = args[:-1]
957
raise errors.BzrCommandError(
958
gettext("command {0!r} requires argument {1}").format(
959
cmd, argname.upper()))
961
argdict[argname] = args.pop(0)
964
raise errors.BzrCommandError(gettext(
965
"extra argument to command {0}: {1}").format(
971
def apply_coveraged(the_callable, *args, **kwargs):
973
cov = coverage.Coverage()
974
os.environ['COVERAGE_PROCESS_START'] = cov.config_file
977
return exception_to_return_code(the_callable, *args, **kwargs)
983
def apply_profiled(the_callable, *args, **kwargs):
987
pffileno, pfname = tempfile.mkstemp()
989
prof = hotshot.Profile(pfname)
991
ret = prof.runcall(exception_to_return_code, the_callable, *args,
995
stats = hotshot.stats.load(pfname)
997
stats.sort_stats('cum') # 'time'
998
# XXX: Might like to write to stderr or the trace file instead but
999
# print_stats seems hardcoded to stdout
1000
stats.print_stats(20)
1007
def exception_to_return_code(the_callable, *args, **kwargs):
1008
"""UI level helper for profiling and coverage.
1010
This transforms exceptions into a return value of 3. As such its only
1011
relevant to the UI layer, and should never be called where catching
1012
exceptions may be desirable.
1015
return the_callable(*args, **kwargs)
1016
except (KeyboardInterrupt, Exception):
1017
# used to handle AssertionError and KeyboardInterrupt
1018
# specially here, but hopefully they're handled ok by the logger now
1019
exc_info = sys.exc_info()
1020
exitcode = trace.report_exception(exc_info, sys.stderr)
1021
if os.environ.get('BRZ_PDB'):
1022
print('**** entering debugger')
1024
pdb.post_mortem(exc_info[2])
1028
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
1029
from breezy.lsprof import profile
1030
ret, stats = profile(exception_to_return_code, the_callable,
1033
if filename is None:
1036
stats.save(filename)
1037
trace.note(gettext('Profile data written to "%s".'), filename)
1041
def get_alias(cmd, config=None):
1042
"""Return an expanded alias, or None if no alias exists.
1045
Command to be checked for an alias.
1047
Used to specify an alternative config to use,
1048
which is especially useful for testing.
1049
If it is unspecified, the global config will be used.
1052
import breezy.config
1053
config = breezy.config.GlobalConfig()
1054
alias = config.get_alias(cmd)
1056
return cmdline.split(alias)
1060
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
1061
"""Execute a command.
1063
:param argv: The command-line arguments, without the program name from
1064
argv[0] These should already be decoded. All library/test code calling
1065
run_bzr should be passing valid strings (don't need decoding).
1066
:param load_plugins: What function to call when triggering plugin loading.
1067
This function should take no arguments and cause all plugins to be
1069
:param disable_plugins: What function to call when disabling plugin
1070
loading. This function should take no arguments and cause all plugin
1071
loading to be prohibited (so that code paths in your application that
1072
know about some plugins possibly being present will fail to import
1073
those plugins even if they are installed.)
1074
:return: Returns a command exit code or raises an exception.
1076
Special master options: these must come before the command because
1077
they control how the command is interpreted.
1080
Do not load plugin modules at all
1083
Do not allow aliases
1086
Only use builtin commands. (Plugins are still allowed to change
1090
Run under the Python hotshot profiler.
1093
Run under the Python lsprof profiler.
1096
Generate code coverage report
1099
Specify the number of processes that can be run concurrently
1102
trace.mutter("breezy version: " + breezy.__version__)
1103
argv = _specified_or_unicode_argv(argv)
1104
trace.mutter("brz arguments: %r", argv)
1106
opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
1107
opt_coverage = opt_no_l10n = opt_no_aliases = False
1108
opt_lsprof_file = None
1110
# --no-plugins is handled specially at a very early stage. We need
1111
# to load plugins before doing other command parsing so that they
1112
# can override commands, but this needs to happen first.
1116
override_config = []
1117
while i < len(argv):
1119
if a == '--profile':
1121
elif a == '--lsprof':
1123
elif a == '--lsprof-file':
1125
opt_lsprof_file = argv[i + 1]
1127
elif a == '--no-plugins':
1128
opt_no_plugins = True
1129
elif a == '--no-aliases':
1130
opt_no_aliases = True
1131
elif a == '--no-l10n':
1133
elif a == '--builtin':
1135
elif a == '--concurrency':
1136
os.environ['BRZ_CONCURRENCY'] = argv[i + 1]
1138
elif a == '--coverage':
1140
elif a == '--profile-imports':
1141
pass # already handled in startup script Bug #588277
1142
elif a.startswith('-D'):
1143
debug.debug_flags.add(a[2:])
1144
elif a.startswith('-O'):
1145
override_config.append(a[2:])
1150
cmdline_overrides = breezy.get_global_state().cmdline_overrides
1151
cmdline_overrides._from_cmdline(override_config)
1153
debug.set_debug_flags_from_config()
1155
if not opt_no_plugins:
1162
get_cmd_object('help').run_argv_aliases([])
1165
if argv[0] == '--version':
1166
get_cmd_object('version').run_argv_aliases([])
1171
if not opt_no_aliases:
1172
alias_argv = get_alias(argv[0])
1174
argv[0] = alias_argv.pop(0)
1177
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
1179
cmd_obj.l10n = False
1180
run = cmd_obj.run_argv_aliases
1181
run_argv = [argv, alias_argv]
1184
# We can be called recursively (tests for example), but we don't want
1185
# the verbosity level to propagate.
1186
saved_verbosity_level = option._verbosity_level
1187
option._verbosity_level = 0
1191
'--coverage ignored, because --lsprof is in use.')
1192
ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
1196
'--coverage ignored, because --profile is in use.')
1197
ret = apply_profiled(run, *run_argv)
1199
ret = apply_coveraged(run, *run_argv)
1201
ret = run(*run_argv)
1204
# reset, in case we may do other commands later within the same
1205
# process. Commands that want to execute sub-commands must propagate
1206
# --verbose in their own way.
1207
if 'memory' in debug.debug_flags:
1208
trace.debug_memory('Process status after command:', short=False)
1209
option._verbosity_level = saved_verbosity_level
1210
# Reset the overrides
1211
cmdline_overrides._reset()
1214
def display_command(func):
1215
"""Decorator that suppresses pipe/interrupt errors."""
1216
def ignore_pipe(*args, **kwargs):
1218
result = func(*args, **kwargs)
1221
except IOError as e:
1222
if getattr(e, 'errno', None) is None:
1224
if e.errno != errno.EPIPE:
1225
# Win32 raises IOError with errno=0 on a broken pipe
1226
if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
1229
except KeyboardInterrupt:
1234
def install_bzr_command_hooks():
1235
"""Install the hooks to supply bzr's own commands."""
1236
if _list_bzr_commands in Command.hooks["list_commands"]:
1238
Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
1240
Command.hooks.install_named_hook("get_command", _get_bzr_command,
1242
Command.hooks.install_named_hook("get_command", _get_plugin_command,
1243
"bzr plugin commands")
1244
Command.hooks.install_named_hook("get_command", _get_external_command,
1245
"bzr external command lookup")
1246
Command.hooks.install_named_hook("get_missing_command",
1247
_try_plugin_provider,
1248
"bzr plugin-provider-db check")
1251
def _specified_or_unicode_argv(argv):
1252
# For internal or testing use, argv can be passed. Otherwise, get it from
1253
# the process arguments in a unicode-safe way.
1255
return osutils.get_unicode_argv()
1258
# ensure all arguments are unicode strings
1260
if not isinstance(a, str):
1261
raise ValueError('not native str or unicode: %r' % (a,))
1263
except (ValueError, UnicodeDecodeError):
1264
raise errors.BzrError("argv should be list of unicode strings.")
1268
def main(argv=None):
1269
"""Main entry point of command-line interface.
1271
Typically `breezy.initialize` should be called first.
1273
:param argv: list of unicode command-line arguments similar to sys.argv.
1274
argv[0] is script name usually, it will be ignored.
1275
Don't pass here sys.argv because this list contains plain strings
1276
and not unicode; pass None instead.
1278
:return: exit code of brz command.
1280
if argv is not None:
1282
_register_builtin_commands()
1283
ret = run_bzr_catch_errors(argv)
1284
trace.mutter("return code %d", ret)
1288
def run_bzr_catch_errors(argv):
1289
"""Run a bzr command with parameters as described by argv.
1291
This function assumed that that UI layer is setup, that symbol deprecations
1292
are already applied, and that unicode decoding has already been performed
1295
# done here so that they're covered for every test run
1296
install_bzr_command_hooks()
1297
return exception_to_return_code(run_bzr, argv)
1300
def run_bzr_catch_user_errors(argv):
1301
"""Run brz and report user errors, but let internal errors propagate.
1303
This is used for the test suite, and might be useful for other programs
1304
that want to wrap the commandline interface.
1306
# done here so that they're covered for every test run
1307
install_bzr_command_hooks()
1309
return run_bzr(argv)
1310
except Exception as e:
1311
if (isinstance(e, (OSError, IOError))
1312
or not getattr(e, 'internal_error', True)):
1313
trace.report_exception(sys.exc_info(), sys.stderr)
1319
class HelpCommandIndex(object):
1320
"""A index for bzr help that returns commands."""
1323
self.prefix = 'commands/'
1325
def get_topics(self, topic):
1326
"""Search for topic amongst commands.
1328
:param topic: A topic to search for.
1329
:return: A list which is either empty or contains a single
1332
if topic and topic.startswith(self.prefix):
1333
topic = topic[len(self.prefix):]
1335
cmd = _get_cmd_object(topic, check_missing=False)
1342
class Provider(object):
1343
"""Generic class to be overriden by plugins"""
1345
def plugin_for_command(self, cmd_name):
1346
"""Takes a command and returns the information for that plugin
1348
:return: A dictionary with all the available information
1349
for the requested plugin
1351
raise NotImplementedError
1354
class ProvidersRegistry(registry.Registry):
1355
"""This registry exists to allow other providers to exist"""
1358
for key, provider in self.items():
1362
command_providers_registry = ProvidersRegistry()