166
171
:return: workingtree, [relative_paths]
168
if file_list is None or len(file_list) == 0:
169
tree = WorkingTree.open_containing(default_branch)[0]
170
if tree.supports_views() and apply_view:
171
view_files = tree.views.lookup_view()
173
file_list = view_files
174
view_str = views.view_display_str(view_files)
175
note("Ignoring files outside view. View is %s" % view_str)
176
return tree, file_list
177
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
178
return tree, safe_relpath_files(tree, file_list, canonicalize,
179
apply_view=apply_view)
182
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
183
"""Convert file_list into a list of relpaths in tree.
185
:param tree: A tree to operate on.
186
:param file_list: A list of user provided paths or None.
187
:param apply_view: if True and a view is set, apply it or check that
188
specified files are within it
189
:return: A list of relative paths.
190
:raises errors.PathNotChild: When a provided path is in a different tree
193
if file_list is None:
195
if tree.supports_views() and apply_view:
196
view_files = tree.views.lookup_view()
200
# tree.relpath exists as a "thunk" to osutils, but canonical_relpath
201
# doesn't - fix that up here before we enter the loop.
203
fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
206
for filename in file_list:
208
relpath = fixer(osutils.dereference_path(filename))
209
if view_files and not osutils.is_inside_any(view_files, relpath):
210
raise errors.FileOutsideView(filename, view_files)
211
new_list.append(relpath)
212
except errors.PathNotChild:
213
raise errors.FileInWrongBranch(tree.branch, filename)
173
return WorkingTree.open_containing_paths(
174
file_list, default_directory='.',
217
179
def _get_view_info_for_change_reporter(tree):
336
306
takes_args = ['revision_id?']
337
takes_options = ['revision']
307
takes_options = ['directory', 'revision']
338
308
# cat-revision is more for frontends so should be exact
339
309
encoding = 'strict'
311
def print_revision(self, revisions, revid):
312
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
313
record = stream.next()
314
if record.storage_kind == 'absent':
315
raise errors.NoSuchRevision(revisions, revid)
316
revtext = record.get_bytes_as('fulltext')
317
self.outf.write(revtext.decode('utf-8'))
342
def run(self, revision_id=None, revision=None):
320
def run(self, revision_id=None, revision=None, directory=u'.'):
343
321
if revision_id is not None and revision is not None:
344
322
raise errors.BzrCommandError('You can only supply one of'
345
323
' revision_id or --revision')
346
324
if revision_id is None and revision is None:
347
325
raise errors.BzrCommandError('You must supply either'
348
326
' --revision or a revision_id')
349
b = WorkingTree.open_containing(u'.')[0].branch
351
# TODO: jam 20060112 should cat-revision always output utf-8?
352
if revision_id is not None:
353
revision_id = osutils.safe_revision_id(revision_id, warn=False)
355
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
356
except errors.NoSuchRevision:
357
msg = "The repository %s contains no revision %s." % (b.repository.base,
359
raise errors.BzrCommandError(msg)
360
elif revision is not None:
363
raise errors.BzrCommandError('You cannot specify a NULL'
365
rev_id = rev.as_revision_id(b)
366
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
327
b = WorkingTree.open_containing(directory)[0].branch
329
revisions = b.repository.revisions
330
if revisions is None:
331
raise errors.BzrCommandError('Repository %r does not support '
332
'access to raw revision texts')
334
b.repository.lock_read()
336
# TODO: jam 20060112 should cat-revision always output utf-8?
337
if revision_id is not None:
338
revision_id = osutils.safe_revision_id(revision_id, warn=False)
340
self.print_revision(revisions, revision_id)
341
except errors.NoSuchRevision:
342
msg = "The repository %s contains no revision %s." % (
343
b.repository.base, revision_id)
344
raise errors.BzrCommandError(msg)
345
elif revision is not None:
348
raise errors.BzrCommandError(
349
'You cannot specify a NULL revision.')
350
rev_id = rev.as_revision_id(b)
351
self.print_revision(revisions, rev_id)
353
b.repository.unlock()
369
356
class cmd_dump_btree(Command):
370
"""Dump the contents of a btree index file to stdout.
357
__doc__ = """Dump the contents of a btree index file to stdout.
372
359
PATH is a btree index file, it can be any URL. This includes things like
373
360
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
451
443
To re-create the working tree, use "bzr checkout".
453
445
_see_also = ['checkout', 'working-trees']
454
takes_args = ['location?']
446
takes_args = ['location*']
455
447
takes_options = [
457
449
help='Remove the working tree even if it has '
458
'uncommitted changes.'),
450
'uncommitted or shelved changes.'),
461
def run(self, location='.', force=False):
462
d = bzrdir.BzrDir.open(location)
465
working = d.open_workingtree()
466
except errors.NoWorkingTree:
467
raise errors.BzrCommandError("No working tree to remove")
468
except errors.NotLocalUrl:
469
raise errors.BzrCommandError("You cannot remove the working tree"
472
if (working.has_changes()):
473
raise errors.UncommittedChanges(working)
475
working_path = working.bzrdir.root_transport.base
476
branch_path = working.branch.bzrdir.root_transport.base
477
if working_path != branch_path:
478
raise errors.BzrCommandError("You cannot remove the working tree"
479
" from a lightweight checkout")
481
d.destroy_workingtree()
453
def run(self, location_list, force=False):
454
if not location_list:
457
for location in location_list:
458
d = bzrdir.BzrDir.open(location)
461
working = d.open_workingtree()
462
except errors.NoWorkingTree:
463
raise errors.BzrCommandError("No working tree to remove")
464
except errors.NotLocalUrl:
465
raise errors.BzrCommandError("You cannot remove the working tree"
468
if (working.has_changes()):
469
raise errors.UncommittedChanges(working)
470
if working.get_shelf_manager().last_shelf() is not None:
471
raise errors.ShelvedChanges(working)
473
if working.user_url != working.branch.user_url:
474
raise errors.BzrCommandError("You cannot remove the working tree"
475
" from a lightweight checkout")
477
d.destroy_workingtree()
484
480
class cmd_revno(Command):
485
"""Show current revision number.
481
__doc__ = """Show current revision number.
487
483
This is equal to the number of revisions on this branch.
500
496
wt = WorkingTree.open_containing(location)[0]
497
self.add_cleanup(wt.lock_read().unlock)
502
498
except (errors.NoWorkingTree, errors.NotLocalUrl):
503
499
raise errors.NoWorkingTree(location)
500
revid = wt.last_revision()
505
revid = wt.last_revision()
507
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
508
except errors.NoSuchRevision:
510
revno = ".".join(str(n) for n in revno_t)
502
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
503
except errors.NoSuchRevision:
505
revno = ".".join(str(n) for n in revno_t)
514
507
b = Branch.open_containing(location)[0]
508
self.add_cleanup(b.lock_read().unlock)
521
511
self.outf.write(str(revno) + '\n')
524
514
class cmd_revision_info(Command):
525
"""Show revision number and revision id for a given revision identifier.
515
__doc__ = """Show revision number and revision id for a given revision identifier.
528
518
takes_args = ['revision_info*']
529
519
takes_options = [
521
custom_help('directory',
532
522
help='Branch to examine, '
533
'rather than the one containing the working directory.',
523
'rather than the one containing the working directory.'),
537
524
Option('tree', help='Show revno of working tree'),
545
532
wt = WorkingTree.open_containing(directory)[0]
534
self.add_cleanup(wt.lock_read().unlock)
548
535
except (errors.NoWorkingTree, errors.NotLocalUrl):
550
537
b = Branch.open_containing(directory)[0]
554
if revision is not None:
555
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
556
if revision_info_list is not None:
557
for rev_str in revision_info_list:
558
rev_spec = RevisionSpec.from_string(rev_str)
559
revision_ids.append(rev_spec.as_revision_id(b))
560
# No arguments supplied, default to the last revision
561
if len(revision_ids) == 0:
564
raise errors.NoWorkingTree(directory)
565
revision_ids.append(wt.last_revision())
567
revision_ids.append(b.last_revision())
571
for revision_id in revision_ids:
573
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
574
revno = '.'.join(str(i) for i in dotted_revno)
575
except errors.NoSuchRevision:
577
maxlen = max(maxlen, len(revno))
578
revinfos.append([revno, revision_id])
538
self.add_cleanup(b.lock_read().unlock)
540
if revision is not None:
541
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
542
if revision_info_list is not None:
543
for rev_str in revision_info_list:
544
rev_spec = RevisionSpec.from_string(rev_str)
545
revision_ids.append(rev_spec.as_revision_id(b))
546
# No arguments supplied, default to the last revision
547
if len(revision_ids) == 0:
550
raise errors.NoWorkingTree(directory)
551
revision_ids.append(wt.last_revision())
553
revision_ids.append(b.last_revision())
557
for revision_id in revision_ids:
559
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
560
revno = '.'.join(str(i) for i in dotted_revno)
561
except errors.NoSuchRevision:
563
maxlen = max(maxlen, len(revno))
564
revinfos.append([revno, revision_id])
585
567
for ri in revinfos:
586
568
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
589
571
class cmd_add(Command):
590
"""Add specified files or directories.
572
__doc__ = """Add specified files or directories.
592
574
In non-recursive mode, all the named items are added, regardless
593
575
of whether they were previously ignored. A warning is given if
733
717
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
735
719
revision = _get_one_revision('inventory', revision)
736
work_tree, file_list = tree_files(file_list)
737
work_tree.lock_read()
739
if revision is not None:
740
tree = revision.as_tree(work_tree.branch)
742
extra_trees = [work_tree]
748
if file_list is not None:
749
file_ids = tree.paths2ids(file_list, trees=extra_trees,
750
require_versioned=True)
751
# find_ids_across_trees may include some paths that don't
753
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
754
for file_id in file_ids if file_id in tree)
756
entries = tree.inventory.entries()
759
if tree is not work_tree:
720
work_tree, file_list = WorkingTree.open_containing_paths(file_list)
721
self.add_cleanup(work_tree.lock_read().unlock)
722
if revision is not None:
723
tree = revision.as_tree(work_tree.branch)
725
extra_trees = [work_tree]
726
self.add_cleanup(tree.lock_read().unlock)
731
if file_list is not None:
732
file_ids = tree.paths2ids(file_list, trees=extra_trees,
733
require_versioned=True)
734
# find_ids_across_trees may include some paths that don't
736
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
737
for file_id in file_ids if file_id in tree)
739
entries = tree.inventory.entries()
762
742
for path, entry in entries:
763
743
if kind and kind != entry.kind:
1006
986
branch_from = Branch.open(location,
1007
987
possible_transports=possible_transports)
988
self.add_cleanup(branch_from.lock_read().unlock)
1009
990
if branch_to.get_parent() is None or remember:
1010
991
branch_to.set_parent(branch_from.base)
1012
if branch_from is not branch_to:
1013
branch_from.lock_read()
1015
if revision is not None:
1016
revision_id = revision.as_revision_id(branch_from)
1018
branch_to.lock_write()
1020
if tree_to is not None:
1021
view_info = _get_view_info_for_change_reporter(tree_to)
1022
change_reporter = delta._ChangeReporter(
1023
unversioned_filter=tree_to.is_ignored,
1024
view_info=view_info)
1025
result = tree_to.pull(
1026
branch_from, overwrite, revision_id, change_reporter,
1027
possible_transports=possible_transports, local=local)
1029
result = branch_to.pull(
1030
branch_from, overwrite, revision_id, local=local)
1032
result.report(self.outf)
1033
if verbose and result.old_revid != result.new_revid:
1034
log.show_branch_change(
1035
branch_to, self.outf, result.old_revno,
1040
if branch_from is not branch_to:
1041
branch_from.unlock()
993
if revision is not None:
994
revision_id = revision.as_revision_id(branch_from)
996
if tree_to is not None:
997
view_info = _get_view_info_for_change_reporter(tree_to)
998
change_reporter = delta._ChangeReporter(
999
unversioned_filter=tree_to.is_ignored,
1000
view_info=view_info)
1001
result = tree_to.pull(
1002
branch_from, overwrite, revision_id, change_reporter,
1003
possible_transports=possible_transports, local=local,
1004
show_base=show_base)
1006
result = branch_to.pull(
1007
branch_from, overwrite, revision_id, local=local)
1009
result.report(self.outf)
1010
if verbose and result.old_revid != result.new_revid:
1011
log.show_branch_change(
1012
branch_to, self.outf, result.old_revno,
1044
1016
class cmd_push(Command):
1045
"""Update a mirror of this branch.
1017
__doc__ = """Update a mirror of this branch.
1047
1019
The target branch will not have its working tree populated because this
1048
1020
is both expensive, and is not supported on remote file systems.
1109
1078
# Get the source branch
1110
1079
(tree, br_from,
1111
1080
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1113
strict = br_from.get_config().get_user_option_as_bool('push_strict')
1114
if strict is None: strict = True # default value
1115
1081
# Get the tip's revision_id
1116
1082
revision = _get_one_revision('push', revision)
1117
1083
if revision is not None:
1118
1084
revision_id = revision.in_history(br_from).rev_id
1120
1086
revision_id = None
1121
if strict and tree is not None and revision_id is None:
1122
if (tree.has_changes()):
1123
raise errors.UncommittedChanges(
1124
tree, more='Use --no-strict to force the push.')
1125
if tree.last_revision() != tree.branch.last_revision():
1126
# The tree has lost sync with its branch, there is little
1127
# chance that the user is aware of it but he can still force
1128
# the push with --no-strict
1129
raise errors.OutOfDateTree(
1130
tree, more='Use --no-strict to force the push.')
1087
if tree is not None and revision_id is None:
1088
tree.check_changed_or_out_of_date(
1089
strict, 'push_strict',
1090
more_error='Use --no-strict to force the push.',
1091
more_warning='Uncommitted changes will not be pushed.')
1132
1092
# Get the stacked_on branch, if any
1133
1093
if stacked_on is not None:
1134
1094
stacked_on = urlutils.normalize_url(stacked_on)
1199
1161
' directory exists, but does not already'
1200
1162
' have a control directory. This flag will'
1201
1163
' allow branch to proceed.'),
1165
help="Bind new branch to from location."),
1203
1167
aliases = ['get', 'clone']
1205
1169
def run(self, from_location, to_location=None, revision=None,
1206
1170
hardlink=False, stacked=False, standalone=False, no_tree=False,
1207
use_existing_dir=False, switch=False):
1171
use_existing_dir=False, switch=False, bind=False,
1208
1173
from bzrlib import switch as _mod_switch
1209
1174
from bzrlib.tag import _merge_tags_if_possible
1210
1175
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1177
if not (hardlink or files_from):
1178
# accelerator_tree is usually slower because you have to read N
1179
# files (no readahead, lots of seeks, etc), but allow the user to
1180
# explicitly request it
1181
accelerator_tree = None
1182
if files_from is not None and files_from != from_location:
1183
accelerator_tree = WorkingTree.open(files_from)
1212
1184
revision = _get_one_revision('branch', revision)
1185
self.add_cleanup(br_from.lock_read().unlock)
1186
if revision is not None:
1187
revision_id = revision.as_revision_id(br_from)
1189
# FIXME - wt.last_revision, fallback to branch, fall back to
1190
# None or perhaps NULL_REVISION to mean copy nothing
1192
revision_id = br_from.last_revision()
1193
if to_location is None:
1194
to_location = urlutils.derive_to_location(from_location)
1195
to_transport = transport.get_transport(to_location)
1215
if revision is not None:
1216
revision_id = revision.as_revision_id(br_from)
1197
to_transport.mkdir('.')
1198
except errors.FileExists:
1199
if not use_existing_dir:
1200
raise errors.BzrCommandError('Target directory "%s" '
1201
'already exists.' % to_location)
1218
# FIXME - wt.last_revision, fallback to branch, fall back to
1219
# None or perhaps NULL_REVISION to mean copy nothing
1221
revision_id = br_from.last_revision()
1222
if to_location is None:
1223
to_location = urlutils.derive_to_location(from_location)
1224
to_transport = transport.get_transport(to_location)
1226
to_transport.mkdir('.')
1227
except errors.FileExists:
1228
if not use_existing_dir:
1229
raise errors.BzrCommandError('Target directory "%s" '
1230
'already exists.' % to_location)
1204
bzrdir.BzrDir.open_from_transport(to_transport)
1205
except errors.NotBranchError:
1233
bzrdir.BzrDir.open_from_transport(to_transport)
1234
except errors.NotBranchError:
1237
raise errors.AlreadyBranchError(to_location)
1238
except errors.NoSuchFile:
1239
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1242
# preserve whatever source format we have.
1243
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1244
possible_transports=[to_transport],
1245
accelerator_tree=accelerator_tree,
1246
hardlink=hardlink, stacked=stacked,
1247
force_new_repo=standalone,
1248
create_tree_if_local=not no_tree,
1249
source_branch=br_from)
1250
branch = dir.open_branch()
1251
except errors.NoSuchRevision:
1252
to_transport.delete_tree('.')
1253
msg = "The branch %s has no revision %s." % (from_location,
1255
raise errors.BzrCommandError(msg)
1256
_merge_tags_if_possible(br_from, branch)
1257
# If the source branch is stacked, the new branch may
1258
# be stacked whether we asked for that explicitly or not.
1259
# We therefore need a try/except here and not just 'if stacked:'
1261
note('Created new stacked branch referring to %s.' %
1262
branch.get_stacked_on_url())
1263
except (errors.NotStacked, errors.UnstackableBranchFormat,
1264
errors.UnstackableRepositoryFormat), e:
1265
note('Branched %d revision(s).' % branch.revno())
1267
# Switch to the new branch
1268
wt, _ = WorkingTree.open_containing('.')
1269
_mod_switch.switch(wt.bzrdir, branch)
1270
note('Switched to branch: %s',
1271
urlutils.unescape_for_display(branch.base, 'utf-8'))
1208
raise errors.AlreadyBranchError(to_location)
1209
except errors.NoSuchFile:
1210
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1213
# preserve whatever source format we have.
1214
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1215
possible_transports=[to_transport],
1216
accelerator_tree=accelerator_tree,
1217
hardlink=hardlink, stacked=stacked,
1218
force_new_repo=standalone,
1219
create_tree_if_local=not no_tree,
1220
source_branch=br_from)
1221
branch = dir.open_branch()
1222
except errors.NoSuchRevision:
1223
to_transport.delete_tree('.')
1224
msg = "The branch %s has no revision %s." % (from_location,
1226
raise errors.BzrCommandError(msg)
1227
_merge_tags_if_possible(br_from, branch)
1228
# If the source branch is stacked, the new branch may
1229
# be stacked whether we asked for that explicitly or not.
1230
# We therefore need a try/except here and not just 'if stacked:'
1232
note('Created new stacked branch referring to %s.' %
1233
branch.get_stacked_on_url())
1234
except (errors.NotStacked, errors.UnstackableBranchFormat,
1235
errors.UnstackableRepositoryFormat), e:
1236
note('Branched %d revision(s).' % branch.revno())
1238
# Bind to the parent
1239
parent_branch = Branch.open(from_location)
1240
branch.bind(parent_branch)
1241
note('New branch bound to %s' % from_location)
1243
# Switch to the new branch
1244
wt, _ = WorkingTree.open_containing('.')
1245
_mod_switch.switch(wt.bzrdir, branch)
1246
note('Switched to branch: %s',
1247
urlutils.unescape_for_display(branch.base, 'utf-8'))
1276
1250
class cmd_checkout(Command):
1277
"""Create a new checkout of an existing branch.
1251
__doc__ = """Create a new checkout of an existing branch.
1279
1253
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1280
1254
the branch found in '.'. This is useful if you have removed the working tree
1354
1333
@display_command
1355
1334
def run(self, dir=u'.'):
1356
1335
tree = WorkingTree.open_containing(dir)[0]
1359
new_inv = tree.inventory
1360
old_tree = tree.basis_tree()
1361
old_tree.lock_read()
1363
old_inv = old_tree.inventory
1365
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1366
for f, paths, c, v, p, n, k, e in iterator:
1367
if paths[0] == paths[1]:
1371
renames.append(paths)
1373
for old_name, new_name in renames:
1374
self.outf.write("%s => %s\n" % (old_name, new_name))
1336
self.add_cleanup(tree.lock_read().unlock)
1337
new_inv = tree.inventory
1338
old_tree = tree.basis_tree()
1339
self.add_cleanup(old_tree.lock_read().unlock)
1340
old_inv = old_tree.inventory
1342
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1343
for f, paths, c, v, p, n, k, e in iterator:
1344
if paths[0] == paths[1]:
1348
renames.append(paths)
1350
for old_name, new_name in renames:
1351
self.outf.write("%s => %s\n" % (old_name, new_name))
1381
1354
class cmd_update(Command):
1382
"""Update a tree to have the latest code committed to its branch.
1355
__doc__ = """Update a tree to have the latest code committed to its branch.
1384
1357
This will perform a merge into the working tree, and may generate
1385
1358
conflicts. If you have any local changes, you will still
1388
1361
If you want to discard your local changes, you can just do a
1389
1362
'bzr revert' instead of 'bzr commit' after the update.
1364
If you want to restore a file that has been removed locally, use
1365
'bzr revert' instead of 'bzr update'.
1367
If the tree's branch is bound to a master branch, it will also update
1368
the branch from the master.
1392
1371
_see_also = ['pull', 'working-trees', 'status-flags']
1393
1372
takes_args = ['dir?']
1373
takes_options = ['revision',
1375
help="Show base revision text in conflicts."),
1394
1377
aliases = ['up']
1396
def run(self, dir='.'):
1379
def run(self, dir='.', revision=None, show_base=None):
1380
if revision is not None and len(revision) != 1:
1381
raise errors.BzrCommandError(
1382
"bzr update --revision takes exactly one revision")
1397
1383
tree = WorkingTree.open_containing(dir)[0]
1384
branch = tree.branch
1398
1385
possible_transports = []
1399
master = tree.branch.get_master_branch(
1386
master = branch.get_master_branch(
1400
1387
possible_transports=possible_transports)
1401
1388
if master is not None:
1403
1389
branch_location = master.base
1392
branch_location = tree.branch.base
1405
1393
tree.lock_tree_write()
1406
branch_location = tree.branch.base
1394
self.add_cleanup(tree.unlock)
1407
1395
# get rid of the final '/' and be ready for display
1408
branch_location = urlutils.unescape_for_display(branch_location[:-1],
1396
branch_location = urlutils.unescape_for_display(
1397
branch_location.rstrip('/'),
1399
existing_pending_merges = tree.get_parent_ids()[1:]
1403
# may need to fetch data into a heavyweight checkout
1404
# XXX: this may take some time, maybe we should display a
1406
old_tip = branch.update(possible_transports)
1407
if revision is not None:
1408
revision_id = revision[0].as_revision_id(branch)
1410
revision_id = branch.last_revision()
1411
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1412
revno = branch.revision_id_to_dotted_revno(revision_id)
1413
note("Tree is up to date at revision %s of branch %s" %
1414
('.'.join(map(str, revno)), branch_location))
1416
view_info = _get_view_info_for_change_reporter(tree)
1417
change_reporter = delta._ChangeReporter(
1418
unversioned_filter=tree.is_ignored,
1419
view_info=view_info)
1411
existing_pending_merges = tree.get_parent_ids()[1:]
1412
last_rev = _mod_revision.ensure_null(tree.last_revision())
1413
if last_rev == _mod_revision.ensure_null(
1414
tree.branch.last_revision()):
1415
# may be up to date, check master too.
1416
if master is None or last_rev == _mod_revision.ensure_null(
1417
master.last_revision()):
1418
revno = tree.branch.revision_id_to_revno(last_rev)
1419
note('Tree is up to date at revision %d of branch %s'
1420
% (revno, branch_location))
1422
view_info = _get_view_info_for_change_reporter(tree)
1423
1421
conflicts = tree.update(
1424
delta._ChangeReporter(unversioned_filter=tree.is_ignored,
1425
view_info=view_info), possible_transports=possible_transports)
1426
revno = tree.branch.revision_id_to_revno(
1427
_mod_revision.ensure_null(tree.last_revision()))
1428
note('Updated to revision %d of branch %s' %
1429
(revno, branch_location))
1430
if tree.get_parent_ids()[1:] != existing_pending_merges:
1431
note('Your local commits will now show as pending merges with '
1432
"'bzr status', and can be committed with 'bzr commit'.")
1423
possible_transports=possible_transports,
1424
revision=revision_id,
1426
show_base=show_base)
1427
except errors.NoSuchRevision, e:
1428
raise errors.BzrCommandError(
1429
"branch has no revision %s\n"
1430
"bzr update --revision only works"
1431
" for a revision in the branch history"
1433
revno = tree.branch.revision_id_to_dotted_revno(
1434
_mod_revision.ensure_null(tree.last_revision()))
1435
note('Updated to revision %s of branch %s' %
1436
('.'.join(map(str, revno)), branch_location))
1437
parent_ids = tree.get_parent_ids()
1438
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1439
note('Your local commits will now show as pending merges with '
1440
"'bzr status', and can be committed with 'bzr commit'.")
1441
1447
class cmd_info(Command):
1442
"""Show information about a working tree, branch or repository.
1448
__doc__ = """Show information about a working tree, branch or repository.
1444
1450
This command will show all known locations and formats associated to the
1445
1451
tree, branch or repository.
1507
1513
def run(self, file_list, verbose=False, new=False,
1508
1514
file_deletion_strategy='safe'):
1509
tree, file_list = tree_files(file_list)
1515
tree, file_list = WorkingTree.open_containing_paths(file_list)
1511
1517
if file_list is not None:
1512
1518
file_list = [f for f in file_list]
1516
# Heuristics should probably all move into tree.remove_smart or
1519
added = tree.changes_from(tree.basis_tree(),
1520
specific_files=file_list).added
1521
file_list = sorted([f[0] for f in added], reverse=True)
1522
if len(file_list) == 0:
1523
raise errors.BzrCommandError('No matching files.')
1524
elif file_list is None:
1525
# missing files show up in iter_changes(basis) as
1526
# versioned-with-no-kind.
1528
for change in tree.iter_changes(tree.basis_tree()):
1529
# Find paths in the working tree that have no kind:
1530
if change[1][1] is not None and change[6][1] is None:
1531
missing.append(change[1][1])
1532
file_list = sorted(missing, reverse=True)
1533
file_deletion_strategy = 'keep'
1534
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1535
keep_files=file_deletion_strategy=='keep',
1536
force=file_deletion_strategy=='force')
1520
self.add_cleanup(tree.lock_write().unlock)
1521
# Heuristics should probably all move into tree.remove_smart or
1524
added = tree.changes_from(tree.basis_tree(),
1525
specific_files=file_list).added
1526
file_list = sorted([f[0] for f in added], reverse=True)
1527
if len(file_list) == 0:
1528
raise errors.BzrCommandError('No matching files.')
1529
elif file_list is None:
1530
# missing files show up in iter_changes(basis) as
1531
# versioned-with-no-kind.
1533
for change in tree.iter_changes(tree.basis_tree()):
1534
# Find paths in the working tree that have no kind:
1535
if change[1][1] is not None and change[6][1] is None:
1536
missing.append(change[1][1])
1537
file_list = sorted(missing, reverse=True)
1538
file_deletion_strategy = 'keep'
1539
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1540
keep_files=file_deletion_strategy=='keep',
1541
force=file_deletion_strategy=='force')
1541
1544
class cmd_file_id(Command):
1542
"""Print file_id of a particular file or directory.
1545
__doc__ = """Print file_id of a particular file or directory.
1544
1547
The file_id is assigned when the file is first added and remains the
1545
1548
same through all revisions where the file exists, even when it is
1940
1958
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1941
1959
' one or two revision specifiers')
1961
if using is not None and format is not None:
1962
raise errors.BzrCommandError('--using and --format are mutually '
1943
1965
(old_tree, new_tree,
1944
1966
old_branch, new_branch,
1945
specific_files, extra_trees) = get_trees_and_branches_to_diff(
1946
file_list, revision, old, new, apply_view=True)
1967
specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1968
file_list, revision, old, new, self.add_cleanup, apply_view=True)
1969
# GNU diff on Windows uses ANSI encoding for filenames
1970
path_encoding = osutils.get_diff_header_encoding()
1947
1971
return show_diff_trees(old_tree, new_tree, sys.stdout,
1948
1972
specific_files=specific_files,
1949
1973
external_diff_options=diff_options,
1950
1974
old_label=old_label, new_label=new_label,
1951
extra_trees=extra_trees, using=using)
1975
extra_trees=extra_trees,
1976
path_encoding=path_encoding,
1954
1981
class cmd_deleted(Command):
1955
"""List files deleted in the working tree.
1982
__doc__ = """List files deleted in the working tree.
1957
1984
# TODO: Show files deleted since a previous revision, or
1958
1985
# between two revisions.
1961
1988
# level of effort but possibly much less IO. (Or possibly not,
1962
1989
# if the directories are very large...)
1963
1990
_see_also = ['status', 'ls']
1964
takes_options = ['show-ids']
1991
takes_options = ['directory', 'show-ids']
1966
1993
@display_command
1967
def run(self, show_ids=False):
1968
tree = WorkingTree.open_containing(u'.')[0]
1971
old = tree.basis_tree()
1974
for path, ie in old.inventory.iter_entries():
1975
if not tree.has_id(ie.file_id):
1976
self.outf.write(path)
1978
self.outf.write(' ')
1979
self.outf.write(ie.file_id)
1980
self.outf.write('\n')
1994
def run(self, show_ids=False, directory=u'.'):
1995
tree = WorkingTree.open_containing(directory)[0]
1996
self.add_cleanup(tree.lock_read().unlock)
1997
old = tree.basis_tree()
1998
self.add_cleanup(old.lock_read().unlock)
1999
for path, ie in old.inventory.iter_entries():
2000
if not tree.has_id(ie.file_id):
2001
self.outf.write(path)
2003
self.outf.write(' ')
2004
self.outf.write(ie.file_id)
2005
self.outf.write('\n')
1987
2008
class cmd_modified(Command):
1988
"""List files modified in working tree.
2009
__doc__ = """List files modified in working tree.
1992
2013
_see_also = ['status', 'ls']
1995
help='Write an ascii NUL (\\0) separator '
1996
'between files rather than a newline.')
2014
takes_options = ['directory', 'null']
1999
2016
@display_command
2000
def run(self, null=False):
2001
tree = WorkingTree.open_containing(u'.')[0]
2017
def run(self, null=False, directory=u'.'):
2018
tree = WorkingTree.open_containing(directory)[0]
2002
2019
td = tree.changes_from(tree.basis_tree())
2003
2020
for path, id, kind, text_modified, meta_modified in td.modified:
2010
2027
class cmd_added(Command):
2011
"""List files added in working tree.
2028
__doc__ = """List files added in working tree.
2015
2032
_see_also = ['status', 'ls']
2018
help='Write an ascii NUL (\\0) separator '
2019
'between files rather than a newline.')
2033
takes_options = ['directory', 'null']
2022
2035
@display_command
2023
def run(self, null=False):
2024
wt = WorkingTree.open_containing(u'.')[0]
2027
basis = wt.basis_tree()
2030
basis_inv = basis.inventory
2033
if file_id in basis_inv:
2035
if inv.is_root(file_id) and len(basis_inv) == 0:
2037
path = inv.id2path(file_id)
2038
if not os.access(osutils.abspath(path), os.F_OK):
2041
self.outf.write(path + '\0')
2043
self.outf.write(osutils.quotefn(path) + '\n')
2036
def run(self, null=False, directory=u'.'):
2037
wt = WorkingTree.open_containing(directory)[0]
2038
self.add_cleanup(wt.lock_read().unlock)
2039
basis = wt.basis_tree()
2040
self.add_cleanup(basis.lock_read().unlock)
2041
basis_inv = basis.inventory
2044
if file_id in basis_inv:
2046
if inv.is_root(file_id) and len(basis_inv) == 0:
2048
path = inv.id2path(file_id)
2049
if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2052
self.outf.write(path + '\0')
2054
self.outf.write(osutils.quotefn(path) + '\n')
2050
2057
class cmd_root(Command):
2051
"""Show the tree root directory.
2058
__doc__ = """Show the tree root directory.
2053
2060
The root is the nearest enclosing directory with a .bzr control
2310
2330
filter_by_dir = False
2314
# find the file ids to log and check for directory filtering
2315
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2316
revision, file_list)
2317
for relpath, file_id, kind in file_info_list:
2319
raise errors.BzrCommandError(
2320
"Path unknown at end or start of revision range: %s" %
2322
# If the relpath is the top of the tree, we log everything
2327
file_ids.append(file_id)
2328
filter_by_dir = filter_by_dir or (
2329
kind in ['directory', 'tree-reference'])
2332
# FIXME ? log the current subdir only RBC 20060203
2333
if revision is not None \
2334
and len(revision) > 0 and revision[0].get_branch():
2335
location = revision[0].get_branch()
2332
# find the file ids to log and check for directory filtering
2333
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2334
revision, file_list, self.add_cleanup)
2335
for relpath, file_id, kind in file_info_list:
2337
raise errors.BzrCommandError(
2338
"Path unknown at end or start of revision range: %s" %
2340
# If the relpath is the top of the tree, we log everything
2338
dir, relpath = bzrdir.BzrDir.open_containing(location)
2339
b = dir.open_branch()
2341
rev1, rev2 = _get_revision_range(revision, b, self.name())
2343
# Decide on the type of delta & diff filtering to use
2344
# TODO: add an --all-files option to make this configurable & consistent
2352
diff_type = 'partial'
2356
# Build the log formatter
2357
if log_format is None:
2358
log_format = log.log_formatter_registry.get_default(b)
2359
# Make a non-encoding output to include the diffs - bug 328007
2360
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2361
lf = log_format(show_ids=show_ids, to_file=self.outf,
2362
to_exact_file=unencoded_output,
2363
show_timezone=timezone,
2364
delta_format=get_verbosity_level(),
2366
show_advice=levels is None)
2368
# Choose the algorithm for doing the logging. It's annoying
2369
# having multiple code paths like this but necessary until
2370
# the underlying repository format is faster at generating
2371
# deltas or can provide everything we need from the indices.
2372
# The default algorithm - match-using-deltas - works for
2373
# multiple files and directories and is faster for small
2374
# amounts of history (200 revisions say). However, it's too
2375
# slow for logging a single file in a repository with deep
2376
# history, i.e. > 10K revisions. In the spirit of "do no
2377
# evil when adding features", we continue to use the
2378
# original algorithm - per-file-graph - for the "single
2379
# file that isn't a directory without showing a delta" case.
2380
partial_history = revision and b.repository._format.supports_chks
2381
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2382
or delta_type or partial_history)
2384
# Build the LogRequest and execute it
2385
if len(file_ids) == 0:
2387
rqst = make_log_request_dict(
2388
direction=direction, specific_fileids=file_ids,
2389
start_revision=rev1, end_revision=rev2, limit=limit,
2390
message_search=message, delta_type=delta_type,
2391
diff_type=diff_type, _match_using_deltas=match_using_deltas)
2392
Logger(b, rqst).show(lf)
2345
file_ids.append(file_id)
2346
filter_by_dir = filter_by_dir or (
2347
kind in ['directory', 'tree-reference'])
2350
# FIXME ? log the current subdir only RBC 20060203
2351
if revision is not None \
2352
and len(revision) > 0 and revision[0].get_branch():
2353
location = revision[0].get_branch()
2356
dir, relpath = bzrdir.BzrDir.open_containing(location)
2357
b = dir.open_branch()
2358
self.add_cleanup(b.lock_read().unlock)
2359
rev1, rev2 = _get_revision_range(revision, b, self.name())
2361
# Decide on the type of delta & diff filtering to use
2362
# TODO: add an --all-files option to make this configurable & consistent
2370
diff_type = 'partial'
2374
# Build the log formatter
2375
if log_format is None:
2376
log_format = log.log_formatter_registry.get_default(b)
2377
# Make a non-encoding output to include the diffs - bug 328007
2378
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2379
lf = log_format(show_ids=show_ids, to_file=self.outf,
2380
to_exact_file=unencoded_output,
2381
show_timezone=timezone,
2382
delta_format=get_verbosity_level(),
2384
show_advice=levels is None,
2385
author_list_handler=authors)
2387
# Choose the algorithm for doing the logging. It's annoying
2388
# having multiple code paths like this but necessary until
2389
# the underlying repository format is faster at generating
2390
# deltas or can provide everything we need from the indices.
2391
# The default algorithm - match-using-deltas - works for
2392
# multiple files and directories and is faster for small
2393
# amounts of history (200 revisions say). However, it's too
2394
# slow for logging a single file in a repository with deep
2395
# history, i.e. > 10K revisions. In the spirit of "do no
2396
# evil when adding features", we continue to use the
2397
# original algorithm - per-file-graph - for the "single
2398
# file that isn't a directory without showing a delta" case.
2399
partial_history = revision and b.repository._format.supports_chks
2400
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2401
or delta_type or partial_history)
2403
# Build the LogRequest and execute it
2404
if len(file_ids) == 0:
2406
rqst = make_log_request_dict(
2407
direction=direction, specific_fileids=file_ids,
2408
start_revision=rev1, end_revision=rev2, limit=limit,
2409
message_search=message, delta_type=delta_type,
2410
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2411
exclude_common_ancestry=exclude_common_ancestry,
2413
Logger(b, rqst).show(lf)
2398
2416
def _get_revision_range(revisionspec_list, branch, command_name):
2486
2505
help='Recurse into subdirectories.'),
2487
2506
Option('from-root',
2488
2507
help='Print paths relative to the root of the branch.'),
2489
Option('unknown', help='Print unknown files.'),
2508
Option('unknown', short_name='u',
2509
help='Print unknown files.'),
2490
2510
Option('versioned', help='Print versioned files.',
2491
2511
short_name='V'),
2492
Option('ignored', help='Print ignored files.'),
2494
help='Write an ascii NUL (\\0) separator '
2495
'between files rather than a newline.'),
2512
Option('ignored', short_name='i',
2513
help='Print ignored files.'),
2514
Option('kind', short_name='k',
2497
2515
help='List entries of a particular kind: file, directory, symlink.',
2501
2521
@display_command
2502
2522
def run(self, revision=None, verbose=False,
2503
2523
recursive=False, from_root=False,
2504
2524
unknown=False, versioned=False, ignored=False,
2505
null=False, kind=None, show_ids=False, path=None):
2525
null=False, kind=None, show_ids=False, path=None, directory=None):
2507
2527
if kind and kind not in ('file', 'directory', 'symlink'):
2508
2528
raise errors.BzrCommandError('invalid kind specified')
2542
2562
view_str = views.view_display_str(view_files)
2543
2563
note("Ignoring files outside view. View is %s" % view_str)
2547
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2548
from_dir=relpath, recursive=recursive):
2549
# Apply additional masking
2550
if not all and not selection[fc]:
2552
if kind is not None and fkind != kind:
2557
fullpath = osutils.pathjoin(relpath, fp)
2560
views.check_path_in_view(tree, fullpath)
2561
except errors.FileOutsideView:
2565
self.add_cleanup(tree.lock_read().unlock)
2566
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2567
from_dir=relpath, recursive=recursive):
2568
# Apply additional masking
2569
if not all and not selection[fc]:
2571
if kind is not None and fkind != kind:
2576
fullpath = osutils.pathjoin(relpath, fp)
2579
views.check_path_in_view(tree, fullpath)
2580
except errors.FileOutsideView:
2566
fp = osutils.pathjoin(prefix, fp)
2567
kindch = entry.kind_character()
2568
outstring = fp + kindch
2569
ui.ui_factory.clear_term()
2571
outstring = '%-8s %s' % (fc, outstring)
2572
if show_ids and fid is not None:
2573
outstring = "%-50s %s" % (outstring, fid)
2585
fp = osutils.pathjoin(prefix, fp)
2586
kindch = entry.kind_character()
2587
outstring = fp + kindch
2588
ui.ui_factory.clear_term()
2590
outstring = '%-8s %s' % (fc, outstring)
2591
if show_ids and fid is not None:
2592
outstring = "%-50s %s" % (outstring, fid)
2593
self.outf.write(outstring + '\n')
2595
self.outf.write(fp + '\0')
2598
self.outf.write(fid)
2599
self.outf.write('\0')
2607
self.outf.write('%-50s %s\n' % (outstring, my_id))
2574
2609
self.outf.write(outstring + '\n')
2576
self.outf.write(fp + '\0')
2579
self.outf.write(fid)
2580
self.outf.write('\0')
2588
self.outf.write('%-50s %s\n' % (outstring, my_id))
2590
self.outf.write(outstring + '\n')
2595
2612
class cmd_unknowns(Command):
2596
"""List unknown files.
2613
__doc__ = """List unknown files.
2600
2617
_see_also = ['ls']
2618
takes_options = ['directory']
2602
2620
@display_command
2604
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2621
def run(self, directory=u'.'):
2622
for f in WorkingTree.open_containing(directory)[0].unknowns():
2605
2623
self.outf.write(osutils.quotefn(f) + '\n')
2608
2626
class cmd_ignore(Command):
2609
"""Ignore specified files or patterns.
2627
__doc__ = """Ignore specified files or patterns.
2611
2629
See ``bzr help patterns`` for details on the syntax of patterns.
2644
2679
Ignore everything but the "debian" toplevel directory::
2646
2681
bzr ignore "RE:(?!debian/).*"
2683
Ignore everything except the "local" toplevel directory,
2684
but always ignore "*~" autosave files, even under local/::
2687
bzr ignore "!./local"
2649
2691
_see_also = ['status', 'ignored', 'patterns']
2650
2692
takes_args = ['name_pattern*']
2652
Option('old-default-rules',
2653
help='Write out the ignore rules bzr < 0.9 always used.')
2693
takes_options = ['directory',
2694
Option('default-rules',
2695
help='Display the default ignore rules that bzr uses.')
2656
def run(self, name_pattern_list=None, old_default_rules=None):
2698
def run(self, name_pattern_list=None, default_rules=None,
2657
2700
from bzrlib import ignores
2658
if old_default_rules is not None:
2659
# dump the rules and exit
2660
for pattern in ignores.OLD_DEFAULTS:
2701
if default_rules is not None:
2702
# dump the default rules and exit
2703
for pattern in ignores.USER_DEFAULTS:
2704
self.outf.write("%s\n" % pattern)
2663
2706
if not name_pattern_list:
2664
2707
raise errors.BzrCommandError("ignore requires at least one "
2665
"NAME_PATTERN or --old-default-rules")
2708
"NAME_PATTERN or --default-rules.")
2666
2709
name_pattern_list = [globbing.normalize_pattern(p)
2667
2710
for p in name_pattern_list]
2712
for p in name_pattern_list:
2713
if not globbing.Globster.is_pattern_valid(p):
2714
bad_patterns += ('\n %s' % p)
2716
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2717
ui.ui_factory.show_error(msg)
2718
raise errors.InvalidPattern('')
2668
2719
for name_pattern in name_pattern_list:
2669
2720
if (name_pattern[0] == '/' or
2670
2721
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2671
2722
raise errors.BzrCommandError(
2672
2723
"NAME_PATTERN should not be an absolute path")
2673
tree, relpath = WorkingTree.open_containing(u'.')
2724
tree, relpath = WorkingTree.open_containing(directory)
2674
2725
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2675
2726
ignored = globbing.Globster(name_pattern_list)
2728
self.add_cleanup(tree.lock_read().unlock)
2678
2729
for entry in tree.list_files():
2680
2731
if id is not None:
2681
2732
filename = entry[0]
2682
2733
if ignored.match(filename):
2683
matches.append(filename.encode('utf-8'))
2734
matches.append(filename)
2685
2735
if len(matches) > 0:
2686
print "Warning: the following files are version controlled and" \
2687
" match your ignore pattern:\n%s" \
2688
"\nThese files will continue to be version controlled" \
2689
" unless you 'bzr remove' them." % ("\n".join(matches),)
2736
self.outf.write("Warning: the following files are version controlled and"
2737
" match your ignore pattern:\n%s"
2738
"\nThese files will continue to be version controlled"
2739
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
2692
2742
class cmd_ignored(Command):
2693
"""List ignored files and the patterns that matched them.
2743
__doc__ = """List ignored files and the patterns that matched them.
2695
2745
List all the ignored files and the ignore pattern that caused the file to
2703
2753
encoding_type = 'replace'
2704
2754
_see_also = ['ignore', 'ls']
2755
takes_options = ['directory']
2706
2757
@display_command
2708
tree = WorkingTree.open_containing(u'.')[0]
2711
for path, file_class, kind, file_id, entry in tree.list_files():
2712
if file_class != 'I':
2714
## XXX: Slightly inefficient since this was already calculated
2715
pat = tree.is_ignored(path)
2716
self.outf.write('%-50s %s\n' % (path, pat))
2758
def run(self, directory=u'.'):
2759
tree = WorkingTree.open_containing(directory)[0]
2760
self.add_cleanup(tree.lock_read().unlock)
2761
for path, file_class, kind, file_id, entry in tree.list_files():
2762
if file_class != 'I':
2764
## XXX: Slightly inefficient since this was already calculated
2765
pat = tree.is_ignored(path)
2766
self.outf.write('%-50s %s\n' % (path, pat))
2721
2769
class cmd_lookup_revision(Command):
2722
"""Lookup the revision-id from a revision-number
2770
__doc__ = """Lookup the revision-id from a revision-number
2725
2773
bzr lookup-revision 33
2728
2776
takes_args = ['revno']
2777
takes_options = ['directory']
2730
2779
@display_command
2731
def run(self, revno):
2780
def run(self, revno, directory=u'.'):
2733
2782
revno = int(revno)
2734
2783
except ValueError:
2735
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2737
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2784
raise errors.BzrCommandError("not a valid revision-number: %r"
2786
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2787
self.outf.write("%s\n" % revid)
2740
2790
class cmd_export(Command):
2741
"""Export current or past revision to a destination directory or archive.
2791
__doc__ = """Export current or past revision to a destination directory or archive.
2743
2793
If no revision is specified this exports the last committed revision.
2818
2872
@display_command
2819
2873
def run(self, filename, revision=None, name_from_revision=False,
2874
filters=False, directory=None):
2821
2875
if revision is not None and len(revision) != 1:
2822
2876
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2823
2877
" one revision specifier")
2824
2878
tree, branch, relpath = \
2825
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2828
return self._run(tree, branch, relpath, filename, revision,
2829
name_from_revision, filters)
2879
_open_directory_or_containing_tree_or_branch(filename, directory)
2880
self.add_cleanup(branch.lock_read().unlock)
2881
return self._run(tree, branch, relpath, filename, revision,
2882
name_from_revision, filters)
2833
2884
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2835
2886
if tree is None:
2836
2887
tree = b.basis_tree()
2837
2888
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2889
self.add_cleanup(rev_tree.lock_read().unlock)
2839
2891
old_file_id = rev_tree.path2id(relpath)
3090
3144
'(use --file "%(f)s" to take commit message from that file)'
3091
3145
% { 'f': message })
3092
3146
ui.ui_factory.show_warning(warning_msg)
3148
message = message.replace('\r\n', '\n')
3149
message = message.replace('\r', '\n')
3151
raise errors.BzrCommandError(
3152
"please specify either --message or --file")
3094
3154
def get_message(commit_obj):
3095
3155
"""Callback to get commit message"""
3096
my_message = message
3097
if my_message is not None and '\r' in my_message:
3098
my_message = my_message.replace('\r\n', '\n')
3099
my_message = my_message.replace('\r', '\n')
3100
if my_message is None and not file:
3101
t = make_commit_message_template_encoded(tree,
3159
my_message = f.read().decode(osutils.get_user_encoding())
3162
elif message is not None:
3163
my_message = message
3165
# No message supplied: make one up.
3166
# text is the status of the tree
3167
text = make_commit_message_template_encoded(tree,
3102
3168
selected_list, diff=show_diff,
3103
3169
output_encoding=osutils.get_user_encoding())
3170
# start_message is the template generated from hooks
3171
# XXX: Warning - looks like hooks return unicode,
3172
# make_commit_message_template_encoded returns user encoding.
3173
# We probably want to be using edit_commit_message instead to
3104
3175
start_message = generate_commit_message_template(commit_obj)
3105
my_message = edit_commit_message_encoded(t,
3176
my_message = edit_commit_message_encoded(text,
3106
3177
start_message=start_message)
3107
3178
if my_message is None:
3108
3179
raise errors.BzrCommandError("please specify a commit"
3109
3180
" message with either --message or --file")
3110
elif my_message and file:
3111
raise errors.BzrCommandError(
3112
"please specify either --message or --file")
3114
my_message = codecs.open(file, 'rt',
3115
osutils.get_user_encoding()).read()
3116
3181
if my_message == "":
3117
3182
raise errors.BzrCommandError("empty commit message specified")
3118
3183
return my_message
3510
3583
def run(self, testspecs_list=None, verbose=False, one=False,
3511
3584
transport=None, benchmark=None,
3512
lsprof_timed=None, cache_dir=None,
3513
3586
first=False, list_only=False,
3514
3587
randomize=None, exclude=None, strict=False,
3515
3588
load_list=None, debugflag=None, starting_with=None, subunit=False,
3516
3589
parallel=None, lsprof_tests=False):
3517
from bzrlib.tests import selftest
3518
import bzrlib.benchmarks as benchmarks
3519
from bzrlib.benchmarks import tree_creator
3521
# Make deprecation warnings visible, unless -Werror is set
3522
symbol_versioning.activate_deprecation_warnings(override=False)
3524
if cache_dir is not None:
3525
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3590
from bzrlib import tests
3526
3592
if testspecs_list is not None:
3527
3593
pattern = '|'.join(testspecs_list)
3534
3600
raise errors.BzrCommandError("subunit not available. subunit "
3535
3601
"needs to be installed to use --subunit.")
3536
3602
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3603
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3604
# stdout, which would corrupt the subunit stream.
3605
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3606
# following code can be deleted when it's sufficiently deployed
3607
# -- vila/mgz 20100514
3608
if (sys.platform == "win32"
3609
and getattr(sys.stdout, 'fileno', None) is not None):
3611
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3538
3613
self.additional_selftest_args.setdefault(
3539
3614
'suite_decorators', []).append(parallel)
3541
test_suite_factory = benchmarks.test_suite
3542
# Unless user explicitly asks for quiet, be verbose in benchmarks
3543
verbose = not is_quiet()
3544
# TODO: should possibly lock the history file...
3545
benchfile = open(".perf_history", "at", buffering=1)
3547
test_suite_factory = None
3616
raise errors.BzrCommandError(
3617
"--benchmark is no longer supported from bzr 2.2; "
3618
"use bzr-usertest instead")
3619
test_suite_factory = None
3620
selftest_kwargs = {"verbose": verbose,
3622
"stop_on_failure": one,
3623
"transport": transport,
3624
"test_suite_factory": test_suite_factory,
3625
"lsprof_timed": lsprof_timed,
3626
"lsprof_tests": lsprof_tests,
3627
"matching_tests_first": first,
3628
"list_only": list_only,
3629
"random_seed": randomize,
3630
"exclude_pattern": exclude,
3632
"load_list": load_list,
3633
"debug_flags": debugflag,
3634
"starting_with": starting_with
3636
selftest_kwargs.update(self.additional_selftest_args)
3638
# Make deprecation warnings visible, unless -Werror is set
3639
cleanup = symbol_versioning.activate_deprecation_warnings(
3550
selftest_kwargs = {"verbose": verbose,
3552
"stop_on_failure": one,
3553
"transport": transport,
3554
"test_suite_factory": test_suite_factory,
3555
"lsprof_timed": lsprof_timed,
3556
"lsprof_tests": lsprof_tests,
3557
"bench_history": benchfile,
3558
"matching_tests_first": first,
3559
"list_only": list_only,
3560
"random_seed": randomize,
3561
"exclude_pattern": exclude,
3563
"load_list": load_list,
3564
"debug_flags": debugflag,
3565
"starting_with": starting_with
3567
selftest_kwargs.update(self.additional_selftest_args)
3568
result = selftest(**selftest_kwargs)
3642
result = tests.selftest(**selftest_kwargs)
3570
if benchfile is not None:
3572
3645
return int(not result)
3575
3648
class cmd_version(Command):
3576
"""Show version of bzr."""
3649
__doc__ = """Show version of bzr."""
3578
3651
encoding_type = 'replace'
3579
3652
takes_options = [
3749
3825
view_info = _get_view_info_for_change_reporter(tree)
3750
3826
change_reporter = delta._ChangeReporter(
3751
3827
unversioned_filter=tree.is_ignored, view_info=view_info)
3754
pb = ui.ui_factory.nested_progress_bar()
3755
cleanups.append(pb.finished)
3757
cleanups.append(tree.unlock)
3758
if location is not None:
3760
mergeable = bundle.read_mergeable_from_url(location,
3761
possible_transports=possible_transports)
3762
except errors.NotABundle:
3766
raise errors.BzrCommandError('Cannot use --uncommitted'
3767
' with bundles or merge directives.')
3769
if revision is not None:
3770
raise errors.BzrCommandError(
3771
'Cannot use -r with merge directives or bundles')
3772
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3775
if merger is None and uncommitted:
3776
if revision is not None and len(revision) > 0:
3777
raise errors.BzrCommandError('Cannot use --uncommitted and'
3778
' --revision at the same time.')
3779
merger = self.get_merger_from_uncommitted(tree, location, pb,
3781
allow_pending = False
3784
merger, allow_pending = self._get_merger_from_branch(tree,
3785
location, revision, remember, possible_transports, pb)
3787
merger.merge_type = merge_type
3788
merger.reprocess = reprocess
3789
merger.show_base = show_base
3790
self.sanity_check_merger(merger)
3791
if (merger.base_rev_id == merger.other_rev_id and
3792
merger.other_rev_id is not None):
3793
note('Nothing to do.')
3828
pb = ui.ui_factory.nested_progress_bar()
3829
self.add_cleanup(pb.finished)
3830
self.add_cleanup(tree.lock_write().unlock)
3831
if location is not None:
3833
mergeable = bundle.read_mergeable_from_url(location,
3834
possible_transports=possible_transports)
3835
except errors.NotABundle:
3839
raise errors.BzrCommandError('Cannot use --uncommitted'
3840
' with bundles or merge directives.')
3842
if revision is not None:
3843
raise errors.BzrCommandError(
3844
'Cannot use -r with merge directives or bundles')
3845
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3848
if merger is None and uncommitted:
3849
if revision is not None and len(revision) > 0:
3850
raise errors.BzrCommandError('Cannot use --uncommitted and'
3851
' --revision at the same time.')
3852
merger = self.get_merger_from_uncommitted(tree, location, None)
3853
allow_pending = False
3856
merger, allow_pending = self._get_merger_from_branch(tree,
3857
location, revision, remember, possible_transports, None)
3859
merger.merge_type = merge_type
3860
merger.reprocess = reprocess
3861
merger.show_base = show_base
3862
self.sanity_check_merger(merger)
3863
if (merger.base_rev_id == merger.other_rev_id and
3864
merger.other_rev_id is not None):
3865
note('Nothing to do.')
3868
if merger.interesting_files is not None:
3869
raise errors.BzrCommandError('Cannot pull individual files')
3870
if (merger.base_rev_id == tree.last_revision()):
3871
result = tree.pull(merger.other_branch, False,
3872
merger.other_rev_id)
3873
result.report(self.outf)
3796
if merger.interesting_files is not None:
3797
raise errors.BzrCommandError('Cannot pull individual files')
3798
if (merger.base_rev_id == tree.last_revision()):
3799
result = tree.pull(merger.other_branch, False,
3800
merger.other_rev_id)
3801
result.report(self.outf)
3803
if merger.this_basis is None:
3804
raise errors.BzrCommandError(
3805
"This branch has no commits."
3806
" (perhaps you would prefer 'bzr pull')")
3808
return self._do_preview(merger, cleanups)
3810
return self._do_interactive(merger, cleanups)
3812
return self._do_merge(merger, change_reporter, allow_pending,
3815
for cleanup in reversed(cleanups):
3875
if merger.this_basis is None:
3876
raise errors.BzrCommandError(
3877
"This branch has no commits."
3878
" (perhaps you would prefer 'bzr pull')")
3880
return self._do_preview(merger)
3882
return self._do_interactive(merger)
3884
return self._do_merge(merger, change_reporter, allow_pending,
3818
def _get_preview(self, merger, cleanups):
3887
def _get_preview(self, merger):
3819
3888
tree_merger = merger.make_merger()
3820
3889
tt = tree_merger.make_preview_transform()
3821
cleanups.append(tt.finalize)
3890
self.add_cleanup(tt.finalize)
3822
3891
result_tree = tt.get_preview_tree()
3823
3892
return result_tree
3825
def _do_preview(self, merger, cleanups):
3894
def _do_preview(self, merger):
3826
3895
from bzrlib.diff import show_diff_trees
3827
result_tree = self._get_preview(merger, cleanups)
3896
result_tree = self._get_preview(merger)
3897
path_encoding = osutils.get_diff_header_encoding()
3828
3898
show_diff_trees(merger.this_tree, result_tree, self.outf,
3829
old_label='', new_label='')
3899
old_label='', new_label='',
3900
path_encoding=path_encoding)
3831
3902
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3832
3903
merger.change_reporter = change_reporter
4019
4088
def run(self, file_list=None, merge_type=None, show_base=False,
4020
4089
reprocess=False):
4090
from bzrlib.conflicts import restore
4021
4091
if merge_type is None:
4022
4092
merge_type = _mod_merge.Merge3Merger
4023
tree, file_list = tree_files(file_list)
4026
parents = tree.get_parent_ids()
4027
if len(parents) != 2:
4028
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4029
" merges. Not cherrypicking or"
4031
repository = tree.branch.repository
4032
interesting_ids = None
4034
conflicts = tree.conflicts()
4035
if file_list is not None:
4036
interesting_ids = set()
4037
for filename in file_list:
4038
file_id = tree.path2id(filename)
4040
raise errors.NotVersionedError(filename)
4041
interesting_ids.add(file_id)
4042
if tree.kind(file_id) != "directory":
4093
tree, file_list = WorkingTree.open_containing_paths(file_list)
4094
self.add_cleanup(tree.lock_write().unlock)
4095
parents = tree.get_parent_ids()
4096
if len(parents) != 2:
4097
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4098
" merges. Not cherrypicking or"
4100
repository = tree.branch.repository
4101
interesting_ids = None
4103
conflicts = tree.conflicts()
4104
if file_list is not None:
4105
interesting_ids = set()
4106
for filename in file_list:
4107
file_id = tree.path2id(filename)
4109
raise errors.NotVersionedError(filename)
4110
interesting_ids.add(file_id)
4111
if tree.kind(file_id) != "directory":
4045
for name, ie in tree.inventory.iter_entries(file_id):
4046
interesting_ids.add(ie.file_id)
4047
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4049
# Remerge only supports resolving contents conflicts
4050
allowed_conflicts = ('text conflict', 'contents conflict')
4051
restore_files = [c.path for c in conflicts
4052
if c.typestring in allowed_conflicts]
4053
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4054
tree.set_conflicts(ConflictList(new_conflicts))
4055
if file_list is not None:
4056
restore_files = file_list
4057
for filename in restore_files:
4059
restore(tree.abspath(filename))
4060
except errors.NotConflicted:
4062
# Disable pending merges, because the file texts we are remerging
4063
# have not had those merges performed. If we use the wrong parents
4064
# list, we imply that the working tree text has seen and rejected
4065
# all the changes from the other tree, when in fact those changes
4066
# have not yet been seen.
4067
pb = ui.ui_factory.nested_progress_bar()
4068
tree.set_parent_ids(parents[:1])
4114
for name, ie in tree.inventory.iter_entries(file_id):
4115
interesting_ids.add(ie.file_id)
4116
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4118
# Remerge only supports resolving contents conflicts
4119
allowed_conflicts = ('text conflict', 'contents conflict')
4120
restore_files = [c.path for c in conflicts
4121
if c.typestring in allowed_conflicts]
4122
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4123
tree.set_conflicts(ConflictList(new_conflicts))
4124
if file_list is not None:
4125
restore_files = file_list
4126
for filename in restore_files:
4070
merger = _mod_merge.Merger.from_revision_ids(pb,
4072
merger.interesting_ids = interesting_ids
4073
merger.merge_type = merge_type
4074
merger.show_base = show_base
4075
merger.reprocess = reprocess
4076
conflicts = merger.do_merge()
4078
tree.set_parent_ids(parents)
4128
restore(tree.abspath(filename))
4129
except errors.NotConflicted:
4131
# Disable pending merges, because the file texts we are remerging
4132
# have not had those merges performed. If we use the wrong parents
4133
# list, we imply that the working tree text has seen and rejected
4134
# all the changes from the other tree, when in fact those changes
4135
# have not yet been seen.
4136
tree.set_parent_ids(parents[:1])
4138
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4139
merger.interesting_ids = interesting_ids
4140
merger.merge_type = merge_type
4141
merger.show_base = show_base
4142
merger.reprocess = reprocess
4143
conflicts = merger.do_merge()
4145
tree.set_parent_ids(parents)
4082
4146
if conflicts > 0:
4111
4175
created as above. Directories containing unknown files will not be
4114
The working tree contains a list of pending merged revisions, which will
4115
be included as parents in the next commit. Normally, revert clears that
4116
list as well as reverting the files. If any files are specified, revert
4117
leaves the pending merge list alone and reverts only the files. Use "bzr
4118
revert ." in the tree root to revert all files but keep the merge record,
4119
and "bzr revert --forget-merges" to clear the pending merge list without
4178
The working tree contains a list of revisions that have been merged but
4179
not yet committed. These revisions will be included as additional parents
4180
of the next commit. Normally, using revert clears that list as well as
4181
reverting the files. If any files are specified, revert leaves the list
4182
of uncommitted merges alone and reverts only the files. Use ``bzr revert
4183
.`` in the tree root to revert all files but keep the recorded merges,
4184
and ``bzr revert --forget-merges`` to clear the pending merge list without
4120
4185
reverting any files.
4122
Using "bzr revert --forget-merges", it is possible to apply the changes
4123
from an arbitrary merge as a single revision. To do this, perform the
4124
merge as desired. Then doing revert with the "--forget-merges" option will
4125
keep the content of the tree as it was, but it will clear the list of
4126
pending merges. The next commit will then contain all of the changes that
4127
would have been in the merge, but without any mention of the other parent
4128
revisions. Because this technique forgets where these changes originated,
4129
it may cause additional conflicts on later merges involving the source and
4187
Using "bzr revert --forget-merges", it is possible to apply all of the
4188
changes from a branch in a single revision. To do this, perform the merge
4189
as desired. Then doing revert with the "--forget-merges" option will keep
4190
the content of the tree as it was, but it will clear the list of pending
4191
merges. The next commit will then contain all of the changes that are
4192
present in the other branch, but without any other parent revisions.
4193
Because this technique forgets where these changes originated, it may
4194
cause additional conflicts on later merges involving the same source and
4130
4195
target branches.
4142
4207
def run(self, revision=None, no_backup=False, file_list=None,
4143
4208
forget_merges=None):
4144
tree, file_list = tree_files(file_list)
4148
tree.set_parent_ids(tree.get_parent_ids()[:1])
4150
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
4209
tree, file_list = WorkingTree.open_containing_paths(file_list)
4210
self.add_cleanup(tree.lock_tree_write().unlock)
4212
tree.set_parent_ids(tree.get_parent_ids()[:1])
4214
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
4155
4217
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4156
4218
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4157
pb = ui.ui_factory.nested_progress_bar()
4159
tree.revert(file_list, rev_tree, not no_backup, pb,
4160
report_changes=True)
4219
tree.revert(file_list, rev_tree, not no_backup, None,
4220
report_changes=True)
4165
4223
class cmd_assert_fail(Command):
4166
"""Test reporting of assertion failures"""
4224
__doc__ = """Test reporting of assertion failures"""
4167
4225
# intended just for use in testing
4314
4378
_get_revision_range(revision,
4315
4379
remote_branch, self.name()))
4317
local_branch.lock_read()
4319
remote_branch.lock_read()
4321
local_extra, remote_extra = find_unmerged(
4322
local_branch, remote_branch, restrict,
4323
backward=not reverse,
4324
include_merges=include_merges,
4325
local_revid_range=local_revid_range,
4326
remote_revid_range=remote_revid_range)
4328
if log_format is None:
4329
registry = log.log_formatter_registry
4330
log_format = registry.get_default(local_branch)
4331
lf = log_format(to_file=self.outf,
4333
show_timezone='original')
4336
if local_extra and not theirs_only:
4337
message("You have %d extra revision(s):\n" %
4339
for revision in iter_log_revisions(local_extra,
4340
local_branch.repository,
4342
lf.log_revision(revision)
4343
printed_local = True
4346
printed_local = False
4348
if remote_extra and not mine_only:
4349
if printed_local is True:
4351
message("You are missing %d revision(s):\n" %
4353
for revision in iter_log_revisions(remote_extra,
4354
remote_branch.repository,
4356
lf.log_revision(revision)
4359
if mine_only and not local_extra:
4360
# We checked local, and found nothing extra
4361
message('This branch is up to date.\n')
4362
elif theirs_only and not remote_extra:
4363
# We checked remote, and found nothing extra
4364
message('Other branch is up to date.\n')
4365
elif not (mine_only or theirs_only or local_extra or
4367
# We checked both branches, and neither one had extra
4369
message("Branches are up to date.\n")
4371
remote_branch.unlock()
4373
local_branch.unlock()
4381
local_extra, remote_extra = find_unmerged(
4382
local_branch, remote_branch, restrict,
4383
backward=not reverse,
4384
include_merges=include_merges,
4385
local_revid_range=local_revid_range,
4386
remote_revid_range=remote_revid_range)
4388
if log_format is None:
4389
registry = log.log_formatter_registry
4390
log_format = registry.get_default(local_branch)
4391
lf = log_format(to_file=self.outf,
4393
show_timezone='original')
4396
if local_extra and not theirs_only:
4397
message("You have %d extra revision(s):\n" %
4399
for revision in iter_log_revisions(local_extra,
4400
local_branch.repository,
4402
lf.log_revision(revision)
4403
printed_local = True
4406
printed_local = False
4408
if remote_extra and not mine_only:
4409
if printed_local is True:
4411
message("You are missing %d revision(s):\n" %
4413
for revision in iter_log_revisions(remote_extra,
4414
remote_branch.repository,
4416
lf.log_revision(revision)
4419
if mine_only and not local_extra:
4420
# We checked local, and found nothing extra
4421
message('This branch is up to date.\n')
4422
elif theirs_only and not remote_extra:
4423
# We checked remote, and found nothing extra
4424
message('Other branch is up to date.\n')
4425
elif not (mine_only or theirs_only or local_extra or
4427
# We checked both branches, and neither one had extra
4429
message("Branches are up to date.\n")
4374
4431
if not status_code and parent is None and other_branch is not None:
4375
local_branch.lock_write()
4377
# handle race conditions - a parent might be set while we run.
4378
if local_branch.get_parent() is None:
4379
local_branch.set_parent(remote_branch.base)
4381
local_branch.unlock()
4432
self.add_cleanup(local_branch.lock_write().unlock)
4433
# handle race conditions - a parent might be set while we run.
4434
if local_branch.get_parent() is None:
4435
local_branch.set_parent(remote_branch.base)
4382
4436
return status_code
4385
4439
class cmd_pack(Command):
4386
"""Compress the data within a repository."""
4440
__doc__ = """Compress the data within a repository.
4442
This operation compresses the data within a bazaar repository. As
4443
bazaar supports automatic packing of repository, this operation is
4444
normally not required to be done manually.
4446
During the pack operation, bazaar takes a backup of existing repository
4447
data, i.e. pack files. This backup is eventually removed by bazaar
4448
automatically when it is safe to do so. To save disk space by removing
4449
the backed up pack files, the --clean-obsolete-packs option may be
4452
Warning: If you use --clean-obsolete-packs and your machine crashes
4453
during or immediately after repacking, you may be left with a state
4454
where the deletion has been written to disk but the new packs have not
4455
been. In this case the repository may be unusable.
4388
4458
_see_also = ['repositories']
4389
4459
takes_args = ['branch_or_repo?']
4461
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4391
def run(self, branch_or_repo='.'):
4464
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4392
4465
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4394
4467
branch = dir.open_branch()
4395
4468
repository = branch.repository
4396
4469
except errors.NotBranchError:
4397
4470
repository = dir.open_repository()
4471
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4401
4474
class cmd_plugins(Command):
4402
"""List the installed plugins.
4475
__doc__ = """List the installed plugins.
4404
4477
This command displays the list of installed plugins including
4405
4478
version of plugin and a short description of each.
4495
4565
Option('long', help='Show commit date in annotations.'),
4499
4570
encoding_type = 'exact'
4501
4572
@display_command
4502
4573
def run(self, filename, all=False, long=False, revision=None,
4574
show_ids=False, directory=None):
4504
4575
from bzrlib.annotate import annotate_file, annotate_file_tree
4505
4576
wt, branch, relpath = \
4506
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4512
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4514
file_id = wt.path2id(relpath)
4516
file_id = tree.path2id(relpath)
4518
raise errors.NotVersionedError(filename)
4519
file_version = tree.inventory[file_id].revision
4520
if wt is not None and revision is None:
4521
# If there is a tree and we're not annotating historical
4522
# versions, annotate the working tree's content.
4523
annotate_file_tree(wt, file_id, self.outf, long, all,
4526
annotate_file(branch, file_version, file_id, long, all, self.outf,
4577
_open_directory_or_containing_tree_or_branch(filename, directory)
4579
self.add_cleanup(wt.lock_read().unlock)
4581
self.add_cleanup(branch.lock_read().unlock)
4582
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4583
self.add_cleanup(tree.lock_read().unlock)
4585
file_id = wt.path2id(relpath)
4587
file_id = tree.path2id(relpath)
4589
raise errors.NotVersionedError(filename)
4590
file_version = tree.inventory[file_id].revision
4591
if wt is not None and revision is None:
4592
# If there is a tree and we're not annotating historical
4593
# versions, annotate the working tree's content.
4594
annotate_file_tree(wt, file_id, self.outf, long, all,
4597
annotate_file(branch, file_version, file_id, long, all, self.outf,
4535
4601
class cmd_re_sign(Command):
4536
"""Create a digital signature for an existing revision."""
4602
__doc__ = """Create a digital signature for an existing revision."""
4537
4603
# TODO be able to replace existing ones.
4539
4605
hidden = True # is this right ?
4540
4606
takes_args = ['revision_id*']
4541
takes_options = ['revision']
4607
takes_options = ['directory', 'revision']
4543
def run(self, revision_id_list=None, revision=None):
4609
def run(self, revision_id_list=None, revision=None, directory=u'.'):
4544
4610
if revision_id_list is not None and revision is not None:
4545
4611
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4546
4612
if revision_id_list is None and revision is None:
4547
4613
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4548
b = WorkingTree.open_containing(u'.')[0].branch
4551
return self._run(b, revision_id_list, revision)
4614
b = WorkingTree.open_containing(directory)[0].branch
4615
self.add_cleanup(b.lock_write().unlock)
4616
return self._run(b, revision_id_list, revision)
4555
4618
def _run(self, b, revision_id_list, revision):
4556
4619
import bzrlib.gpg as gpg
4749
4809
end_revision=last_revno)
4752
print 'Dry-run, pretending to remove the above revisions.'
4754
val = raw_input('Press <enter> to continue')
4812
self.outf.write('Dry-run, pretending to remove'
4813
' the above revisions.\n')
4756
print 'The above revision(s) will be removed.'
4758
val = raw_input('Are you sure [y/N]? ')
4759
if val.lower() not in ('y', 'yes'):
4815
self.outf.write('The above revision(s) will be removed.\n')
4818
if not ui.ui_factory.confirm_action(
4819
'Uncommit these revisions',
4820
'bzrlib.builtins.uncommit',
4822
self.outf.write('Canceled\n')
4763
4825
mutter('Uncommitting from {%s} to {%s}',
4764
4826
last_rev_id, rev_id)
4765
4827
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4766
4828
revno=revno, local=local)
4767
note('You can restore the old tip by running:\n'
4768
' bzr pull . -r revid:%s', last_rev_id)
4829
self.outf.write('You can restore the old tip by running:\n'
4830
' bzr pull . -r revid:%s\n' % last_rev_id)
4771
4833
class cmd_break_lock(Command):
4772
"""Break a dead lock on a repository, branch or working directory.
4834
__doc__ = """Break a dead lock.
4836
This command breaks a lock on a repository, branch, working directory or
4774
4839
CAUTION: Locks should only be broken when you are sure that the process
4775
4840
holding the lock has been stopped.
4777
You can get information on what locks are open via the 'bzr info' command.
4842
You can get information on what locks are open via the 'bzr info
4843
[location]' command.
4847
bzr break-lock bzr+ssh://example.com/bzr/foo
4848
bzr break-lock --conf ~/.bazaar
4782
4851
takes_args = ['location?']
4854
help='LOCATION is the directory where the config lock is.'),
4856
help='Do not ask for confirmation before breaking the lock.'),
4784
def run(self, location=None, show=False):
4859
def run(self, location=None, config=False, force=False):
4785
4860
if location is None:
4786
4861
location = u'.'
4787
control, relpath = bzrdir.BzrDir.open_containing(location)
4789
control.break_lock()
4790
except NotImplementedError:
4863
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
4865
{'bzrlib.lockdir.break': True})
4867
conf = _mod_config.LockableConfig(file_name=location)
4870
control, relpath = bzrdir.BzrDir.open_containing(location)
4872
control.break_lock()
4873
except NotImplementedError:
4794
4877
class cmd_wait_until_signalled(Command):
4795
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4878
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4797
4880
This just prints a line to signal when it is ready, then blocks on stdin.
5055
5139
directly from the merge directive, without retrieving data from a
5058
If --no-bundle is specified, then public_branch is needed (and must be
5059
up-to-date), so that the receiver can perform the merge using the
5060
public_branch. The public_branch is always included if known, so that
5061
people can check it later.
5063
The submit branch defaults to the parent, but can be overridden. Both
5064
submit branch and public branch will be remembered if supplied.
5066
If a public_branch is known for the submit_branch, that public submit
5067
branch is used in the merge instructions. This means that a local mirror
5068
can be used as your actual submit branch, once you have set public_branch
5142
`bzr send` creates a compact data set that, when applied using bzr
5143
merge, has the same effect as merging from the source branch.
5145
By default the merge directive is self-contained and can be applied to any
5146
branch containing submit_branch in its ancestory without needing access to
5149
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5150
revisions, but only a structured request to merge from the
5151
public_location. In that case the public_branch is needed and it must be
5152
up-to-date and accessible to the recipient. The public_branch is always
5153
included if known, so that people can check it later.
5155
The submit branch defaults to the parent of the source branch, but can be
5156
overridden. Both submit branch and public branch will be remembered in
5157
branch.conf the first time they are used for a particular branch. The
5158
source branch defaults to that containing the working directory, but can
5159
be changed using --from.
5161
In order to calculate those changes, bzr must analyse the submit branch.
5162
Therefore it is most efficient for the submit branch to be a local mirror.
5163
If a public location is known for the submit_branch, that location is used
5164
in the merge directive.
5166
The default behaviour is to send the merge directive by mail, unless -o is
5167
given, in which case it is sent to a file.
5071
5169
Mail is sent using your preferred mail program. This should be transparent
5072
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
5170
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
5073
5171
If the preferred client can't be found (or used), your editor will be used.
5075
5173
To use a specific mail program, set the mail_client configuration option.
5230
5332
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5231
5333
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5335
If no tag name is specified it will be determined through the
5336
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5337
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5234
5341
_see_also = ['commit', 'tags']
5235
takes_args = ['tag_name']
5342
takes_args = ['tag_name?']
5236
5343
takes_options = [
5237
5344
Option('delete',
5238
5345
help='Delete this tag rather than placing it.',
5241
help='Branch in which to place the tag.',
5347
custom_help('directory',
5348
help='Branch in which to place the tag.'),
5245
5349
Option('force',
5246
5350
help='Replace existing tags.',
5251
def run(self, tag_name,
5355
def run(self, tag_name=None,
5257
5361
branch, relpath = Branch.open_containing(directory)
5261
branch.tags.delete_tag(tag_name)
5262
self.outf.write('Deleted tag %s.\n' % tag_name)
5362
self.add_cleanup(branch.lock_write().unlock)
5364
if tag_name is None:
5365
raise errors.BzrCommandError("No tag specified to delete.")
5366
branch.tags.delete_tag(tag_name)
5367
self.outf.write('Deleted tag %s.\n' % tag_name)
5370
if len(revision) != 1:
5371
raise errors.BzrCommandError(
5372
"Tags can only be placed on a single revision, "
5374
revision_id = revision[0].as_revision_id(branch)
5265
if len(revision) != 1:
5266
raise errors.BzrCommandError(
5267
"Tags can only be placed on a single revision, "
5269
revision_id = revision[0].as_revision_id(branch)
5271
revision_id = branch.last_revision()
5272
if (not force) and branch.tags.has_tag(tag_name):
5273
raise errors.TagAlreadyExists(tag_name)
5274
branch.tags.set_tag(tag_name, revision_id)
5275
self.outf.write('Created tag %s.\n' % tag_name)
5376
revision_id = branch.last_revision()
5377
if tag_name is None:
5378
tag_name = branch.automatic_tag_name(revision_id)
5379
if tag_name is None:
5380
raise errors.BzrCommandError(
5381
"Please specify a tag name.")
5382
if (not force) and branch.tags.has_tag(tag_name):
5383
raise errors.TagAlreadyExists(tag_name)
5384
branch.tags.set_tag(tag_name, revision_id)
5385
self.outf.write('Created tag %s.\n' % tag_name)
5280
5388
class cmd_tags(Command):
5389
__doc__ = """List tags.
5283
5391
This command shows a table of tag names and the revisions they reference.
5286
5394
_see_also = ['tag']
5287
5395
takes_options = [
5289
help='Branch whose tags should be displayed.',
5396
custom_help('directory',
5397
help='Branch whose tags should be displayed.'),
5293
5398
RegistryOption.from_kwargs('sort',
5294
5399
'Sort tags by different criteria.', title='Sorting',
5295
5400
alpha='Sort tags lexicographically (default).',
5318
graph = branch.repository.get_graph()
5319
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5320
revid1, revid2 = rev1.rev_id, rev2.rev_id
5321
# only show revisions between revid1 and revid2 (inclusive)
5322
tags = [(tag, revid) for tag, revid in tags if
5323
graph.is_between(revid, revid1, revid2)]
5326
elif sort == 'time':
5328
for tag, revid in tags:
5330
revobj = branch.repository.get_revision(revid)
5331
except errors.NoSuchRevision:
5332
timestamp = sys.maxint # place them at the end
5334
timestamp = revobj.timestamp
5335
timestamps[revid] = timestamp
5336
tags.sort(key=lambda x: timestamps[x[1]])
5338
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5339
for index, (tag, revid) in enumerate(tags):
5341
revno = branch.revision_id_to_dotted_revno(revid)
5342
if isinstance(revno, tuple):
5343
revno = '.'.join(map(str, revno))
5344
except errors.NoSuchRevision:
5345
# Bad tag data/merges can lead to tagged revisions
5346
# which are not in this branch. Fail gracefully ...
5348
tags[index] = (tag, revno)
5420
self.add_cleanup(branch.lock_read().unlock)
5422
graph = branch.repository.get_graph()
5423
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5424
revid1, revid2 = rev1.rev_id, rev2.rev_id
5425
# only show revisions between revid1 and revid2 (inclusive)
5426
tags = [(tag, revid) for tag, revid in tags if
5427
graph.is_between(revid, revid1, revid2)]
5430
elif sort == 'time':
5432
for tag, revid in tags:
5434
revobj = branch.repository.get_revision(revid)
5435
except errors.NoSuchRevision:
5436
timestamp = sys.maxint # place them at the end
5438
timestamp = revobj.timestamp
5439
timestamps[revid] = timestamp
5440
tags.sort(key=lambda x: timestamps[x[1]])
5442
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5443
for index, (tag, revid) in enumerate(tags):
5445
revno = branch.revision_id_to_dotted_revno(revid)
5446
if isinstance(revno, tuple):
5447
revno = '.'.join(map(str, revno))
5448
except errors.NoSuchRevision:
5449
# Bad tag data/merges can lead to tagged revisions
5450
# which are not in this branch. Fail gracefully ...
5452
tags[index] = (tag, revno)
5351
5454
for tag, revspec in tags:
5352
5455
self.outf.write('%-20s %s\n' % (tag, revspec))
5355
5458
class cmd_reconfigure(Command):
5356
"""Reconfigure the type of a bzr directory.
5459
__doc__ = """Reconfigure the type of a bzr directory.
5358
5461
A target configuration must be specified.
5466
5569
that of the master.
5469
takes_args = ['to_location']
5470
takes_options = [Option('force',
5572
takes_args = ['to_location?']
5573
takes_options = ['directory',
5471
5575
help='Switch even if local commits will be lost.'),
5472
5577
Option('create-branch', short_name='b',
5473
5578
help='Create the target branch from this one before'
5474
5579
' switching to it.'),
5477
def run(self, to_location, force=False, create_branch=False):
5582
def run(self, to_location=None, force=False, create_branch=False,
5583
revision=None, directory=u'.'):
5478
5584
from bzrlib import switch
5585
tree_location = directory
5586
revision = _get_one_revision('switch', revision)
5480
5587
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5588
if to_location is None:
5589
if revision is None:
5590
raise errors.BzrCommandError('You must supply either a'
5591
' revision or a location')
5592
to_location = tree_location
5482
5594
branch = control_dir.open_branch()
5483
5595
had_explicit_nick = branch.get_config().has_explicit_nickname()
5896
6033
self.outf.write('%s %s\n' % (path, location))
5899
# these get imported and then picked up by the scan for cmd_*
5900
# TODO: Some more consistent way to split command definitions across files;
5901
# we do need to load at least some information about them to know of
5902
# aliases. ideally we would avoid loading the implementation until the
5903
# details were needed.
5904
from bzrlib.cmd_version_info import cmd_version_info
5905
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
5906
from bzrlib.bundle.commands import (
5909
from bzrlib.foreign import cmd_dpush
5910
from bzrlib.sign_my_commits import cmd_sign_my_commits
5911
from bzrlib.weave_commands import cmd_versionedfile_list, \
5912
cmd_weave_plan_merge, cmd_weave_merge_text
6036
def _register_lazy_builtins():
6037
# register lazy builtins from other modules; called at startup and should
6038
# be only called once.
6039
for (name, aliases, module_name) in [
6040
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6041
('cmd_dpush', [], 'bzrlib.foreign'),
6042
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6043
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6044
('cmd_conflicts', [], 'bzrlib.conflicts'),
6045
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6047
builtin_command_registry.register_lazy(name, aliases, module_name)