1
# Copyright (C) 2004, 2005 by 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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: Help messages for options.
23
# TODO: Define arguments by objects, rather than just using names.
24
# Those objects can specify the expected type of the argument, which
25
# would help with validation and shell completion.
31
from warnings import warn
32
from inspect import getdoc
36
from bzrlib.trace import mutter, note, log_error, warning
37
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
38
from bzrlib.branch import find_branch
39
from bzrlib import BZRDIR
45
def register_command(cmd):
46
"Utility function to help register a command"
49
if k.startswith("cmd_"):
50
k_unsquished = _unsquish_command_name(k)
53
if not plugin_cmds.has_key(k_unsquished):
54
plugin_cmds[k_unsquished] = cmd
55
mutter('registered plugin command %s', k_unsquished)
57
log_error('Two plugins defined the same command: %r' % k)
58
log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
61
def _squish_command_name(cmd):
62
return 'cmd_' + cmd.replace('-', '_')
65
def _unsquish_command_name(cmd):
66
assert cmd.startswith("cmd_")
67
return cmd[4:].replace('_','-')
70
def _parse_revision_str(revstr):
71
"""This handles a revision string -> revno.
73
This always returns a list. The list will have one element for
75
It supports integers directly, but everything else it
76
defers for passing to Branch.get_revision_info()
78
>>> _parse_revision_str('234')
80
>>> _parse_revision_str('234..567')
82
>>> _parse_revision_str('..')
84
>>> _parse_revision_str('..234')
86
>>> _parse_revision_str('234..')
88
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
90
>>> _parse_revision_str('234....789') # Error?
92
>>> _parse_revision_str('revid:test@other.com-234234')
93
['revid:test@other.com-234234']
94
>>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
95
['revid:test@other.com-234234', 'revid:test@other.com-234235']
96
>>> _parse_revision_str('revid:test@other.com-234234..23')
97
['revid:test@other.com-234234', 23]
98
>>> _parse_revision_str('date:2005-04-12')
100
>>> _parse_revision_str('date:2005-04-12 12:24:33')
101
['date:2005-04-12 12:24:33']
102
>>> _parse_revision_str('date:2005-04-12T12:24:33')
103
['date:2005-04-12T12:24:33']
104
>>> _parse_revision_str('date:2005-04-12,12:24:33')
105
['date:2005-04-12,12:24:33']
106
>>> _parse_revision_str('-5..23')
108
>>> _parse_revision_str('-5')
110
>>> _parse_revision_str('123a')
112
>>> _parse_revision_str('abc')
116
old_format_re = re.compile('\d*:\d*')
117
m = old_format_re.match(revstr)
119
warning('Colon separator for revision numbers is deprecated.'
122
for rev in revstr.split(':'):
124
revs.append(int(rev))
129
for x in revstr.split('..'):
140
def get_merge_type(typestring):
141
"""Attempt to find the merge class/factory associated with a string."""
142
from merge import merge_types
144
return merge_types[typestring][0]
146
templ = '%s%%7s: %%s' % (' '*12)
147
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
148
type_list = '\n'.join(lines)
149
msg = "No known merge type %s. Supported types are:\n%s" %\
150
(typestring, type_list)
151
raise BzrCommandError(msg)
154
def get_merge_type(typestring):
155
"""Attempt to find the merge class/factory associated with a string."""
156
from merge import merge_types
158
return merge_types[typestring][0]
160
templ = '%s%%7s: %%s' % (' '*12)
161
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
162
type_list = '\n'.join(lines)
163
msg = "No known merge type %s. Supported types are:\n%s" %\
164
(typestring, type_list)
165
raise BzrCommandError(msg)
168
def _builtin_commands():
169
import bzrlib.builtins
171
builtins = bzrlib.builtins.__dict__
172
for name in builtins:
173
if name.startswith("cmd_"):
174
real_name = _unsquish_command_name(name)
175
r[real_name] = builtins[name]
180
def builtin_command_names():
181
"""Return list of builtin command names."""
182
return _builtin_commands().keys()
185
def plugin_command_names():
186
return plugin_cmds.keys()
189
def _get_cmd_dict(plugins_override=True):
190
"""Return name->class mapping for all commands."""
191
d = _builtin_commands()
193
d.update(plugin_cmds)
197
def get_all_cmds(plugins_override=True):
198
"""Return canonical name and class for all registered commands."""
199
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
203
def get_cmd_object(cmd_name, plugins_override=True):
204
"""Return the canonical name and command class for a command.
207
If true, plugin commands can override builtins.
209
cmd_name = str(cmd_name) # not unicode
211
# first look up this command under the specified name
212
cmds = _get_cmd_dict(plugins_override=plugins_override)
214
return cmds[cmd_name]()
218
# look for any command which claims this as an alias
219
for real_cmd_name, cmd_class in cmds.iteritems():
220
if cmd_name in cmd_class.aliases:
223
cmd_obj = ExternalCommand.find_command(cmd_name)
227
raise BzrCommandError("unknown command %r" % cmd_name)
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,
256
List of options that may be given for this command.
259
If true, this command isn't advertised. This is typically
260
for commands intended for expert users.
270
"""Construct an instance of this command."""
271
if self.__doc__ == Command.__doc__:
272
warn("No help message set for %r" % self)
276
"""Actually run the command.
278
This is invoked with the options and arguments bound to
281
Return 0 or None if the command was successful, or a non-zero
282
shell error code if not. It's OK for this method to allow
283
an exception to raise up.
285
raise NotImplementedError()
289
"""Return help message for this class."""
290
if self.__doc__ is Command.__doc__:
295
return _unsquish_command_name(self.__class__.__name__)
298
class ExternalCommand(Command):
299
"""Class to wrap external commands.
301
We cheat a little here, when get_cmd_class() calls us we actually
302
give it back an object we construct that has the appropriate path,
303
help, options etc for the specified command.
305
When run_bzr() tries to instantiate that 'class' it gets caught by
306
the __call__ method, which we override to call the Command.__init__
307
method. That then calls our run method which is pretty straight
310
The only wrinkle is that we have to map bzr's dictionary of options
311
and arguments back into command line options and arguments for the
315
def find_command(cls, cmd):
317
bzrpath = os.environ.get('BZRPATH', '')
319
for dir in bzrpath.split(os.pathsep):
320
path = os.path.join(dir, cmd)
321
if os.path.isfile(path):
322
return ExternalCommand(path)
326
find_command = classmethod(find_command)
328
def __init__(self, path):
331
pipe = os.popen('%s --bzr-usage' % path, 'r')
332
self.takes_options = pipe.readline().split()
334
for opt in self.takes_options:
335
if not opt in OPTIONS:
336
raise BzrError("Unknown option '%s' returned by external command %s"
339
# TODO: Is there any way to check takes_args is valid here?
340
self.takes_args = pipe.readline().split()
342
if pipe.close() is not None:
343
raise BzrError("Failed funning '%s --bzr-usage'" % path)
345
pipe = os.popen('%s --bzr-help' % path, 'r')
346
self.__doc__ = pipe.read()
347
if pipe.close() is not None:
348
raise BzrError("Failed funning '%s --bzr-help'" % path)
350
def __call__(self, options, arguments):
351
Command.__init__(self, options, arguments)
355
raise NotImplementedError()
357
def run(self, **kargs):
358
raise NotImplementedError()
366
optname = name.replace('_','-')
368
if OPTIONS.has_key(optname):
370
opts.append('--%s' % optname)
371
if value is not None and value is not True:
372
opts.append(str(value))
374
# it's an arg, or arg list
375
if type(value) is not list:
381
self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
386
def parse_spec(spec):
392
>>> parse_spec("../@")
394
>>> parse_spec("../f/@35")
396
>>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
397
['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
402
parsed = spec.split('/@')
403
assert len(parsed) == 2
408
parsed[1] = int(parsed[1])
410
pass # We can allow stuff like ./@revid:blahblahblah
414
parsed = [spec, None]
420
# list of all available options; the rhs can be either None for an
421
# option that takes no argument, or a constructor function that checks
434
'revision': _parse_revision_str,
446
'merge-type': get_merge_type,
460
def parse_args(argv):
461
"""Parse command line.
463
Arguments and options are parsed at this level before being passed
464
down to specific command handlers. This routine knows, from a
465
lookup table, something about the available options, what optargs
466
they take, and which commands will accept them.
468
>>> parse_args('--help'.split())
470
>>> parse_args('help -- --invalidcmd'.split())
471
(['help', '--invalidcmd'], {})
472
>>> parse_args('--version'.split())
473
([], {'version': True})
474
>>> parse_args('status --all'.split())
475
(['status'], {'all': True})
476
>>> parse_args('commit --message=biter'.split())
477
(['commit'], {'message': u'biter'})
478
>>> parse_args('log -r 500'.split())
479
(['log'], {'revision': [500]})
480
>>> parse_args('log -r500..600'.split())
481
(['log'], {'revision': [500, 600]})
482
>>> parse_args('log -vr500..600'.split())
483
(['log'], {'verbose': True, 'revision': [500, 600]})
484
>>> parse_args('log -rv500..600'.split()) #the r takes an argument
485
(['log'], {'revision': ['v500', 600]})
493
if not argsover and a[0] == '-':
494
# option names must not be unicode
499
# We've received a standalone -- No more flags
502
mutter(" got option %r" % a)
504
optname, optarg = a[2:].split('=', 1)
507
if optname not in OPTIONS:
508
raise BzrError('unknown long option %r' % a)
511
if shortopt in SHORT_OPTIONS:
512
# Multi-character options must have a space to delimit
514
optname = SHORT_OPTIONS[shortopt]
516
# Single character short options, can be chained,
517
# and have their value appended to their name
519
if shortopt not in SHORT_OPTIONS:
520
# We didn't find the multi-character name, and we
521
# didn't find the single char name
522
raise BzrError('unknown short option %r' % a)
523
optname = SHORT_OPTIONS[shortopt]
526
# There are extra things on this option
527
# see if it is the value, or if it is another
529
optargfn = OPTIONS[optname]
531
# This option does not take an argument, so the
532
# next entry is another short option, pack it back
534
argv.insert(0, '-' + a[2:])
536
# This option takes an argument, so pack it
541
# XXX: Do we ever want to support this, e.g. for -r?
542
raise BzrError('repeated option %r' % a)
544
optargfn = OPTIONS[optname]
548
raise BzrError('option %r needs an argument' % a)
551
opts[optname] = optargfn(optarg)
554
raise BzrError('option %r takes no argument' % optname)
564
def _match_argform(cmd, takes_args, args):
567
# step through args and takes_args, allowing appropriate 0-many matches
568
for ap in takes_args:
572
argdict[argname] = args.pop(0)
573
elif ap[-1] == '*': # all remaining arguments
575
argdict[argname + '_list'] = args[:]
578
argdict[argname + '_list'] = None
581
raise BzrCommandError("command %r needs one or more %s"
582
% (cmd, argname.upper()))
584
argdict[argname + '_list'] = args[:]
586
elif ap[-1] == '$': # all but one
588
raise BzrCommandError("command %r needs one or more %s"
589
% (cmd, argname.upper()))
590
argdict[argname + '_list'] = args[:-1]
596
raise BzrCommandError("command %r requires argument %s"
597
% (cmd, argname.upper()))
599
argdict[argname] = args.pop(0)
602
raise BzrCommandError("extra argument to command %s: %s"
609
def apply_profiled(the_callable, *args, **kwargs):
612
pffileno, pfname = tempfile.mkstemp()
614
prof = hotshot.Profile(pfname)
616
ret = prof.runcall(the_callable, *args, **kwargs) or 0
621
stats = hotshot.stats.load(pfname)
623
stats.sort_stats('time')
624
## XXX: Might like to write to stderr or the trace file instead but
625
## print_stats seems hardcoded to stdout
626
stats.print_stats(20)
635
"""Execute a command.
637
This is similar to main(), but without all the trappings for
638
logging and error handling.
641
The command-line arguments, without the program name from argv[0]
643
Returns a command status or raises an exception.
645
Special master options: these must come before the command because
646
they control how the command is interpreted.
649
Do not load plugin modules at all
652
Only use builtin commands. (Plugins are still allowed to change
656
Run under the Python profiler.
659
argv = [a.decode(bzrlib.user_encoding) for a in argv]
661
opt_profile = opt_no_plugins = opt_builtin = False
663
# --no-plugins is handled specially at a very early stage. We need
664
# to load plugins before doing other command parsing so that they
665
# can override commands, but this needs to happen first.
670
elif a == '--no-plugins':
671
opt_no_plugins = True
672
elif a == '--builtin':
678
if not opt_no_plugins:
679
from bzrlib.plugin import load_plugins
682
args, opts = parse_args(argv)
685
from bzrlib.help import help
692
if 'version' in opts:
693
from bzrlib.builtins import show_version
698
from bzrlib.help import help
702
cmd = str(args.pop(0))
704
cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
706
# check options are reasonable
707
allowed = cmd_obj.takes_options
709
if oname not in allowed:
710
raise BzrCommandError("option '--%s' is not allowed for command %r"
713
# mix arguments and options into one dictionary
714
cmdargs = _match_argform(cmd, cmd_obj.takes_args, args)
716
for k, v in opts.items():
717
cmdopts[k.replace('-', '_')] = v
719
all_cmd_args = cmdargs.copy()
720
all_cmd_args.update(cmdopts)
723
ret = apply_profiled(cmd_obj.run, **all_cmd_args)
725
ret = cmd_obj.run(**all_cmd_args)
734
bzrlib.trace.log_startup(argv)
735
bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
739
return run_bzr(argv[1:])
741
# do this here inside the exception wrappers to catch EPIPE
743
except BzrCommandError, e:
744
# command line syntax error, etc
748
bzrlib.trace.log_exception()
750
except AssertionError, e:
751
bzrlib.trace.log_exception('assertion failed: ' + str(e))
753
except KeyboardInterrupt, e:
754
bzrlib.trace.note('interrupted')
758
if (isinstance(e, IOError)
759
and hasattr(e, 'errno')
760
and e.errno == errno.EPIPE):
761
bzrlib.trace.note('broken pipe')
764
bzrlib.trace.log_exception()
768
if __name__ == '__main__':
769
sys.exit(main(sys.argv))