28
28
# TODO: "--profile=cum", to change sort order. Is there any value in leaving
29
29
# the profile output behind so it can be interactively examined?
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
34
39
from warnings import warn
38
import bzrlib.errors as errors
39
from bzrlib.errors import (BzrError,
43
from bzrlib import option
52
from bzrlib import registry
54
from bzrlib.hooks import HookPoint, Hooks
44
55
from bzrlib.option import Option
46
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
48
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
58
class CommandInfo(object):
59
"""Information about a command."""
61
def __init__(self, aliases):
62
"""The list of aliases for the command."""
63
self.aliases = aliases
66
def from_command(klass, command):
67
"""Factory to construct a CommandInfo from a command."""
68
return klass(command.aliases)
71
class CommandRegistry(registry.Registry):
74
def _get_name(command_name):
75
if command_name.startswith("cmd_"):
76
return _unsquish_command_name(command_name)
80
def register(self, cmd, decorate=False):
81
"""Utility function to help register a command
83
:param cmd: Command subclass to register
84
:param decorate: If true, allow overriding an existing command
85
of the same name; the old command is returned by this function.
86
Otherwise it is an error to try to override an existing command.
89
k_unsquished = self._get_name(k)
91
previous = self.get(k_unsquished)
93
previous = _builtin_commands().get(k_unsquished)
94
info = CommandInfo.from_command(cmd)
96
registry.Registry.register(self, k_unsquished, cmd,
97
override_existing=decorate, info=info)
99
trace.log_error('Two plugins defined the same command: %r' % k)
100
trace.log_error('Not loading the one in %r' %
101
sys.modules[cmd.__module__])
102
trace.log_error('Previously this command was registered from %r' %
103
sys.modules[previous.__module__])
106
def register_lazy(self, command_name, aliases, module_name):
107
"""Register a command without loading its module.
109
:param command_name: The primary name of the command.
110
:param aliases: A list of aliases for the command.
111
:module_name: The module that the command lives in.
113
key = self._get_name(command_name)
114
registry.Registry.register_lazy(self, key, module_name, command_name,
115
info=CommandInfo(aliases))
118
plugin_cmds = CommandRegistry()
53
121
def register_command(cmd, decorate=False):
54
"""Utility function to help register a command
56
:param cmd: Command subclass to register
57
:param decorate: If true, allow overriding an existing command
58
of the same name; the old command is returned by this function.
59
Otherwise it is an error to try to override an existing command.
61
122
global plugin_cmds
63
if k.startswith("cmd_"):
64
k_unsquished = _unsquish_command_name(k)
67
if k_unsquished not in plugin_cmds:
68
plugin_cmds[k_unsquished] = cmd
69
mutter('registered plugin command %s', k_unsquished)
70
if decorate and k_unsquished in builtin_command_names():
71
return _builtin_commands()[k_unsquished]
73
result = plugin_cmds[k_unsquished]
74
plugin_cmds[k_unsquished] = cmd
77
log_error('Two plugins defined the same command: %r' % k)
78
log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
123
return plugin_cmds.register(cmd, decorate)
81
126
def _squish_command_name(cmd):
211
292
encoding_type = 'strict'
215
296
def __init__(self):
216
297
"""Construct an instance of this command."""
217
298
if self.__doc__ == Command.__doc__:
218
299
warn("No help message set for %r" % self)
300
# List of standard options directly supported
301
self.supported_std_options = []
303
def _maybe_expand_globs(self, file_list):
304
"""Glob expand file_list if the platform does not do that itself.
306
:return: A possibly empty list of unicode paths.
308
Introduced in bzrlib 0.18.
312
if sys.platform == 'win32':
313
file_list = win32utils.glob_expand(file_list)
314
return list(file_list)
317
"""Return single-line grammar for this command.
319
Only describes arguments, not options.
321
s = 'bzr ' + self.name() + ' '
322
for aname in self.takes_args:
323
aname = aname.upper()
324
if aname[-1] in ['$', '+']:
325
aname = aname[:-1] + '...'
326
elif aname[-1] == '?':
327
aname = '[' + aname[:-1] + ']'
328
elif aname[-1] == '*':
329
aname = '[' + aname[:-1] + '...]'
331
s = s[:-1] # remove last space
334
def get_help_text(self, additional_see_also=None, plain=True,
335
see_also_as_links=False, verbose=True):
336
"""Return a text string with help for this command.
338
:param additional_see_also: Additional help topics to be
340
:param plain: if False, raw help (reStructuredText) is
341
returned instead of plain text.
342
:param see_also_as_links: if True, convert items in 'See also'
343
list to internal links (used by bzr_man rstx generator)
344
:param verbose: if True, display the full help, otherwise
345
leave out the descriptive sections and just display
346
usage help (e.g. Purpose, Usage, Options) with a
347
message explaining how to obtain full help.
351
raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
353
# Extract the summary (purpose) and sections out from the text
354
purpose,sections,order = self._get_help_parts(doc)
356
# If a custom usage section was provided, use it
357
if sections.has_key('Usage'):
358
usage = sections.pop('Usage')
360
usage = self._usage()
362
# The header is the purpose and usage
364
result += ':Purpose: %s\n' % purpose
365
if usage.find('\n') >= 0:
366
result += ':Usage:\n%s\n' % usage
368
result += ':Usage: %s\n' % usage
372
options = option.get_optparser(self.options()).format_option_help()
373
if options.startswith('Options:'):
374
result += ':' + options
375
elif options.startswith('options:'):
376
# Python 2.4 version of optparse
377
result += ':Options:' + options[len('options:'):]
383
# Add the description, indenting it 2 spaces
384
# to match the indentation of the options
385
if sections.has_key(None):
386
text = sections.pop(None)
387
text = '\n '.join(text.splitlines())
388
result += ':%s:\n %s\n\n' % ('Description',text)
390
# Add the custom sections (e.g. Examples). Note that there's no need
391
# to indent these as they must be indented already in the source.
394
if sections.has_key(label):
395
result += ':%s:\n%s\n' % (label,sections[label])
398
result += ("See bzr help %s for more details and examples.\n\n"
401
# Add the aliases, source (plug-in) and see also links, if any
403
result += ':Aliases: '
404
result += ', '.join(self.aliases) + '\n'
405
plugin_name = self.plugin_name()
406
if plugin_name is not None:
407
result += ':From: plugin "%s"\n' % plugin_name
408
see_also = self.get_see_also(additional_see_also)
410
if not plain and see_also_as_links:
412
for item in see_also:
414
# topics doesn't have an independent section
415
# so don't create a real link
416
see_also_links.append(item)
418
# Use a reST link for this entry
419
see_also_links.append("`%s`_" % (item,))
420
see_also = see_also_links
421
result += ':See also: '
422
result += ', '.join(see_also) + '\n'
424
# If this will be rendered as plain text, convert it
426
import bzrlib.help_topics
427
result = bzrlib.help_topics.help_as_plain_text(result)
431
def _get_help_parts(text):
432
"""Split help text into a summary and named sections.
434
:return: (summary,sections,order) where summary is the top line and
435
sections is a dictionary of the rest indexed by section name.
436
order is the order the section appear in the text.
437
A section starts with a heading line of the form ":xxx:".
438
Indented text on following lines is the section value.
439
All text found outside a named section is assigned to the
440
default section which is given the key of None.
442
def save_section(sections, order, label, section):
444
if sections.has_key(label):
445
sections[label] += '\n' + section
448
sections[label] = section
450
lines = text.rstrip().splitlines()
451
summary = lines.pop(0)
454
label,section = None,''
456
if line.startswith(':') and line.endswith(':') and len(line) > 2:
457
save_section(sections, order, label, section)
458
label,section = line[1:-1],''
459
elif (label is not None) and len(line) > 1 and not line[0].isspace():
460
save_section(sections, order, label, section)
461
label,section = None,line
464
section += '\n' + line
467
save_section(sections, order, label, section)
468
return summary, sections, order
470
def get_help_topic(self):
471
"""Return the commands help topic - its name."""
474
def get_see_also(self, additional_terms=None):
475
"""Return a list of help topics that are related to this command.
477
The list is derived from the content of the _see_also attribute. Any
478
duplicates are removed and the result is in lexical order.
479
:param additional_terms: Additional help topics to cross-reference.
480
:return: A list of help topics.
482
see_also = set(getattr(self, '_see_also', []))
484
see_also.update(additional_terms)
485
return sorted(see_also)
220
487
def options(self):
221
488
"""Return dict of valid options for this command.
223
490
Maps from long option name to option object."""
225
r['help'] = Option.OPTIONS['help']
491
r = Option.STD_OPTIONS.copy()
226
493
for o in self.takes_options:
227
494
if isinstance(o, basestring):
228
o = Option.OPTIONS[o]
495
o = option.Option.OPTIONS[o]
497
if o.name in std_names:
498
self.supported_std_options.append(o.name)
232
501
def _setup_outf(self):
233
502
"""Return a file linked to stdout, which has proper encoding."""
234
assert self.encoding_type in ['strict', 'exact', 'replace']
236
503
# Originally I was using self.stdout, but that looks
237
504
# *way* too much like sys.stdout
238
505
if self.encoding_type == 'exact':
506
# force sys.stdout to be binary stream on win32
507
if sys.platform == 'win32':
508
fileno = getattr(sys.stdout, 'fileno', None)
511
msvcrt.setmode(fileno(), os.O_BINARY)
239
512
self.outf = sys.stdout
242
output_encoding = bzrlib.osutils.get_terminal_encoding()
515
output_encoding = osutils.get_terminal_encoding()
244
# use 'replace' so that we don't abort if trying to write out
245
# in e.g. the default C locale.
246
self.outf = codecs.getwriter(output_encoding)(sys.stdout, errors=self.encoding_type)
517
self.outf = codecs.getwriter(output_encoding)(sys.stdout,
518
errors=self.encoding_type)
247
519
# For whatever reason codecs.getwriter() does not advertise its encoding
248
520
# it just returns the encoding of the wrapped file, which is completely
249
521
# bogus. So set the attribute, so we can find the correct encoding later.
250
522
self.outf.encoding = output_encoding
252
@deprecated_method(zero_eight)
253
def run_argv(self, argv):
254
"""Parse command line and run.
256
See run_argv_aliases for the 0.8 and beyond api.
258
return self.run_argv_aliases(argv)
260
524
def run_argv_aliases(self, argv, alias_argv=None):
261
525
"""Parse the command line and run with extra aliases in alias_argv."""
263
warn("Passing None for [] is deprecated from bzrlib 0.10",
527
warn("Passing None for [] is deprecated from bzrlib 0.10",
264
528
DeprecationWarning, stacklevel=2)
266
530
args, opts = parse_args(self, argv, alias_argv)
532
# Process the standard options
267
533
if 'help' in opts: # e.g. bzr add --help
268
from bzrlib.help import help_on_command
269
help_on_command(self.name())
534
sys.stdout.write(self.get_help_text())
536
if 'usage' in opts: # e.g. bzr add --usage
537
sys.stdout.write(self.get_help_text(verbose=False))
539
trace.set_verbosity_level(option._verbosity_level)
540
if 'verbose' in self.supported_std_options:
541
opts['verbose'] = trace.is_verbose()
542
elif opts.has_key('verbose'):
544
if 'quiet' in self.supported_std_options:
545
opts['quiet'] = trace.is_quiet()
546
elif opts.has_key('quiet'):
271
549
# mix arguments and options into one dictionary
272
550
cmdargs = _match_argform(self.name(), self.takes_args, args)
385
650
argdict[argname + '_list'] = None
386
651
elif ap[-1] == '+':
388
raise BzrCommandError("command %r needs one or more %s"
389
% (cmd, argname.upper()))
653
raise errors.BzrCommandError("command %r needs one or more %s"
654
% (cmd, argname.upper()))
391
656
argdict[argname + '_list'] = args[:]
393
658
elif ap[-1] == '$': # all but one
394
659
if len(args) < 2:
395
raise BzrCommandError("command %r needs one or more %s"
396
% (cmd, argname.upper()))
660
raise errors.BzrCommandError("command %r needs one or more %s"
661
% (cmd, argname.upper()))
397
662
argdict[argname + '_list'] = args[:-1]
400
665
# just a plain arg
403
raise BzrCommandError("command %r requires argument %s"
404
% (cmd, argname.upper()))
668
raise errors.BzrCommandError("command %r requires argument %s"
669
% (cmd, argname.upper()))
406
671
argdict[argname] = args.pop(0)
409
raise BzrCommandError("extra argument to command %s: %s"
674
raise errors.BzrCommandError("extra argument to command %s: %s"
679
def apply_coveraged(dirname, the_callable, *args, **kwargs):
680
# Cannot use "import trace", as that would import bzrlib.trace instead of
681
# the standard library's trace.
682
trace = __import__('trace')
684
tracer = trace.Trace(count=1, trace=0)
685
sys.settrace(tracer.globaltrace)
686
threading.settrace(tracer.globaltrace)
689
return exception_to_return_code(the_callable, *args, **kwargs)
692
results = tracer.results()
693
results.write_results(show_missing=1, summary=False,
416
697
def apply_profiled(the_callable, *args, **kwargs):
436
718
os.remove(pfname)
721
def exception_to_return_code(the_callable, *args, **kwargs):
722
"""UI level helper for profiling and coverage.
724
This transforms exceptions into a return value of 3. As such its only
725
relevant to the UI layer, and should never be called where catching
726
exceptions may be desirable.
729
return the_callable(*args, **kwargs)
730
except (KeyboardInterrupt, Exception), e:
731
# used to handle AssertionError and KeyboardInterrupt
732
# specially here, but hopefully they're handled ok by the logger now
733
exc_info = sys.exc_info()
734
exitcode = trace.report_exception(exc_info, sys.stderr)
735
if os.environ.get('BZR_PDB'):
736
print '**** entering debugger'
739
if sys.version_info[:2] < (2, 6):
741
# pdb.post_mortem(tb)
742
# but because pdb.post_mortem gives bad results for tracebacks
743
# from inside generators, we do it manually.
744
# (http://bugs.python.org/issue4150, fixed in Python 2.6)
746
# Setup pdb on the traceback
749
p.setup(tb.tb_frame, tb)
750
# Point the debugger at the deepest frame of the stack
751
p.curindex = len(p.stack) - 1
752
p.curframe = p.stack[p.curindex][0]
753
# Start the pdb prompt.
754
p.print_stack_entry(p.stack[p.curindex])
439
762
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
440
763
from bzrlib.lsprof import profile
442
ret, stats = profile(the_callable, *args, **kwargs)
764
ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
444
766
if filename is None:
448
cPickle.dump(stats, open(filename, 'w'), 2)
449
print 'Profile data written to %r.' % filename
770
trace.note('Profile data written to "%s".', filename)
454
"""Return an expanded alias, or None if no alias exists"""
456
alias = bzrlib.config.GlobalConfig().get_alias(cmd)
774
def shlex_split_unicode(unsplit):
776
return [u.decode('utf-8') for u in shlex.split(unsplit.encode('utf-8'))]
779
def get_alias(cmd, config=None):
780
"""Return an expanded alias, or None if no alias exists.
783
Command to be checked for an alias.
785
Used to specify an alternative config to use,
786
which is especially useful for testing.
787
If it is unspecified, the global config will be used.
791
config = bzrlib.config.GlobalConfig()
792
alias = config.get_alias(cmd)
458
return alias.split(' ')
794
return shlex_split_unicode(alias)
462
798
def run_bzr(argv):
463
799
"""Execute a command.
465
This is similar to main(), but without all the trappings for
466
logging and error handling.
469
802
The command-line arguments, without the program name from argv[0]
470
803
These should already be decoded. All library/test code calling
471
804
run_bzr should be passing valid strings (don't need decoding).
473
806
Returns a command status or raises an exception.
475
808
Special master options: these must come before the command because
601
from bzrlib.ui.text import TextUIFactory
602
bzrlib.ui.ui_factory = TextUIFactory()
603
argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
957
bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
958
sys.stdin, sys.stdout, sys.stderr)
960
# Is this a final release version? If so, we should suppress warnings
961
if bzrlib.version_info[3] == 'final':
962
from bzrlib import symbol_versioning
963
symbol_versioning.suppress_deprecation_warnings(override=False)
965
user_encoding = osutils.get_user_encoding()
966
argv = [a.decode(user_encoding) for a in argv[1:]]
967
except UnicodeDecodeError:
968
raise errors.BzrError(("Parameter '%r' is unsupported by the current "
604
970
ret = run_bzr_catch_errors(argv)
605
mutter("return code %d", ret)
971
trace.mutter("return code %d", ret)
609
975
def run_bzr_catch_errors(argv):
976
"""Run a bzr command with parameters as described by argv.
978
This function assumed that that UI layer is setup, that symbol deprecations
979
are already applied, and that unicode decoding has already been performed on argv.
981
return exception_to_return_code(run_bzr, argv)
984
def run_bzr_catch_user_errors(argv):
985
"""Run bzr and report user errors, but let internal errors propagate.
987
This is used for the test suite, and might be useful for other programs
988
that want to wrap the commandline interface.
611
991
return run_bzr(argv)
612
# do this here inside the exception wrappers to catch EPIPE
614
992
except Exception, e:
615
# used to handle AssertionError and KeyboardInterrupt
616
# specially here, but hopefully they're handled ok by the logger now
617
bzrlib.trace.report_exception(sys.exc_info(), sys.stderr)
618
if os.environ.get('BZR_PDB'):
619
print '**** entering debugger'
621
pdb.post_mortem(sys.exc_traceback)
993
if (isinstance(e, (OSError, IOError))
994
or not getattr(e, 'internal_error', True)):
995
trace.report_exception(sys.exc_info(), sys.stderr)
1001
class HelpCommandIndex(object):
1002
"""A index for bzr help that returns commands."""
1005
self.prefix = 'commands/'
1007
def get_topics(self, topic):
1008
"""Search for topic amongst commands.
1010
:param topic: A topic to search for.
1011
:return: A list which is either empty or contains a single
1014
if topic and topic.startswith(self.prefix):
1015
topic = topic[len(self.prefix):]
1017
cmd = _get_cmd_object(topic)
1024
class Provider(object):
1025
'''Generic class to be overriden by plugins'''
1027
def plugin_for_command(self, cmd_name):
1028
'''Takes a command and returns the information for that plugin
1030
:return: A dictionary with all the available information
1031
for the requested plugin
1033
raise NotImplementedError
1036
class ProvidersRegistry(registry.Registry):
1037
'''This registry exists to allow other providers to exist'''
1040
for key, provider in self.iteritems():
1043
command_providers_registry = ProvidersRegistry()
624
1046
if __name__ == '__main__':
625
1047
sys.exit(main(sys.argv))