22
22
from bzrlib.trace import mutter, note, log_error
23
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
24
from bzrlib.osutils import quotefn
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
23
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
24
from bzrlib.branch import find_branch
25
from bzrlib import BZRDIR
31
def register_command(cmd):
32
"Utility function to help register a command"
35
if k.startswith("cmd_"):
36
k_unsquished = _unsquish_command_name(k)
39
if not plugin_cmds.has_key(k_unsquished):
40
plugin_cmds[k_unsquished] = cmd
42
log_error('Two plugins defined the same command: %r' % k)
43
log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
29
46
def _squish_command_name(cmd):
72
"""Return canonical name and class for all registered commands."""
90
def _get_cmd_dict(plugins_override=True):
73
92
for k, v in globals().iteritems():
74
93
if k.startswith("cmd_"):
75
yield _unsquish_command_name(k), v
77
def get_cmd_class(cmd):
94
d[_unsquish_command_name(k)] = v
95
# If we didn't load plugins, the plugin_cmds dict will be empty
99
d2 = plugin_cmds.copy()
105
def get_all_cmds(plugins_override=True):
106
"""Return canonical name and class for all registered commands."""
107
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
111
def get_cmd_class(cmd, plugins_override=True):
78
112
"""Return the canonical name and command class for a command.
80
114
cmd = str(cmd) # not unicode
82
116
# first look up this command under the specified name
117
cmds = _get_cmd_dict(plugins_override=plugins_override)
84
return cmd, globals()[_squish_command_name(cmd)]
119
return cmd, cmds[cmd]
88
123
# look for any command which claims this as an alias
89
for cmdname, cmdclass in get_all_cmds():
124
for cmdname, cmdclass in cmds.iteritems():
90
125
if cmd in cmdclass.aliases:
91
126
return cmdname, cmdclass
177
212
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.
183
215
pipe = os.popen('%s --bzr-usage' % path, 'r')
184
216
self.takes_options = pipe.readline().split()
218
for opt in self.takes_options:
219
if not opt in OPTIONS:
220
raise BzrError("Unknown option '%s' returned by external command %s"
223
# TODO: Is there any way to check takes_args is valid here?
185
224
self.takes_args = pipe.readline().split()
226
if pipe.close() is not None:
227
raise BzrError("Failed funning '%s --bzr-usage'" % path)
188
229
pipe = os.popen('%s --bzr-help' % path, 'r')
189
230
self.__doc__ = pipe.read()
231
if pipe.close() is not None:
232
raise BzrError("Failed funning '%s --bzr-help'" % path)
192
234
def __call__(self, options, arguments):
193
235
Command.__init__(self, options, arguments)
379
442
takes_args = ['from_name', 'to_name']
381
444
def run(self, from_name, to_name):
383
446
b.rename_one(b.relpath(from_name), b.relpath(to_name))
452
class cmd_pull(Command):
453
"""Pull any changes from another branch into the current one.
455
If the location is omitted, the last-used location will be used.
456
Both the revision history and the working directory will be
459
This command only works on branches that have not diverged. Branches are
460
considered diverged if both branches have had commits without first
461
pulling from the other.
463
If branches have diverged, you can use 'bzr merge' to pull the text changes
464
from one into the other.
466
takes_args = ['location?']
468
def run(self, location=None):
469
from bzrlib.merge import merge
471
from shutil import rmtree
474
br_to = find_branch('.')
477
stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
479
if e.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
cache_root = tempfile.mkdtemp()
488
from bzrlib.branch import DivergedBranches
489
br_from = find_branch(location)
490
location = pull_loc(br_from)
491
old_revno = br_to.revno()
493
from branch import find_cached_branch, DivergedBranches
494
br_from = find_cached_branch(location, cache_root)
495
location = pull_loc(br_from)
496
old_revno = br_to.revno()
498
br_to.update_revisions(br_from)
499
except DivergedBranches:
500
raise BzrCommandError("These branches have diverged."
503
merge(('.', -1), ('.', old_revno), check_clean=False)
504
if location != stored_loc:
505
br_to.controlfile("x-pull", "wb").write(location + "\n")
511
class cmd_branch(Command):
512
"""Create a new copy of a branch.
514
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
515
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
517
To retrieve the branch as of a particular revision, supply the --revision
518
parameter, as in "branch foo/bar -r 5".
520
takes_args = ['from_location', 'to_location?']
521
takes_options = ['revision']
523
def run(self, from_location, to_location=None, revision=None):
525
from bzrlib.merge import merge
526
from bzrlib.branch import DivergedBranches, NoSuchRevision, \
527
find_cached_branch, Branch
528
from shutil import rmtree
529
from meta_store import CachedStore
531
cache_root = tempfile.mkdtemp()
534
br_from = find_cached_branch(from_location, cache_root)
536
if e.errno == errno.ENOENT:
537
raise BzrCommandError('Source location "%s" does not'
538
' exist.' % to_location)
542
if to_location is None:
543
to_location = os.path.basename(from_location.rstrip("/\\"))
546
os.mkdir(to_location)
548
if e.errno == errno.EEXIST:
549
raise BzrCommandError('Target directory "%s" already'
550
' exists.' % to_location)
551
if e.errno == errno.ENOENT:
552
raise BzrCommandError('Parent of "%s" does not exist.' %
556
br_to = Branch(to_location, init=True)
559
br_to.update_revisions(br_from, stop_revision=revision)
560
except NoSuchRevision:
562
msg = "The branch %s has no revision %d." % (from_location,
564
raise BzrCommandError(msg)
565
merge((to_location, -1), (to_location, 0), this_dir=to_location,
566
check_clean=False, ignore_zero=True)
567
from_location = pull_loc(br_from)
568
br_to.controlfile("x-pull", "wb").write(from_location + "\n")
573
def pull_loc(branch):
574
# TODO: Should perhaps just make attribute be 'base' in
575
# RemoteBranch and Branch?
576
if hasattr(branch, "baseurl"):
577
return branch.baseurl
387
583
class cmd_renames(Command):
388
584
"""Show list of renamed files.
643
837
takes_args = ['filename?']
644
takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
838
takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long']
646
840
def run(self, filename=None, timezone='original',
651
from bzrlib import show_log, find_branch
846
from bzrlib.branch import find_branch
847
from bzrlib.log import log_formatter, show_log
654
850
direction = (forward and 'forward') or 'reverse'
828
1033
except ValueError:
829
1034
raise BzrCommandError("not a valid revision-number: %r" % revno)
831
print Branch('.').lookup_revision(revno)
1036
print find_branch('.').lookup_revision(revno)
834
1039
class cmd_export(Command):
835
1040
"""Export past revision to destination directory.
837
If no revision is specified this exports the last committed revision."""
1042
If no revision is specified this exports the last committed revision.
1044
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1045
given, exports to a directory (equivalent to --format=dir)."""
1046
# TODO: list known exporters
838
1047
takes_args = ['dest']
839
takes_options = ['revision']
840
def run(self, dest, revision=None):
1048
takes_options = ['revision', 'format']
1049
def run(self, dest, revision=None, format='dir'):
1050
b = find_branch('.')
842
1051
if revision == None:
843
1052
rh = b.revision_history()[-1]
845
1054
rh = b.lookup_revision(int(revision))
846
1055
t = b.revision_tree(rh)
1056
t.export(dest, format)
850
1059
class cmd_cat(Command):
890
1099
def run(self, message=None, file=None, verbose=True, selected_list=None):
891
1100
from bzrlib.commit import commit
1101
from bzrlib.osutils import get_text_message
893
1103
## Warning: shadows builtin file()
894
1104
if not message and not file:
895
raise BzrCommandError("please specify a commit message",
896
["use either --message or --file"])
1107
catcher = cStringIO.StringIO()
1108
sys.stdout = catcher
1109
cmd_status({"file_list":selected_list}, {})
1110
info = catcher.getvalue()
1112
message = get_text_message(info)
1115
raise BzrCommandError("please specify a commit message",
1116
["use either --message or --file"])
897
1117
elif message and file:
898
1118
raise BzrCommandError("please specify either --message or --file")
979
1225
parsed = [spec, None]
982
1230
class cmd_merge(Command):
983
"""Perform a three-way merge of trees."""
984
takes_args = ['other_spec', 'base_spec']
986
def run(self, other_spec, base_spec):
987
from bzrlib.merge import merge
988
merge(parse_spec(other_spec), parse_spec(base_spec))
1231
"""Perform a three-way merge of trees.
1233
The SPEC parameters are working tree or revision specifiers. Working trees
1234
are specified using standard paths or urls. No component of a directory
1235
path may begin with '@'.
1237
Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
1239
Revisions are specified using a dirname/@revno pair, where dirname is the
1240
branch directory and revno is the revision within that branch. If no revno
1241
is specified, the latest revision is used.
1243
Revision examples: './@127', 'foo/@', '../@1'
1245
The OTHER_SPEC parameter is required. If the BASE_SPEC parameter is
1246
not supplied, the common ancestor of OTHER_SPEC the current branch is used
1249
merge refuses to run if there are any uncommitted changes, unless
1252
takes_args = ['other_spec', 'base_spec?']
1253
takes_options = ['force']
1255
def run(self, other_spec, base_spec=None, force=False):
1256
from bzrlib.merge import merge
1257
merge(parse_spec(other_spec), parse_spec(base_spec),
1258
check_clean=(not force))
1262
class cmd_revert(Command):
1263
"""Restore selected files from a previous revision.
1265
takes_args = ['file+']
1266
def run(self, file_list):
1267
from bzrlib.branch import find_branch
1272
b = find_branch(file_list[0])
1274
b.revert([b.relpath(f) for f in file_list])
1277
class cmd_merge_revert(Command):
1278
"""Reverse all changes since the last commit.
1280
Only versioned files are affected.
1282
TODO: Store backups of any files that will be reverted, so
1283
that the revert can be undone.
1285
takes_options = ['revision']
1287
def run(self, revision=-1):
1288
from bzrlib.merge import merge
1289
merge(('.', revision), parse_spec('.'),
990
1294
class cmd_assert_fail(Command):
991
1295
"""Test reporting of assertion failures"""
1063
1382
(['status'], {'all': True})
1064
1383
>>> parse_args('commit --message=biter'.split())
1065
1384
(['commit'], {'message': u'biter'})
1385
>>> parse_args('log -r 500'.split())
1386
(['log'], {'revision': 500})
1387
>>> parse_args('log -r500:600'.split())
1388
(['log'], {'revision': [500, 600]})
1389
>>> parse_args('log -vr500:600'.split())
1390
(['log'], {'verbose': True, 'revision': [500, 600]})
1391
>>> parse_args('log -rv500:600'.split()) #the r takes an argument
1392
Traceback (most recent call last):
1394
ValueError: invalid literal for int(): v500
1083
1412
optname = a[2:]
1084
1413
if optname not in OPTIONS:
1085
bailout('unknown long option %r' % a)
1414
raise BzrError('unknown long option %r' % a)
1087
1416
shortopt = a[1:]
1088
if shortopt not in SHORT_OPTIONS:
1089
bailout('unknown short option %r' % a)
1090
optname = SHORT_OPTIONS[shortopt]
1417
if shortopt in SHORT_OPTIONS:
1418
# Multi-character options must have a space to delimit
1420
optname = SHORT_OPTIONS[shortopt]
1422
# Single character short options, can be chained,
1423
# and have their value appended to their name
1425
if shortopt not in SHORT_OPTIONS:
1426
# We didn't find the multi-character name, and we
1427
# didn't find the single char name
1428
raise BzrError('unknown short option %r' % a)
1429
optname = SHORT_OPTIONS[shortopt]
1432
# There are extra things on this option
1433
# see if it is the value, or if it is another
1435
optargfn = OPTIONS[optname]
1436
if optargfn is None:
1437
# This option does not take an argument, so the
1438
# next entry is another short option, pack it back
1440
argv.insert(0, '-' + a[2:])
1442
# This option takes an argument, so pack it
1092
1446
if optname in opts:
1093
1447
# XXX: Do we ever want to support this, e.g. for -r?
1094
bailout('repeated option %r' % a)
1448
raise BzrError('repeated option %r' % a)
1096
1450
optargfn = OPTIONS[optname]
1098
1452
if optarg == None:
1100
bailout('option %r needs an argument' % a)
1454
raise BzrError('option %r needs an argument' % a)
1102
1456
optarg = argv.pop(0)
1103
1457
opts[optname] = optargfn(optarg)
1105
1459
if optarg != None:
1106
bailout('option %r takes no argument' % optname)
1460
raise BzrError('option %r takes no argument' % optname)
1107
1461
opts[optname] = True
1514
def _parse_master_args(argv):
1515
"""Parse the arguments that always go with the original command.
1516
These are things like bzr --no-plugins, etc.
1518
There are now 2 types of option flags. Ones that come *before* the command,
1519
and ones that come *after* the command.
1520
Ones coming *before* the command are applied against all possible commands.
1521
And are generally applied before plugins are loaded.
1523
The current list are:
1524
--builtin Allow plugins to load, but don't let them override builtin commands,
1525
they will still be allowed if they do not override a builtin.
1526
--no-plugins Don't load any plugins. This lets you get back to official source
1528
--profile Enable the hotspot profile before running the command.
1529
For backwards compatibility, this is also a non-master option.
1530
--version Spit out the version of bzr that is running and exit.
1531
This is also a non-master option.
1532
--help Run help and exit, also a non-master option (I think that should stay, though)
1534
>>> argv, opts = _parse_master_args(['bzr', '--test'])
1535
Traceback (most recent call last):
1537
BzrCommandError: Invalid master option: 'test'
1538
>>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
1541
>>> print opts['version']
1543
>>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
1545
['command', '--more-options']
1546
>>> print opts['profile']
1548
>>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
1551
>>> print opts['no-plugins']
1553
>>> print opts['profile']
1555
>>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
1557
['command', '--profile']
1558
>>> print opts['profile']
1561
master_opts = {'builtin':False,
1568
# This is the point where we could hook into argv[0] to determine
1569
# what front-end is supposed to be run
1570
# For now, we are just ignoring it.
1571
cmd_name = argv.pop(0)
1573
if arg[:2] != '--': # at the first non-option, we return the rest
1575
arg = arg[2:] # Remove '--'
1576
if arg not in master_opts:
1577
# We could say that this is not an error, that we should
1578
# just let it be handled by the main section instead
1579
raise BzrCommandError('Invalid master option: %r' % arg)
1580
argv.pop(0) # We are consuming this entry
1581
master_opts[arg] = True
1582
return argv, master_opts
1161
1586
def run_bzr(argv):
1162
1587
"""Execute a command.