22
22
from bzrlib.trace import mutter, note, log_error
23
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
23
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
24
24
from bzrlib.osutils import quotefn
25
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
32
def register_command(cmd):
33
"Utility function to help register a command"
36
if k.startswith("cmd_"):
37
k_unsquished = _unsquish_command_name(k)
40
if not plugin_cmds.has_key(k_unsquished):
41
plugin_cmds[k_unsquished] = cmd
43
log_error('Two plugins defined the same command: %r' % k)
44
log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
47
29
def _squish_command_name(cmd):
48
30
return 'cmd_' + cmd.replace('-', '_')
91
def _get_cmd_dict(plugins_override=True):
72
"""Return canonical name and class for all registered commands."""
93
73
for k, v in globals().iteritems():
94
74
if k.startswith("cmd_"):
95
d[_unsquish_command_name(k)] = v
96
# If we didn't load plugins, the plugin_cmds dict will be empty
100
d2 = plugin_cmds.copy()
106
def get_all_cmds(plugins_override=True):
107
"""Return canonical name and class for all registered commands."""
108
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
112
def get_cmd_class(cmd, plugins_override=True):
75
yield _unsquish_command_name(k), v
77
def get_cmd_class(cmd):
113
78
"""Return the canonical name and command class for a command.
115
80
cmd = str(cmd) # not unicode
117
82
# first look up this command under the specified name
118
cmds = _get_cmd_dict(plugins_override=plugins_override)
120
return cmd, cmds[cmd]
84
return cmd, globals()[_squish_command_name(cmd)]
124
88
# look for any command which claims this as an alias
125
for cmdname, cmdclass in cmds.iteritems():
89
for cmdname, cmdclass in get_all_cmds():
126
90
if cmd in cmdclass.aliases:
127
91
return cmdname, cmdclass
213
177
def __init__(self, path):
180
# TODO: If either of these fail, we should detect that and
181
# assume that path is not really a bzr plugin after all.
216
183
pipe = os.popen('%s --bzr-usage' % path, 'r')
217
184
self.takes_options = pipe.readline().split()
219
for opt in self.takes_options:
220
if not opt in OPTIONS:
221
raise BzrError("Unknown option '%s' returned by external command %s"
224
# TODO: Is there any way to check takes_args is valid here?
225
185
self.takes_args = pipe.readline().split()
227
if pipe.close() is not None:
228
raise BzrError("Failed funning '%s --bzr-usage'" % path)
230
188
pipe = os.popen('%s --bzr-help' % path, 'r')
231
189
self.__doc__ = pipe.read()
232
if pipe.close() is not None:
233
raise BzrError("Failed funning '%s --bzr-help'" % path)
235
192
def __call__(self, options, arguments):
236
193
Command.__init__(self, options, arguments)
454
class cmd_pull(Command):
455
"""Pull any changes from another branch into the current one.
457
If the location is omitted, the last-used location will be used.
458
Both the revision history and the working directory will be
461
This command only works on branches that have not diverged. Branches are
462
considered diverged if both branches have had commits without first
463
pulling from the other.
465
If branches have diverged, you can use 'bzr merge' to pull the text changes
466
from one into the other.
468
takes_args = ['location?']
470
def run(self, location=None):
471
from bzrlib.merge import merge
477
stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
479
if errno == errno.ENOENT:
482
if stored_loc is None:
483
raise BzrCommandError("No pull location known or specified.")
485
print "Using last location: %s" % stored_loc
486
location = stored_loc
487
from branch import find_branch, DivergedBranches
488
br_from = find_branch(location)
489
location = pull_loc(br_from)
490
old_revno = br_to.revno()
492
br_to.update_revisions(br_from)
493
except DivergedBranches:
494
raise BzrCommandError("These branches have diverged. Try merge.")
496
merge(('.', -1), ('.', old_revno), check_clean=False)
497
if location != stored_loc:
498
br_to.controlfile("x-pull", "wb").write(location + "\n")
502
class cmd_branch(Command):
503
"""Create a new copy of a branch.
505
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
506
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
508
To retrieve the branch as of a particular revision, supply the --revision
509
parameter, as in "branch foo/bar -r 5".
511
takes_args = ['from_location', 'to_location?']
512
takes_options = ['revision']
514
def run(self, from_location, to_location=None, revision=None):
516
from bzrlib.merge import merge
517
from branch import find_branch, DivergedBranches, NoSuchRevision
518
from shutil import rmtree
520
br_from = find_branch(from_location)
522
if e.errno == errno.ENOENT:
523
raise BzrCommandError('Source location "%s" does not exist.' %
528
if to_location is None:
529
to_location = os.path.basename(from_location.rstrip("/\\"))
532
os.mkdir(to_location)
534
if e.errno == errno.EEXIST:
535
raise BzrCommandError('Target directory "%s" already exists.' %
537
if e.errno == errno.ENOENT:
538
raise BzrCommandError('Parent of "%s" does not exist.' %
542
br_to = Branch(to_location, init=True)
545
br_to.update_revisions(br_from, stop_revision=revision)
546
except NoSuchRevision:
548
msg = "The branch %s has no revision %d." % (from_location,
550
raise BzrCommandError(msg)
551
merge((to_location, -1), (to_location, 0), this_dir=to_location,
552
check_clean=False, ignore_zero=True)
553
from_location = pull_loc(br_from)
554
br_to.controlfile("x-pull", "wb").write(from_location + "\n")
557
def pull_loc(branch):
558
# TODO: Should perhaps just make attribute be 'base' in
559
# RemoteBranch and Branch?
560
if hasattr(branch, "baseurl"):
561
return branch.baseurl
567
387
class cmd_renames(Command):
568
388
"""Show list of renamed files.
1014
834
class cmd_export(Command):
1015
835
"""Export past revision to destination directory.
1017
If no revision is specified this exports the last committed revision.
1019
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1020
given, exports to a directory (equivalent to --format=dir)."""
1021
# TODO: list known exporters
837
If no revision is specified this exports the last committed revision."""
1022
838
takes_args = ['dest']
1023
takes_options = ['revision', 'format']
1024
def run(self, dest, revision=None, format='dir'):
839
takes_options = ['revision']
840
def run(self, dest, revision=None):
1026
842
if revision == None:
1027
843
rh = b.revision_history()[-1]
1029
845
rh = b.lookup_revision(int(revision))
1030
846
t = b.revision_tree(rh)
1031
t.export(dest, format)
1034
850
class cmd_cat(Command):
1095
911
This command checks various invariants about the branch storage to
1096
912
detect data corruption or bzr bugs.
1098
If given the --update flag, it will update some optional fields
1099
to help ensure data consistency.
1101
914
takes_args = ['dir?']
1103
915
def run(self, dir='.'):
1104
916
import bzrlib.check
1105
917
bzrlib.check.check(Branch(dir))
1109
class cmd_upgrade(Command):
1110
"""Upgrade branch storage to current format.
1112
This should normally be used only after the check command tells
1115
takes_args = ['dir?']
1117
def run(self, dir='.'):
1118
from bzrlib.upgrade import upgrade
1119
upgrade(Branch(dir))
1123
921
class cmd_whoami(Command):
1124
922
"""Show bzr user id."""
1125
923
takes_options = ['email']
1209
1009
The OTHER_SPEC parameter is required. If the BASE_SPEC parameter is
1210
1010
not supplied, the common ancestor of OTHER_SPEC the current branch is used
1213
merge refuses to run if there are any uncommitted changes, unless
1216
1013
takes_args = ['other_spec', 'base_spec?']
1217
takes_options = ['force']
1219
def run(self, other_spec, base_spec=None, force=False):
1015
def run(self, other_spec, base_spec=None):
1220
1016
from bzrlib.merge import merge
1221
merge(parse_spec(other_spec), parse_spec(base_spec),
1222
check_clean=(not force))
1017
merge(parse_spec(other_spec), parse_spec(base_spec))
1225
1020
class cmd_revert(Command):
1226
"""Reverse all changes since the last commit.
1228
Only versioned files are affected.
1230
TODO: Store backups of any files that will be reverted, so
1231
that the revert can be undone.
1022
Reverse all changes since the last commit. Only versioned files are
1233
1025
takes_options = ['revision']
1235
1027
def run(self, revision=-1):
1236
from bzrlib.merge import merge
1237
merge(('.', revision), parse_spec('.'),
1028
merge.merge(('.', revision), parse_spec('.'), no_changes=False,
1242
1032
class cmd_assert_fail(Command):
1328
1105
(['status'], {'all': True})
1329
1106
>>> parse_args('commit --message=biter'.split())
1330
1107
(['commit'], {'message': u'biter'})
1331
>>> parse_args('log -r 500'.split())
1332
(['log'], {'revision': 500})
1333
>>> parse_args('log -r500:600'.split())
1334
(['log'], {'revision': [500, 600]})
1335
>>> parse_args('log -vr500:600'.split())
1336
(['log'], {'verbose': True, 'revision': [500, 600]})
1337
>>> parse_args('log -rv500:600'.split()) #the r takes an argument
1338
Traceback (most recent call last):
1340
ValueError: invalid literal for int(): v500
1358
1125
optname = a[2:]
1359
1126
if optname not in OPTIONS:
1360
raise BzrError('unknown long option %r' % a)
1127
bailout('unknown long option %r' % a)
1362
1129
shortopt = a[1:]
1363
if shortopt in SHORT_OPTIONS:
1364
# Multi-character options must have a space to delimit
1366
optname = SHORT_OPTIONS[shortopt]
1368
# Single character short options, can be chained,
1369
# and have their value appended to their name
1371
if shortopt not in SHORT_OPTIONS:
1372
# We didn't find the multi-character name, and we
1373
# didn't find the single char name
1374
raise BzrError('unknown short option %r' % a)
1375
optname = SHORT_OPTIONS[shortopt]
1378
# There are extra things on this option
1379
# see if it is the value, or if it is another
1381
optargfn = OPTIONS[optname]
1382
if optargfn is None:
1383
# This option does not take an argument, so the
1384
# next entry is another short option, pack it back
1386
argv.insert(0, '-' + a[2:])
1388
# This option takes an argument, so pack it
1130
if shortopt not in SHORT_OPTIONS:
1131
bailout('unknown short option %r' % a)
1132
optname = SHORT_OPTIONS[shortopt]
1392
1134
if optname in opts:
1393
1135
# XXX: Do we ever want to support this, e.g. for -r?
1394
raise BzrError('repeated option %r' % a)
1136
bailout('repeated option %r' % a)
1396
1138
optargfn = OPTIONS[optname]
1398
1140
if optarg == None:
1400
raise BzrError('option %r needs an argument' % a)
1142
bailout('option %r needs an argument' % a)
1402
1144
optarg = argv.pop(0)
1403
1145
opts[optname] = optargfn(optarg)
1405
1147
if optarg != None:
1406
raise BzrError('option %r takes no argument' % optname)
1148
bailout('option %r takes no argument' % optname)
1407
1149
opts[optname] = True
1460
def _parse_master_args(argv):
1461
"""Parse the arguments that always go with the original command.
1462
These are things like bzr --no-plugins, etc.
1464
There are now 2 types of option flags. Ones that come *before* the command,
1465
and ones that come *after* the command.
1466
Ones coming *before* the command are applied against all possible commands.
1467
And are generally applied before plugins are loaded.
1469
The current list are:
1470
--builtin Allow plugins to load, but don't let them override builtin commands,
1471
they will still be allowed if they do not override a builtin.
1472
--no-plugins Don't load any plugins. This lets you get back to official source
1474
--profile Enable the hotspot profile before running the command.
1475
For backwards compatibility, this is also a non-master option.
1476
--version Spit out the version of bzr that is running and exit.
1477
This is also a non-master option.
1478
--help Run help and exit, also a non-master option (I think that should stay, though)
1480
>>> argv, opts = _parse_master_args(['bzr', '--test'])
1481
Traceback (most recent call last):
1483
BzrCommandError: Invalid master option: 'test'
1484
>>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
1487
>>> print opts['version']
1489
>>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
1491
['command', '--more-options']
1492
>>> print opts['profile']
1494
>>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
1497
>>> print opts['no-plugins']
1499
>>> print opts['profile']
1501
>>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
1503
['command', '--profile']
1504
>>> print opts['profile']
1507
master_opts = {'builtin':False,
1514
# This is the point where we could hook into argv[0] to determine
1515
# what front-end is supposed to be run
1516
# For now, we are just ignoring it.
1517
cmd_name = argv.pop(0)
1519
if arg[:2] != '--': # at the first non-option, we return the rest
1521
arg = arg[2:] # Remove '--'
1522
if arg not in master_opts:
1523
# We could say that this is not an error, that we should
1524
# just let it be handled by the main section instead
1525
raise BzrCommandError('Invalid master option: %r' % arg)
1526
argv.pop(0) # We are consuming this entry
1527
master_opts[arg] = True
1528
return argv, master_opts
1532
1203
def run_bzr(argv):
1533
1204
"""Execute a command.