1
# Copyright (C) 2006, 2008 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
18
# TODO: probably should say which arguments are candidates for glob
19
# expansion on windows and do that at the command level.
21
# TODO: Define arguments by objects, rather than just using names.
22
# Those objects can specify the expected type of the argument, which
23
# would help with validation and shell completion. They could also provide
24
# help/explanation for that argument in a structured way.
26
# TODO: Specific "examples" property on commands for consistent formatting.
28
# TODO: "--profile=cum", to change sort order. Is there any value in leaving
29
# the profile output behind so it can be interactively examined?
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
39
from warnings import warn
52
from bzrlib import registry
54
from bzrlib.hooks import HookPoint, Hooks
55
from bzrlib.option import Option
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()
121
def register_command(cmd, decorate=False):
123
return plugin_cmds.register(cmd, decorate)
126
def _squish_command_name(cmd):
127
return 'cmd_' + cmd.replace('-', '_')
130
def _unsquish_command_name(cmd):
131
return cmd[4:].replace('_','-')
134
def _builtin_commands():
135
import bzrlib.builtins
137
builtins = bzrlib.builtins.__dict__
138
for name in builtins:
139
if name.startswith("cmd_"):
140
real_name = _unsquish_command_name(name)
141
r[real_name] = builtins[name]
145
def builtin_command_names():
146
"""Return list of builtin command names."""
147
return _builtin_commands().keys()
150
def plugin_command_names():
151
return plugin_cmds.keys()
154
def _get_cmd_dict(plugins_override=True):
155
"""Return name->class mapping for all commands."""
156
d = _builtin_commands()
158
d.update(plugin_cmds.iteritems())
162
def get_all_cmds(plugins_override=True):
163
"""Return canonical name and class for all registered commands."""
164
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
168
def get_cmd_object(cmd_name, plugins_override=True):
169
"""Return the canonical name and command class for a command.
172
If true, plugin commands can override builtins.
175
cmd = _get_cmd_object(cmd_name, plugins_override)
176
# Allow plugins to extend commands
177
for hook in Command.hooks['extend_command']:
181
raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
184
def _get_cmd_object(cmd_name, plugins_override=True):
185
"""Worker for get_cmd_object which raises KeyError rather than BzrCommandError."""
186
from bzrlib.externalcommand import ExternalCommand
188
# We want only 'ascii' command names, but the user may have typed
189
# in a Unicode name. In that case, they should just get a
190
# 'command not found' error later.
191
# In the future, we may actually support Unicode command names.
193
# first look up this command under the specified name
196
return plugin_cmds.get(cmd_name)()
199
cmds = _get_cmd_dict(plugins_override=False)
201
return cmds[cmd_name]()
205
for key in plugin_cmds.keys():
206
info = plugin_cmds.get_info(key)
207
if cmd_name in info.aliases:
208
return plugin_cmds.get(key)()
209
# look for any command which claims this as an alias
210
for real_cmd_name, cmd_class in cmds.iteritems():
211
if cmd_name in cmd_class.aliases:
214
cmd_obj = ExternalCommand.find_command(cmd_name)
218
# look for plugins that provide this command but aren't installed
219
for provider in command_providers_registry:
221
plugin_metadata = provider.plugin_for_command(cmd_name)
222
except errors.NoPluginAvailable:
225
raise errors.CommandAvailableInPlugin(cmd_name,
226
plugin_metadata, provider)
230
class Command(object):
231
"""Base class for commands.
233
Commands are the heart of the command-line bzr interface.
235
The command object mostly handles the mapping of command-line
236
parameters into one or more bzrlib operations, and of the results
239
Commands normally don't have any state. All their arguments are
240
passed in to the run method. (Subclasses may take a different
241
policy if the behaviour of the instance needs to depend on e.g. a
242
shell plugin and not just its Python class.)
244
The docstring for an actual command should give a single-line
245
summary, then a complete description of the command. A grammar
246
description will be inserted.
249
Other accepted names for this command.
252
List of argument forms, marked with whether they are optional,
257
['to_location', 'from_branch?', 'file*']
259
'to_location' is required
260
'from_branch' is optional
261
'file' can be specified 0 or more times
264
List of options that may be given for this command. These can
265
be either strings, referring to globally-defined options,
266
or option objects. Retrieve through options().
269
If true, this command isn't advertised. This is typically
270
for commands intended for expert users.
273
Command objects will get a 'outf' attribute, which has been
274
setup to properly handle encoding of unicode strings.
275
encoding_type determines what will happen when characters cannot
277
strict - abort if we cannot decode
278
replace - put in a bogus character (typically '?')
279
exact - do not encode sys.stdout
281
NOTE: by default on Windows, sys.stdout is opened as a text
282
stream, therefore LF line-endings are converted to CRLF.
283
When a command uses encoding_type = 'exact', then
284
sys.stdout is forced to be a binary stream, and line-endings
287
:cvar hooks: An instance of CommandHooks.
292
encoding_type = 'strict'
297
"""Construct an instance of this command."""
298
if self.__doc__ == Command.__doc__:
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)
488
"""Return dict of valid options for this command.
490
Maps from long option name to option object."""
491
r = Option.STD_OPTIONS.copy()
493
for o in self.takes_options:
494
if isinstance(o, basestring):
495
o = option.Option.OPTIONS[o]
497
if o.name in std_names:
498
self.supported_std_options.append(o.name)
501
def _setup_outf(self):
502
"""Return a file linked to stdout, which has proper encoding."""
503
# Originally I was using self.stdout, but that looks
504
# *way* too much like sys.stdout
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)
512
self.outf = sys.stdout
515
output_encoding = osutils.get_terminal_encoding()
517
self.outf = codecs.getwriter(output_encoding)(sys.stdout,
518
errors=self.encoding_type)
519
# For whatever reason codecs.getwriter() does not advertise its encoding
520
# it just returns the encoding of the wrapped file, which is completely
521
# bogus. So set the attribute, so we can find the correct encoding later.
522
self.outf.encoding = output_encoding
524
def run_argv_aliases(self, argv, alias_argv=None):
525
"""Parse the command line and run with extra aliases in alias_argv."""
527
warn("Passing None for [] is deprecated from bzrlib 0.10",
528
DeprecationWarning, stacklevel=2)
530
args, opts = parse_args(self, argv, alias_argv)
532
# Process the standard options
533
if 'help' in opts: # e.g. bzr add --help
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'):
549
# mix arguments and options into one dictionary
550
cmdargs = _match_argform(self.name(), self.takes_args, args)
552
for k, v in opts.items():
553
cmdopts[k.replace('-', '_')] = v
555
all_cmd_args = cmdargs.copy()
556
all_cmd_args.update(cmdopts)
560
return self.run(**all_cmd_args)
563
"""Actually run the command.
565
This is invoked with the options and arguments bound to
568
Return 0 or None if the command was successful, or a non-zero
569
shell error code if not. It's OK for this method to allow
570
an exception to raise up.
572
raise NotImplementedError('no implementation of command %r'
576
"""Return help message for this class."""
577
from inspect import getdoc
578
if self.__doc__ is Command.__doc__:
583
return _unsquish_command_name(self.__class__.__name__)
585
def plugin_name(self):
586
"""Get the name of the plugin that provides this command.
588
:return: The name of the plugin or None if the command is builtin.
590
mod_parts = self.__module__.split('.')
591
if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
597
class CommandHooks(Hooks):
598
"""Hooks related to Command object creation/enumeration."""
601
"""Create the default hooks.
603
These are all empty initially, because by default nothing should get
607
self.create_hook(HookPoint('extend_command',
608
"Called after creating a command object to allow modifications "
609
"such as adding or removing options, docs etc. Called with the "
610
"new bzrlib.commands.Command object.", (1, 13), None))
612
Command.hooks = CommandHooks()
615
def parse_args(command, argv, alias_argv=None):
616
"""Parse command line.
618
Arguments and options are parsed at this level before being passed
619
down to specific command handlers. This routine knows, from a
620
lookup table, something about the available options, what optargs
621
they take, and which commands will accept them.
623
# TODO: make it a method of the Command?
624
parser = option.get_optparser(command.options())
625
if alias_argv is not None:
626
args = alias_argv + argv
630
options, args = parser.parse_args(args)
631
opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
632
v is not option.OptionParser.DEFAULT_VALUE])
636
def _match_argform(cmd, takes_args, args):
639
# step through args and takes_args, allowing appropriate 0-many matches
640
for ap in takes_args:
644
argdict[argname] = args.pop(0)
645
elif ap[-1] == '*': # all remaining arguments
647
argdict[argname + '_list'] = args[:]
650
argdict[argname + '_list'] = None
653
raise errors.BzrCommandError("command %r needs one or more %s"
654
% (cmd, argname.upper()))
656
argdict[argname + '_list'] = args[:]
658
elif ap[-1] == '$': # all but one
660
raise errors.BzrCommandError("command %r needs one or more %s"
661
% (cmd, argname.upper()))
662
argdict[argname + '_list'] = args[:-1]
668
raise errors.BzrCommandError("command %r requires argument %s"
669
% (cmd, argname.upper()))
671
argdict[argname] = args.pop(0)
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,
697
def apply_profiled(the_callable, *args, **kwargs):
701
pffileno, pfname = tempfile.mkstemp()
703
prof = hotshot.Profile(pfname)
705
ret = prof.runcall(exception_to_return_code, the_callable, *args,
709
stats = hotshot.stats.load(pfname)
711
stats.sort_stats('cum') # 'time'
712
## XXX: Might like to write to stderr or the trace file instead but
713
## print_stats seems hardcoded to stdout
714
stats.print_stats(20)
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])
762
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
763
from bzrlib.lsprof import profile
764
ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
770
trace.note('Profile data written to "%s".', filename)
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)
794
return shlex_split_unicode(alias)
799
"""Execute a command.
802
The command-line arguments, without the program name from argv[0]
803
These should already be decoded. All library/test code calling
804
run_bzr should be passing valid strings (don't need decoding).
806
Returns a command status or raises an exception.
808
Special master options: these must come before the command because
809
they control how the command is interpreted.
812
Do not load plugin modules at all
818
Only use builtin commands. (Plugins are still allowed to change
822
Run under the Python hotshot profiler.
825
Run under the Python lsprof profiler.
828
Generate line coverage report in the specified directory.
831
trace.mutter("bzr arguments: %r", argv)
833
opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
834
opt_no_aliases = False
835
opt_lsprof_file = opt_coverage_dir = None
837
# --no-plugins is handled specially at a very early stage. We need
838
# to load plugins before doing other command parsing so that they
839
# can override commands, but this needs to happen first.
847
elif a == '--lsprof':
849
elif a == '--lsprof-file':
851
opt_lsprof_file = argv[i + 1]
853
elif a == '--no-plugins':
854
opt_no_plugins = True
855
elif a == '--no-aliases':
856
opt_no_aliases = True
857
elif a == '--builtin':
859
elif a == '--coverage':
860
opt_coverage_dir = argv[i + 1]
862
elif a.startswith('-D'):
863
debug.debug_flags.add(a[2:])
868
debug.set_debug_flags_from_config()
872
from bzrlib.builtins import cmd_help
873
cmd_help().run_argv_aliases([])
876
if argv[0] == '--version':
877
from bzrlib.builtins import cmd_version
878
cmd_version().run_argv_aliases([])
881
if not opt_no_plugins:
882
from bzrlib.plugin import load_plugins
885
from bzrlib.plugin import disable_plugins
890
if not opt_no_aliases:
891
alias_argv = get_alias(argv[0])
893
user_encoding = osutils.get_user_encoding()
894
alias_argv = [a.decode(user_encoding) for a in alias_argv]
895
argv[0] = alias_argv.pop(0)
898
# We want only 'ascii' command names, but the user may have typed
899
# in a Unicode name. In that case, they should just get a
900
# 'command not found' error later.
902
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
903
run = cmd_obj.run_argv_aliases
904
run_argv = [argv, alias_argv]
907
# We can be called recursively (tests for example), but we don't want
908
# the verbosity level to propagate.
909
saved_verbosity_level = option._verbosity_level
910
option._verbosity_level = 0
914
'--coverage ignored, because --lsprof is in use.')
915
ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
919
'--coverage ignored, because --profile is in use.')
920
ret = apply_profiled(run, *run_argv)
921
elif opt_coverage_dir:
922
ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
925
if 'memory' in debug.debug_flags:
926
trace.debug_memory('Process status after command:', short=False)
929
# reset, in case we may do other commands later within the same
930
# process. Commands that want to execute sub-commands must propagate
931
# --verbose in their own way.
932
option._verbosity_level = saved_verbosity_level
935
def display_command(func):
936
"""Decorator that suppresses pipe/interrupt errors."""
937
def ignore_pipe(*args, **kwargs):
939
result = func(*args, **kwargs)
943
if getattr(e, 'errno', None) is None:
945
if e.errno != errno.EPIPE:
946
# Win32 raises IOError with errno=0 on a broken pipe
947
if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
950
except KeyboardInterrupt:
956
"""Main entry point of command-line interface.
958
:param argv: list of unicode command-line arguments similar to sys.argv.
959
argv[0] is script name usually, it will be ignored.
960
Don't pass here sys.argv because this list contains plain strings
961
and not unicode; pass None instead.
963
:return: exit code of bzr command.
966
bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
967
sys.stdin, sys.stdout, sys.stderr)
969
# Is this a final release version? If so, we should suppress warnings
970
if bzrlib.version_info[3] == 'final':
971
from bzrlib import symbol_versioning
972
symbol_versioning.suppress_deprecation_warnings(override=False)
974
argv = osutils.get_unicode_argv()
978
# ensure all arguments are unicode strings
980
if isinstance(a, unicode):
983
new_argv.append(a.decode('ascii'))
984
except UnicodeDecodeError:
985
raise errors.BzrError("argv should be list of unicode strings.")
987
ret = run_bzr_catch_errors(argv)
988
trace.mutter("return code %d", ret)
992
def run_bzr_catch_errors(argv):
993
"""Run a bzr command with parameters as described by argv.
995
This function assumed that that UI layer is setup, that symbol deprecations
996
are already applied, and that unicode decoding has already been performed on argv.
998
return exception_to_return_code(run_bzr, argv)
1001
def run_bzr_catch_user_errors(argv):
1002
"""Run bzr and report user errors, but let internal errors propagate.
1004
This is used for the test suite, and might be useful for other programs
1005
that want to wrap the commandline interface.
1008
return run_bzr(argv)
1009
except Exception, e:
1010
if (isinstance(e, (OSError, IOError))
1011
or not getattr(e, 'internal_error', True)):
1012
trace.report_exception(sys.exc_info(), sys.stderr)
1018
class HelpCommandIndex(object):
1019
"""A index for bzr help that returns commands."""
1022
self.prefix = 'commands/'
1024
def get_topics(self, topic):
1025
"""Search for topic amongst commands.
1027
:param topic: A topic to search for.
1028
:return: A list which is either empty or contains a single
1031
if topic and topic.startswith(self.prefix):
1032
topic = topic[len(self.prefix):]
1034
cmd = _get_cmd_object(topic)
1041
class Provider(object):
1042
'''Generic class to be overriden by plugins'''
1044
def plugin_for_command(self, cmd_name):
1045
'''Takes a command and returns the information for that plugin
1047
:return: A dictionary with all the available information
1048
for the requested plugin
1050
raise NotImplementedError
1053
class ProvidersRegistry(registry.Registry):
1054
'''This registry exists to allow other providers to exist'''
1057
for key, provider in self.iteritems():
1060
command_providers_registry = ProvidersRegistry()
1063
if __name__ == '__main__':
1064
sys.exit(main(sys.argv))