1
# Copyright (C) 2006 Canonical Ltd
1
# Copyright (C) 2004, 2005 by Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
18
# TODO: probably should say which arguments are candidates for glob
19
19
# expansion on windows and do that at the command level.
21
# TODO: Help messages for options.
21
23
# TODO: Define arguments by objects, rather than just using names.
22
24
# 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.
25
# would help with validation and shell completion.
28
27
# TODO: "--profile=cum", to change sort order. Is there any value in leaving
29
28
# the profile output behind so it can be interactively examined?
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
32
from warnings import warn
33
from inspect import getdoc
38
from warnings import warn
50
from bzrlib.symbol_versioning import (
38
from bzrlib.trace import mutter, note, log_error, warning
39
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
40
from bzrlib.revisionspec import RevisionSpec
41
from bzrlib import BZRDIR
57
42
from bzrlib.option import Option
63
47
def register_command(cmd, decorate=False):
64
"""Utility function to help register a command
66
:param cmd: Command subclass to register
67
:param decorate: If true, allow overriding an existing command
68
of the same name; the old command is returned by this function.
69
Otherwise it is an error to try to override an existing command.
48
"Utility function to help register a command"
73
51
if k.startswith("cmd_"):
74
52
k_unsquished = _unsquish_command_name(k)
77
if k_unsquished not in plugin_cmds:
55
if not plugin_cmds.has_key(k_unsquished):
78
56
plugin_cmds[k_unsquished] = cmd
79
## trace.mutter('registered plugin command %s', k_unsquished)
57
mutter('registered plugin command %s', k_unsquished)
80
58
if decorate and k_unsquished in builtin_command_names():
81
59
return _builtin_commands()[k_unsquished]
239
190
Maps from long option name to option object."""
241
r['help'] = option.Option.OPTIONS['help']
192
r['help'] = Option.OPTIONS['help']
242
193
for o in self.takes_options:
243
if isinstance(o, basestring):
244
o = option.Option.OPTIONS[o]
194
if not isinstance(o, Option):
195
o = Option.OPTIONS[o]
248
def _setup_outf(self):
249
"""Return a file linked to stdout, which has proper encoding."""
250
assert self.encoding_type in ['strict', 'exact', 'replace']
252
# Originally I was using self.stdout, but that looks
253
# *way* too much like sys.stdout
254
if self.encoding_type == 'exact':
255
# force sys.stdout to be binary stream on win32
256
if sys.platform == 'win32':
257
fileno = getattr(sys.stdout, 'fileno', None)
260
msvcrt.setmode(fileno(), os.O_BINARY)
261
self.outf = sys.stdout
264
output_encoding = osutils.get_terminal_encoding()
266
# use 'replace' so that we don't abort if trying to write out
267
# in e.g. the default C locale.
268
self.outf = codecs.getwriter(output_encoding)(sys.stdout, errors=self.encoding_type)
269
# For whatever reason codecs.getwriter() does not advertise its encoding
270
# it just returns the encoding of the wrapped file, which is completely
271
# bogus. So set the attribute, so we can find the correct encoding later.
272
self.outf.encoding = output_encoding
274
@deprecated_method(zero_eight)
275
199
def run_argv(self, argv):
276
"""Parse command line and run.
278
See run_argv_aliases for the 0.8 and beyond api.
280
return self.run_argv_aliases(argv)
282
def run_argv_aliases(self, argv, alias_argv=None):
283
"""Parse the command line and run with extra aliases in alias_argv."""
285
warn("Passing None for [] is deprecated from bzrlib 0.10",
286
DeprecationWarning, stacklevel=2)
288
args, opts = parse_args(self, argv, alias_argv)
200
"""Parse command line and run."""
201
args, opts = parse_args(self, argv)
289
202
if 'help' in opts: # e.g. bzr add --help
290
203
from bzrlib.help import help_on_command
291
204
help_on_command(self.name())
206
# XXX: This should be handled by the parser
207
allowed_names = self.options().keys()
209
if oname not in allowed_names:
210
raise BzrCommandError("option '--%s' is not allowed for command %r"
211
% (oname, self.name()))
293
212
# mix arguments and options into one dictionary
294
213
cmdargs = _match_argform(self.name(), self.takes_args, args)
380
282
lookup table, something about the available options, what optargs
381
283
they take, and which commands will accept them.
383
# TODO: make it a method of the Command?
384
parser = option.get_optparser(command.options())
385
if alias_argv is not None:
386
args = alias_argv + argv
390
options, args = parser.parse_args(args)
391
opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
392
v is not option.OptionParser.DEFAULT_VALUE])
285
# TODO: chop up this beast; make it a method of the Command
289
cmd_options = command.options()
297
# We've received a standalone -- No more flags
301
# option names must not be unicode
305
mutter(" got option %r" % a)
307
optname, optarg = a[2:].split('=', 1)
310
if optname not in cmd_options:
311
raise BzrCommandError('unknown long option %r for command %s'
312
% (a, command.name()))
315
if shortopt in Option.SHORT_OPTIONS:
316
# Multi-character options must have a space to delimit
318
# ^^^ what does this mean? mbp 20051014
319
optname = Option.SHORT_OPTIONS[shortopt].name
321
# Single character short options, can be chained,
322
# and have their value appended to their name
324
if shortopt not in Option.SHORT_OPTIONS:
325
# We didn't find the multi-character name, and we
326
# didn't find the single char name
327
raise BzrError('unknown short option %r' % a)
328
optname = Option.SHORT_OPTIONS[shortopt].name
331
# There are extra things on this option
332
# see if it is the value, or if it is another
334
optargfn = Option.OPTIONS[optname].type
336
# This option does not take an argument, so the
337
# next entry is another short option, pack it back
339
argv.insert(0, '-' + a[2:])
341
# This option takes an argument, so pack it
346
# XXX: Do we ever want to support this, e.g. for -r?
347
raise BzrError('repeated option %r' % a)
349
option_obj = cmd_options[optname]
350
optargfn = option_obj.type
354
raise BzrError('option %r needs an argument' % a)
357
opts[optname] = optargfn(optarg)
360
raise BzrError('option %r takes no argument' % optname)
393
364
return args, opts
410
381
argdict[argname + '_list'] = None
411
382
elif ap[-1] == '+':
413
raise errors.BzrCommandError("command %r needs one or more %s"
414
% (cmd, argname.upper()))
384
raise BzrCommandError("command %r needs one or more %s"
385
% (cmd, argname.upper()))
416
387
argdict[argname + '_list'] = args[:]
418
389
elif ap[-1] == '$': # all but one
419
390
if len(args) < 2:
420
raise errors.BzrCommandError("command %r needs one or more %s"
421
% (cmd, argname.upper()))
391
raise BzrCommandError("command %r needs one or more %s"
392
% (cmd, argname.upper()))
422
393
argdict[argname + '_list'] = args[:-1]
425
396
# just a plain arg
428
raise errors.BzrCommandError("command %r requires argument %s"
429
% (cmd, argname.upper()))
399
raise BzrCommandError("command %r requires argument %s"
400
% (cmd, argname.upper()))
431
402
argdict[argname] = args.pop(0)
434
raise errors.BzrCommandError("extra argument to command %s: %s"
405
raise BzrCommandError("extra argument to command %s: %s"
461
432
os.remove(pfname)
464
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
465
from bzrlib.lsprof import profile
467
ret, stats = profile(the_callable, *args, **kwargs)
473
cPickle.dump(stats, open(filename, 'w'), 2)
474
print 'Profile data written to %r.' % filename
478
def get_alias(cmd, config=None):
479
"""Return an expanded alias, or None if no alias exists.
482
Command to be checked for an alias.
484
Used to specify an alternative config to use,
485
which is especially useful for testing.
486
If it is unspecified, the global config will be used.
490
config = bzrlib.config.GlobalConfig()
491
alias = config.get_alias(cmd)
494
return [a.decode('utf-8') for a in shlex.split(alias.encode('utf-8'))]
498
435
def run_bzr(argv):
499
436
"""Execute a command.
515
450
Do not load plugin modules at all
521
453
Only use builtin commands. (Plugins are still allowed to change
522
454
other behaviour.)
525
Run under the Python hotshot profiler.
528
Run under the Python lsprof profiler.
457
Run under the Python profiler.
531
trace.mutter("bzr arguments: %r", argv)
459
argv = [a.decode(bzrlib.user_encoding) for a in argv]
533
opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
534
opt_no_aliases = False
535
opt_lsprof_file = None
461
opt_profile = opt_no_plugins = opt_builtin = False
537
463
# --no-plugins is handled specially at a very early stage. We need
538
464
# to load plugins before doing other command parsing so that they
539
465
# can override commands, but this needs to happen first.
545
468
if a == '--profile':
546
469
opt_profile = True
547
elif a == '--lsprof':
549
elif a == '--lsprof-file':
551
opt_lsprof_file = argv[i + 1]
553
470
elif a == '--no-plugins':
554
471
opt_no_plugins = True
555
elif a == '--no-aliases':
556
opt_no_aliases = True
557
472
elif a == '--builtin':
558
473
opt_builtin = True
559
elif a in ('--quiet', '-q'):
561
elif a.startswith('-D'):
562
debug.debug_flags.add(a[2:])
569
from bzrlib.builtins import cmd_help
570
cmd_help().run_argv_aliases([])
478
if (not argv) or (argv[0] == '--help'):
479
from bzrlib.help import help
573
486
if argv[0] == '--version':
574
from bzrlib.version import show_version
487
from bzrlib.builtins import show_version
578
491
if not opt_no_plugins:
579
492
from bzrlib.plugin import load_plugins
582
from bzrlib.plugin import disable_plugins
587
if not opt_no_aliases:
588
alias_argv = get_alias(argv[0])
590
alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
591
argv[0] = alias_argv.pop(0)
594
# We want only 'ascii' command names, but the user may have typed
595
# in a Unicode name. In that case, they should just get a
596
# 'command not found' error later.
495
cmd = str(argv.pop(0))
598
497
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
599
if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
600
run = cmd_obj.run_argv
500
ret = apply_profiled(cmd_obj.run_argv, argv)
603
run = cmd_obj.run_argv_aliases
604
run_argv = [argv, alias_argv]
608
ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
610
ret = apply_profiled(run, *run_argv)
615
# reset, in case we may do other commands later within the same process
616
trace.be_quiet(False)
502
ret = cmd_obj.run_argv(argv)
618
505
def display_command(func):
619
"""Decorator that suppresses pipe/interrupt errors."""
620
506
def ignore_pipe(*args, **kwargs):
622
result = func(*args, **kwargs)
508
return func(*args, **kwargs)
625
509
except IOError, e:
626
if getattr(e, 'errno', None) is None:
510
if e.errno != errno.EPIPE:
628
if e.errno != errno.EPIPE:
629
# Win32 raises IOError with errno=0 on a broken pipe
630
if sys.platform != 'win32' or e.errno != 0:
633
512
except KeyboardInterrupt:
635
514
return ignore_pipe
640
from bzrlib.ui.text import TextUIFactory
641
bzrlib.ui.ui_factory = TextUIFactory()
642
argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
643
ret = run_bzr_catch_errors(argv)
644
trace.mutter("return code %d", ret)
518
bzrlib.trace.log_startup(argv)
519
bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
521
return run_bzr_catch_errors(argv[1:])
648
524
def run_bzr_catch_errors(argv):
651
# do this here inside the exception wrappers to catch EPIPE
653
except (KeyboardInterrupt, Exception), e:
654
# used to handle AssertionError and KeyboardInterrupt
655
# specially here, but hopefully they're handled ok by the logger now
656
trace.report_exception(sys.exc_info(), sys.stderr)
657
if os.environ.get('BZR_PDB'):
658
print '**** entering debugger'
660
pdb.post_mortem(sys.exc_traceback)
529
# do this here inside the exception wrappers to catch EPIPE
531
except BzrCommandError, e:
532
# command line syntax error, etc
536
bzrlib.trace.log_exception()
538
except AssertionError, e:
539
bzrlib.trace.log_exception('assertion failed: ' + str(e))
541
except KeyboardInterrupt, e:
542
bzrlib.trace.log_exception('interrupted')
546
if (isinstance(e, IOError)
547
and hasattr(e, 'errno')
548
and e.errno == errno.EPIPE):
549
bzrlib.trace.note('broken pipe')
554
bzrlib.trace.log_exception()
663
557
if __name__ == '__main__':
664
558
sys.exit(main(sys.argv))