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?
33
34
from warnings import warn
38
import bzrlib.errors as errors
37
39
from bzrlib.errors import (BzrError,
43
from bzrlib import option
42
44
from bzrlib.option import Option
43
from bzrlib.revisionspec import RevisionSpec
44
from bzrlib.symbol_versioning import *
46
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
45
47
import bzrlib.trace
46
48
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
128
130
from bzrlib.externalcommand import ExternalCommand
130
cmd_name = str(cmd_name) # not unicode
132
# We want only 'ascii' command names, but the user may have typed
133
# in a Unicode name. In that case, they should just get a
134
# 'command not found' error later.
135
# In the future, we may actually support Unicode command names.
132
137
# first look up this command under the specified name
133
138
cmds = _get_cmd_dict(plugins_override=plugins_override)
190
195
If true, this command isn't advertised. This is typically
191
196
for commands intended for expert users.
199
Command objects will get a 'outf' attribute, which has been
200
setup to properly handle encoding of unicode strings.
201
encoding_type determines what will happen when characters cannot
203
strict - abort if we cannot decode
204
replace - put in a bogus character (typically '?')
205
exact - do not encode sys.stdout
195
210
takes_options = []
211
encoding_type = 'strict'
209
225
r['help'] = Option.OPTIONS['help']
210
226
for o in self.takes_options:
211
if not isinstance(o, Option):
227
if isinstance(o, basestring):
212
228
o = Option.OPTIONS[o]
232
def _setup_outf(self):
233
"""Return a file linked to stdout, which has proper encoding."""
234
assert self.encoding_type in ['strict', 'exact', 'replace']
236
# Originally I was using self.stdout, but that looks
237
# *way* too much like sys.stdout
238
if self.encoding_type == 'exact':
239
self.outf = sys.stdout
242
output_encoding = bzrlib.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)
247
# For whatever reason codecs.getwriter() does not advertise its encoding
248
# it just returns the encoding of the wrapped file, which is completely
249
# bogus. So set the attribute, so we can find the correct encoding later.
250
self.outf.encoding = output_encoding
216
252
@deprecated_method(zero_eight)
217
253
def run_argv(self, argv):
218
254
"""Parse command line and run.
224
260
def run_argv_aliases(self, argv, alias_argv=None):
225
261
"""Parse the command line and run with extra aliases in alias_argv."""
263
warn("Passing None for [] is deprecated from bzrlib 0.10",
264
DeprecationWarning, stacklevel=2)
226
266
args, opts = parse_args(self, argv, alias_argv)
227
267
if 'help' in opts: # e.g. bzr add --help
228
268
from bzrlib.help import help_on_command
229
269
help_on_command(self.name())
231
# XXX: This should be handled by the parser
232
allowed_names = self.options().keys()
234
if oname not in allowed_names:
235
raise BzrCommandError("option '--%s' is not allowed for"
236
" command %r" % (oname, self.name()))
237
271
# mix arguments and options into one dictionary
238
272
cmdargs = _match_argform(self.name(), self.takes_args, args)
308
355
lookup table, something about the available options, what optargs
309
356
they take, and which commands will accept them.
311
# TODO: chop up this beast; make it a method of the Command
316
cmd_options = command.options()
318
proc_aliasarg = True # Are we processing alias_argv now?
319
for proc_argv in alias_argv, argv:
326
# We've received a standalone -- No more flags
330
# option names must not be unicode
334
mutter(" got option %r", a)
336
optname, optarg = a[2:].split('=', 1)
339
if optname not in cmd_options:
340
raise BzrOptionError('unknown long option %r for'
345
if shortopt in Option.SHORT_OPTIONS:
346
# Multi-character options must have a space to delimit
348
# ^^^ what does this mean? mbp 20051014
349
optname = Option.SHORT_OPTIONS[shortopt].name
351
# Single character short options, can be chained,
352
# and have their value appended to their name
354
if shortopt not in Option.SHORT_OPTIONS:
355
# We didn't find the multi-character name, and we
356
# didn't find the single char name
357
raise BzrError('unknown short option %r' % a)
358
optname = Option.SHORT_OPTIONS[shortopt].name
361
# There are extra things on this option
362
# see if it is the value, or if it is another
364
optargfn = Option.OPTIONS[optname].type
366
# This option does not take an argument, so the
367
# next entry is another short option, pack it
369
proc_argv.insert(0, '-' + a[2:])
371
# This option takes an argument, so pack it
375
if optname not in cmd_options:
376
raise BzrOptionError('unknown short option %r for'
378
(shortopt, command.name()))
380
# XXX: Do we ever want to support this, e.g. for -r?
382
raise BzrError('repeated option %r' % a)
383
elif optname in alias_opts:
384
# Replace what's in the alias with what's in the real
386
del alias_opts[optname]
388
proc_argv.insert(0, a)
391
raise BzrError('repeated option %r' % a)
393
option_obj = cmd_options[optname]
394
optargfn = option_obj.type
398
raise BzrError('option %r needs an argument' % a)
400
optarg = proc_argv.pop(0)
401
opts[optname] = optargfn(optarg)
403
alias_opts[optname] = optargfn(optarg)
406
raise BzrError('option %r takes no argument' % optname)
409
alias_opts[optname] = True
412
proc_aliasarg = False # Done with alias argv
358
# TODO: make it a method of the Command?
359
parser = option.get_optparser(command.options())
360
if alias_argv is not None:
361
args = alias_argv + argv
365
options, args = parser.parse_args(args)
366
opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
367
v is not option.OptionParser.DEFAULT_VALUE])
413
368
return args, opts
593
551
alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
594
552
argv[0] = alias_argv.pop(0)
596
cmd = str(argv.pop(0))
555
# We want only 'ascii' command names, but the user may have typed
556
# in a Unicode name. In that case, they should just get a
557
# 'command not found' error later.
598
559
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
599
560
if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
638
601
from bzrlib.ui.text import TextUIFactory
639
## bzrlib.trace.enable_default_logging()
640
bzrlib.trace.log_startup(argv)
641
602
bzrlib.ui.ui_factory = TextUIFactory()
642
ret = run_bzr_catch_errors(argv[1:])
603
argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
604
ret = run_bzr_catch_errors(argv)
643
605
mutter("return code %d", ret)
647
609
def run_bzr_catch_errors(argv):
652
# do this here inside the exception wrappers to catch EPIPE
612
# do this here inside the exception wrappers to catch EPIPE
614
except (KeyboardInterrupt, Exception), e:
655
615
# used to handle AssertionError and KeyboardInterrupt
656
616
# specially here, but hopefully they're handled ok by the logger now
658
if (isinstance(e, IOError)
659
and hasattr(e, 'errno')
660
and e.errno == errno.EPIPE):
661
bzrlib.trace.note('broken pipe')
664
bzrlib.trace.log_exception()
665
if os.environ.get('BZR_PDB'):
666
print '**** entering debugger'
668
pdb.post_mortem(sys.exc_traceback)
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)
671
624
if __name__ == '__main__':
672
625
sys.exit(main(sys.argv))