24
24
# Those objects can specify the expected type of the argument, which
25
25
# would help with validation and shell completion.
27
# TODO: "--profile=cum", to change sort order. Is there any value in leaving
28
# the profile output behind so it can be interactively examined?
28
# TODO: Help messages for options.
30
# TODO: Define arguments by objects, rather than just using names.
31
# Those objects can specify the expected type of the argument, which
32
# would help with validation and shell completion.
32
38
from warnings import warn
33
39
from inspect import getdoc
37
42
import bzrlib.trace
38
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
39
from bzrlib.errors import (BzrError,
44
from bzrlib.revisionspec import RevisionSpec
43
from bzrlib.trace import mutter, note, log_error, warning
44
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
45
from bzrlib.branch import find_branch
45
46
from bzrlib import BZRDIR
46
from bzrlib.option import Option
51
def register_command(cmd, decorate=False):
51
def register_command(cmd):
52
52
"Utility function to help register a command"
79
73
return cmd[4:].replace('_','-')
76
def _parse_revision_str(revstr):
77
"""This handles a revision string -> revno.
79
This always returns a list. The list will have one element for
81
It supports integers directly, but everything else it
82
defers for passing to Branch.get_revision_info()
84
>>> _parse_revision_str('234')
86
>>> _parse_revision_str('234..567')
88
>>> _parse_revision_str('..')
90
>>> _parse_revision_str('..234')
92
>>> _parse_revision_str('234..')
94
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
96
>>> _parse_revision_str('234....789') # Error?
98
>>> _parse_revision_str('revid:test@other.com-234234')
99
['revid:test@other.com-234234']
100
>>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
101
['revid:test@other.com-234234', 'revid:test@other.com-234235']
102
>>> _parse_revision_str('revid:test@other.com-234234..23')
103
['revid:test@other.com-234234', 23]
104
>>> _parse_revision_str('date:2005-04-12')
106
>>> _parse_revision_str('date:2005-04-12 12:24:33')
107
['date:2005-04-12 12:24:33']
108
>>> _parse_revision_str('date:2005-04-12T12:24:33')
109
['date:2005-04-12T12:24:33']
110
>>> _parse_revision_str('date:2005-04-12,12:24:33')
111
['date:2005-04-12,12:24:33']
112
>>> _parse_revision_str('-5..23')
114
>>> _parse_revision_str('-5')
116
>>> _parse_revision_str('123a')
118
>>> _parse_revision_str('abc')
122
old_format_re = re.compile('\d*:\d*')
123
m = old_format_re.match(revstr)
125
warning('Colon separator for revision numbers is deprecated.'
128
for rev in revstr.split(':'):
130
revs.append(int(rev))
135
for x in revstr.split('..'):
146
def get_merge_type(typestring):
147
"""Attempt to find the merge class/factory associated with a string."""
148
from merge import merge_types
150
return merge_types[typestring][0]
152
templ = '%s%%7s: %%s' % (' '*12)
153
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
154
type_list = '\n'.join(lines)
155
msg = "No known merge type %s. Supported types are:\n%s" %\
156
(typestring, type_list)
157
raise BzrCommandError(msg)
160
def get_merge_type(typestring):
161
"""Attempt to find the merge class/factory associated with a string."""
162
from merge import merge_types
164
return merge_types[typestring][0]
166
templ = '%s%%7s: %%s' % (' '*12)
167
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
168
type_list = '\n'.join(lines)
169
msg = "No known merge type %s. Supported types are:\n%s" %\
170
(typestring, type_list)
171
raise BzrCommandError(msg)
82
174
def _builtin_commands():
83
175
import bzrlib.builtins
168
260
List of argument forms, marked with whether they are optional,
173
['to_location', 'from_branch?', 'file*']
175
'to_location' is required
176
'from_branch' is optional
177
'file' can be specified 0 or more times
180
List of options that may be given for this command. These can
181
be either strings, referring to globally-defined options,
182
or option objects. Retrieve through options().
264
List of options that may be given for this command.
185
267
If true, this command isn't advertised. This is typically
186
268
for commands intended for expert users.
190
273
takes_options = []
196
279
if self.__doc__ == Command.__doc__:
197
280
warn("No help message set for %r" % self)
200
"""Return dict of valid options for this command.
202
Maps from long option name to option object."""
204
r['help'] = Option.OPTIONS['help']
205
for o in self.takes_options:
206
if not isinstance(o, Option):
207
o = Option.OPTIONS[o]
211
283
def run_argv(self, argv):
212
284
"""Parse command line and run."""
213
args, opts = parse_args(self, argv)
285
args, opts = parse_args(argv)
214
287
if 'help' in opts: # e.g. bzr add --help
215
288
from bzrlib.help import help_on_command
216
289
help_on_command(self.name())
218
# XXX: This should be handled by the parser
219
allowed_names = self.options().keys()
292
# check options are reasonable
293
allowed = self.takes_options
220
294
for oname in opts:
221
if oname not in allowed_names:
295
if oname not in allowed:
222
296
raise BzrCommandError("option '--%s' is not allowed for command %r"
223
297
% (oname, self.name()))
224
299
# mix arguments and options into one dictionary
225
300
cmdargs = _match_argform(self.name(), self.takes_args, args)
286
362
parsed = [spec, None]
289
def parse_args(command, argv):
366
# list of all available options; the rhs can be either None for an
367
# option that takes no argument, or a constructor function that checks
380
'revision': _parse_revision_str,
392
'merge-type': get_merge_type,
406
def parse_args(argv):
290
407
"""Parse command line.
292
409
Arguments and options are parsed at this level before being passed
293
410
down to specific command handlers. This routine knows, from a
294
411
lookup table, something about the available options, what optargs
295
412
they take, and which commands will accept them.
414
>>> parse_args('--help'.split())
416
>>> parse_args('help -- --invalidcmd'.split())
417
(['help', '--invalidcmd'], {})
418
>>> parse_args('--version'.split())
419
([], {'version': True})
420
>>> parse_args('status --all'.split())
421
(['status'], {'all': True})
422
>>> parse_args('commit --message=biter'.split())
423
(['commit'], {'message': u'biter'})
424
>>> parse_args('log -r 500'.split())
425
(['log'], {'revision': [500]})
426
>>> parse_args('log -r500..600'.split())
427
(['log'], {'revision': [500, 600]})
428
>>> parse_args('log -vr500..600'.split())
429
(['log'], {'verbose': True, 'revision': [500, 600]})
430
>>> parse_args('log -rv500..600'.split()) #the r takes an argument
431
(['log'], {'revision': ['v500', 600]})
297
# TODO: chop up this beast; make it a method of the Command
301
cmd_options = command.options()
309
# We've received a standalone -- No more flags
439
if not argsover and a[0] == '-':
313
440
# option names must not be unicode
317
mutter(" got option %r", a)
445
# We've received a standalone -- No more flags
448
mutter(" got option %r" % a)
319
450
optname, optarg = a[2:].split('=', 1)
322
if optname not in cmd_options:
323
raise BzrOptionError('unknown long option %r for command %s'
324
% (a, command.name()))
453
if optname not in OPTIONS:
454
raise BzrError('unknown long option %r' % a)
327
if shortopt in Option.SHORT_OPTIONS:
457
if shortopt in SHORT_OPTIONS:
328
458
# Multi-character options must have a space to delimit
330
# ^^^ what does this mean? mbp 20051014
331
optname = Option.SHORT_OPTIONS[shortopt].name
460
optname = SHORT_OPTIONS[shortopt]
333
462
# Single character short options, can be chained,
334
463
# and have their value appended to their name
335
464
shortopt = a[1:2]
336
if shortopt not in Option.SHORT_OPTIONS:
465
if shortopt not in SHORT_OPTIONS:
337
466
# We didn't find the multi-character name, and we
338
467
# didn't find the single char name
339
468
raise BzrError('unknown short option %r' % a)
340
optname = Option.SHORT_OPTIONS[shortopt].name
469
optname = SHORT_OPTIONS[shortopt]
343
472
# There are extra things on this option
344
473
# see if it is the value, or if it is another
346
optargfn = Option.OPTIONS[optname].type
475
optargfn = OPTIONS[optname]
347
476
if optargfn is None:
348
477
# This option does not take an argument, so the
349
478
# next entry is another short option, pack it back
435
562
ret = prof.runcall(the_callable, *args, **kwargs) or 0
438
567
stats = hotshot.stats.load(pfname)
440
stats.sort_stats('cum') # 'time'
569
stats.sort_stats('time')
441
570
## XXX: Might like to write to stderr or the trace file instead but
442
571
## print_stats seems hardcoded to stdout
443
572
stats.print_stats(20)
446
576
os.close(pffileno)
447
577
os.remove(pfname)
450
def apply_lsprofiled(the_callable, *args, **kwargs):
451
from bzrlib.lsprof import profile
452
ret,stats = profile(the_callable,*args,**kwargs)
457
580
def run_bzr(argv):
458
581
"""Execute a command.
526
643
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
530
ret = apply_lsprofiled(cmd_obj.run_argv, argv)
532
ret = apply_profiled(cmd_obj.run_argv, argv)
534
ret = cmd_obj.run_argv(argv)
537
# reset, in case we may do other commands later within the same process
540
def display_command(func):
541
"""Decorator that suppresses pipe/interrupt errors."""
542
def ignore_pipe(*args, **kwargs):
544
result = func(*args, **kwargs)
548
if not hasattr(e, 'errno'):
550
if e.errno != errno.EPIPE:
553
except KeyboardInterrupt:
646
ret = apply_profiled(cmd_obj.run_argv, argv)
648
ret = cmd_obj.run_argv(argv)
560
from bzrlib.ui.text import TextUIFactory
561
## bzrlib.trace.enable_default_logging()
562
654
bzrlib.trace.log_startup(argv)
563
bzrlib.ui.ui_factory = TextUIFactory()
564
ret = run_bzr_catch_errors(argv[1:])
565
mutter("return code %d", ret)
569
def run_bzr_catch_errors(argv):
655
bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
659
return run_bzr(argv[1:])
574
661
# do this here inside the exception wrappers to catch EPIPE
575
662
sys.stdout.flush()
663
except BzrCommandError, e:
664
# command line syntax error, etc
668
bzrlib.trace.log_exception()
670
except AssertionError, e:
671
bzrlib.trace.log_exception('assertion failed: ' + str(e))
673
except KeyboardInterrupt, e:
674
bzrlib.trace.note('interrupted')
576
676
except Exception, e:
577
# used to handle AssertionError and KeyboardInterrupt
578
# specially here, but hopefully they're handled ok by the logger now
580
678
if (isinstance(e, IOError)
581
679
and hasattr(e, 'errno')
582
680
and e.errno == errno.EPIPE):
583
681
bzrlib.trace.note('broken pipe')
586
684
bzrlib.trace.log_exception()
587
if os.environ.get('BZR_PDB'):
588
print '**** entering debugger'
590
pdb.post_mortem(sys.exc_traceback)
593
688
if __name__ == '__main__':
594
689
sys.exit(main(sys.argv))