175
166
:return: workingtree, [relative_paths]
177
return WorkingTree.open_containing_paths(
178
file_list, default_directory='.',
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)
183
217
def _get_view_info_for_change_reporter(tree):
320
336
takes_args = ['revision_id?']
321
takes_options = ['directory', 'revision']
337
takes_options = ['revision']
322
338
# cat-revision is more for frontends so should be exact
323
339
encoding = 'strict'
325
def print_revision(self, revisions, revid):
326
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
327
record = stream.next()
328
if record.storage_kind == 'absent':
329
raise errors.NoSuchRevision(revisions, revid)
330
revtext = record.get_bytes_as('fulltext')
331
self.outf.write(revtext.decode('utf-8'))
334
def run(self, revision_id=None, revision=None, directory=u'.'):
342
def run(self, revision_id=None, revision=None):
335
343
if revision_id is not None and revision is not None:
336
raise errors.BzrCommandError(gettext('You can only supply one of'
337
' revision_id or --revision'))
344
raise errors.BzrCommandError('You can only supply one of'
345
' revision_id or --revision')
338
346
if revision_id is None and revision is None:
339
raise errors.BzrCommandError(gettext('You must supply either'
340
' --revision or a revision_id'))
342
b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
344
revisions = b.repository.revisions
345
if revisions is None:
346
raise errors.BzrCommandError(gettext('Repository %r does not support '
347
'access to raw revision texts'))
349
b.repository.lock_read()
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.print_revision(revisions, revision_id)
356
except errors.NoSuchRevision:
357
msg = gettext("The repository {0} contains no revision {1}.").format(
358
b.repository.base, revision_id)
359
raise errors.BzrCommandError(msg)
360
elif revision is not None:
363
raise errors.BzrCommandError(
364
gettext('You cannot specify a NULL revision.'))
365
rev_id = rev.as_revision_id(b)
366
self.print_revision(revisions, rev_id)
368
b.repository.unlock()
347
raise errors.BzrCommandError('You must supply either'
348
' --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'))
371
369
class cmd_dump_btree(Command):
372
__doc__ = """Dump the contents of a btree index file to stdout.
370
"""Dump the contents of a btree index file to stdout.
374
372
PATH is a btree index file, it can be any URL. This includes things like
375
373
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
461
451
To re-create the working tree, use "bzr checkout".
463
453
_see_also = ['checkout', 'working-trees']
464
takes_args = ['location*']
454
takes_args = ['location?']
465
455
takes_options = [
467
457
help='Remove the working tree even if it has '
468
'uncommitted or shelved changes.'),
458
'uncommitted changes.'),
471
def run(self, location_list, force=False):
472
if not location_list:
475
for location in location_list:
476
d = bzrdir.BzrDir.open(location)
479
working = d.open_workingtree()
480
except errors.NoWorkingTree:
481
raise errors.BzrCommandError(gettext("No working tree to remove"))
482
except errors.NotLocalUrl:
483
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
484
" of a remote path"))
486
if (working.has_changes()):
487
raise errors.UncommittedChanges(working)
488
if working.get_shelf_manager().last_shelf() is not None:
489
raise errors.ShelvedChanges(working)
491
if working.user_url != working.branch.user_url:
492
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
493
" from a lightweight checkout"))
495
d.destroy_workingtree()
498
class cmd_repair_workingtree(Command):
499
__doc__ = """Reset the working tree state file.
501
This is not meant to be used normally, but more as a way to recover from
502
filesystem corruption, etc. This rebuilds the working inventory back to a
503
'known good' state. Any new modifications (adding a file, renaming, etc)
504
will be lost, though modified files will still be detected as such.
506
Most users will want something more like "bzr revert" or "bzr update"
507
unless the state file has become corrupted.
509
By default this attempts to recover the current state by looking at the
510
headers of the state file. If the state file is too corrupted to even do
511
that, you can supply --revision to force the state of the tree.
514
takes_options = ['revision', 'directory',
516
help='Reset the tree even if it doesn\'t appear to be'
521
def run(self, revision=None, directory='.', force=False):
522
tree, _ = WorkingTree.open_containing(directory)
523
self.add_cleanup(tree.lock_tree_write().unlock)
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"
527
except errors.BzrError:
528
pass # There seems to be a real error here, so we'll reset
531
raise errors.BzrCommandError(gettext(
532
'The tree does not appear to be corrupt. You probably'
533
' want "bzr revert" instead. Use "--force" if you are'
534
' sure you want to reset the working tree.'))
538
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
540
tree.reset_state(revision_ids)
541
except errors.BzrError, e:
542
if revision_ids is None:
543
extra = (gettext(', the header appears corrupt, try passing -r -1'
544
' to set the state to the last commit'))
547
raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
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()
550
484
class cmd_revno(Command):
551
__doc__ = """Show current revision number.
485
"""Show current revision number.
553
487
This is equal to the number of revisions on this branch.
602
545
wt = WorkingTree.open_containing(directory)[0]
604
self.add_cleanup(wt.lock_read().unlock)
605
548
except (errors.NoWorkingTree, errors.NotLocalUrl):
607
550
b = Branch.open_containing(directory)[0]
608
self.add_cleanup(b.lock_read().unlock)
610
if revision is not None:
611
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
612
if revision_info_list is not None:
613
for rev_str in revision_info_list:
614
rev_spec = RevisionSpec.from_string(rev_str)
615
revision_ids.append(rev_spec.as_revision_id(b))
616
# No arguments supplied, default to the last revision
617
if len(revision_ids) == 0:
620
raise errors.NoWorkingTree(directory)
621
revision_ids.append(wt.last_revision())
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])
623
revision_ids.append(b.last_revision())
627
for revision_id in revision_ids:
629
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
630
revno = '.'.join(str(i) for i in dotted_revno)
631
except errors.NoSuchRevision:
633
maxlen = max(maxlen, len(revno))
634
revinfos.append([revno, revision_id])
637
585
for ri in revinfos:
638
586
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
641
589
class cmd_add(Command):
642
__doc__ = """Add specified files or directories.
590
"""Add specified files or directories.
644
592
In non-recursive mode, all the named items are added, regardless
645
593
of whether they were previously ignored. A warning is given if
790
731
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
791
732
if kind and kind not in ['file', 'directory', 'symlink']:
792
raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
733
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
794
735
revision = _get_one_revision('inventory', revision)
795
work_tree, file_list = WorkingTree.open_containing_paths(file_list)
796
self.add_cleanup(work_tree.lock_read().unlock)
797
if revision is not None:
798
tree = revision.as_tree(work_tree.branch)
800
extra_trees = [work_tree]
801
self.add_cleanup(tree.lock_read().unlock)
806
if file_list is not None:
807
file_ids = tree.paths2ids(file_list, trees=extra_trees,
808
require_versioned=True)
809
# find_ids_across_trees may include some paths that don't
812
(tree.id2path(file_id), tree.inventory[file_id])
813
for file_id in file_ids if tree.has_id(file_id))
815
entries = tree.inventory.entries()
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:
818
762
for path, entry in entries:
819
763
if kind and kind != entry.kind:
860
804
return self.run_auto(names_list, after, dry_run)
862
raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
806
raise errors.BzrCommandError('--dry-run requires --auto.')
863
807
if names_list is None:
865
809
if len(names_list) < 2:
866
raise errors.BzrCommandError(gettext("missing file argument"))
867
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
868
self.add_cleanup(tree.lock_tree_write().unlock)
869
self._run(tree, names_list, rel_names, after)
810
raise errors.BzrCommandError("missing file argument")
811
tree, rel_names = tree_files(names_list, canonicalize=False)
812
tree.lock_tree_write()
814
self._run(tree, names_list, rel_names, after)
871
818
def run_auto(self, names_list, after, dry_run):
872
819
if names_list is not None and len(names_list) > 1:
873
raise errors.BzrCommandError(gettext('Only one path may be specified to'
820
raise errors.BzrCommandError('Only one path may be specified to'
876
raise errors.BzrCommandError(gettext('--after cannot be specified with'
878
work_tree, file_list = WorkingTree.open_containing_paths(
879
names_list, default_directory='.')
880
self.add_cleanup(work_tree.lock_tree_write().unlock)
881
rename_map.RenameMap.guess_renames(work_tree, dry_run)
823
raise errors.BzrCommandError('--after cannot be specified with'
825
work_tree, file_list = tree_files(names_list, default_branch='.')
826
work_tree.lock_tree_write()
828
rename_map.RenameMap.guess_renames(work_tree, dry_run)
883
832
def _run(self, tree, names_list, rel_names, after):
884
833
into_existing = osutils.isdir(names_list[-1])
1062
1006
branch_from = Branch.open(location,
1063
1007
possible_transports=possible_transports)
1064
self.add_cleanup(branch_from.lock_read().unlock)
1065
# Remembers if asked explicitly or no previous location is set
1067
or (remember is None and branch_to.get_parent() is None)):
1009
if branch_to.get_parent() is None or remember:
1068
1010
branch_to.set_parent(branch_from.base)
1070
if revision is not None:
1071
revision_id = revision.as_revision_id(branch_from)
1073
if tree_to is not None:
1074
view_info = _get_view_info_for_change_reporter(tree_to)
1075
change_reporter = delta._ChangeReporter(
1076
unversioned_filter=tree_to.is_ignored,
1077
view_info=view_info)
1078
result = tree_to.pull(
1079
branch_from, overwrite, revision_id, change_reporter,
1080
local=local, show_base=show_base)
1082
result = branch_to.pull(
1083
branch_from, overwrite, revision_id, local=local)
1085
result.report(self.outf)
1086
if verbose and result.old_revid != result.new_revid:
1087
log.show_branch_change(
1088
branch_to, self.outf, result.old_revno,
1090
if getattr(result, 'tag_conflicts', None):
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()
1096
1044
class cmd_push(Command):
1097
__doc__ = """Update a mirror of this branch.
1045
"""Update a mirror of this branch.
1099
1047
The target branch will not have its working tree populated because this
1100
1048
is both expensive, and is not supported on remote file systems.
1187
1144
# error by the feedback given to them. RBC 20080227.
1188
1145
stacked_on = parent_url
1189
1146
if not stacked_on:
1190
raise errors.BzrCommandError(gettext(
1191
"Could not determine branch to refer to."))
1147
raise errors.BzrCommandError(
1148
"Could not determine branch to refer to.")
1193
1150
# Get the destination location
1194
1151
if location is None:
1195
1152
stored_loc = br_from.get_push_location()
1196
1153
if stored_loc is None:
1197
raise errors.BzrCommandError(gettext(
1198
"No push location known or specified."))
1154
raise errors.BzrCommandError(
1155
"No push location known or specified.")
1200
1157
display_url = urlutils.unescape_for_display(stored_loc,
1201
1158
self.outf.encoding)
1202
note(gettext("Using saved push location: %s") % display_url)
1159
self.outf.write("Using saved push location: %s\n" % display_url)
1203
1160
location = stored_loc
1205
1162
_show_push_branch(br_from, revision_id, location, self.outf,
1206
1163
verbose=verbose, overwrite=overwrite, remember=remember,
1207
1164
stacked_on=stacked_on, create_prefix=create_prefix,
1208
use_existing_dir=use_existing_dir, no_tree=no_tree)
1165
use_existing_dir=use_existing_dir)
1211
1168
class cmd_branch(Command):
1212
__doc__ = """Create a new branch that is a copy of an existing branch.
1169
"""Create a new branch that is a copy of an existing branch.
1214
1171
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1215
1172
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1246
1199
' directory exists, but does not already'
1247
1200
' have a control directory. This flag will'
1248
1201
' allow branch to proceed.'),
1250
help="Bind new branch to from location."),
1252
1203
aliases = ['get', 'clone']
1254
1205
def run(self, from_location, to_location=None, revision=None,
1255
1206
hardlink=False, stacked=False, standalone=False, no_tree=False,
1256
use_existing_dir=False, switch=False, bind=False,
1207
use_existing_dir=False, switch=False):
1258
1208
from bzrlib import switch as _mod_switch
1259
1209
from bzrlib.tag import _merge_tags_if_possible
1260
if self.invoked_as in ['get', 'clone']:
1261
ui.ui_factory.show_user_warning(
1262
'deprecated_command',
1263
deprecated_name=self.invoked_as,
1264
recommended_name='branch',
1265
deprecated_in_version='2.4')
1266
1210
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1268
if not (hardlink or files_from):
1269
# accelerator_tree is usually slower because you have to read N
1270
# files (no readahead, lots of seeks, etc), but allow the user to
1271
# explicitly request it
1272
accelerator_tree = None
1273
if files_from is not None and files_from != from_location:
1274
accelerator_tree = WorkingTree.open(files_from)
1275
1212
revision = _get_one_revision('branch', revision)
1276
self.add_cleanup(br_from.lock_read().unlock)
1277
if revision is not None:
1278
revision_id = revision.as_revision_id(br_from)
1280
# FIXME - wt.last_revision, fallback to branch, fall back to
1281
# None or perhaps NULL_REVISION to mean copy nothing
1283
revision_id = br_from.last_revision()
1284
if to_location is None:
1285
to_location = urlutils.derive_to_location(from_location)
1286
to_transport = transport.get_transport(to_location)
1288
to_transport.mkdir('.')
1289
except errors.FileExists:
1290
if not use_existing_dir:
1291
raise errors.BzrCommandError(gettext('Target directory "%s" '
1292
'already exists.') % to_location)
1215
if revision is not None:
1216
revision_id = revision.as_revision_id(br_from)
1295
bzrdir.BzrDir.open_from_transport(to_transport)
1296
except errors.NotBranchError:
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)
1299
raise errors.AlreadyBranchError(to_location)
1300
except errors.NoSuchFile:
1301
raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
1304
# preserve whatever source format we have.
1305
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1306
possible_transports=[to_transport],
1307
accelerator_tree=accelerator_tree,
1308
hardlink=hardlink, stacked=stacked,
1309
force_new_repo=standalone,
1310
create_tree_if_local=not no_tree,
1311
source_branch=br_from)
1312
branch = dir.open_branch()
1313
except errors.NoSuchRevision:
1314
to_transport.delete_tree('.')
1315
msg = gettext("The branch {0} has no revision {1}.").format(
1316
from_location, revision)
1317
raise errors.BzrCommandError(msg)
1318
_merge_tags_if_possible(br_from, branch)
1319
# If the source branch is stacked, the new branch may
1320
# be stacked whether we asked for that explicitly or not.
1321
# We therefore need a try/except here and not just 'if stacked:'
1323
note(gettext('Created new stacked branch referring to %s.') %
1324
branch.get_stacked_on_url())
1325
except (errors.NotStacked, errors.UnstackableBranchFormat,
1326
errors.UnstackableRepositoryFormat), e:
1327
note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
1329
# Bind to the parent
1330
parent_branch = Branch.open(from_location)
1331
branch.bind(parent_branch)
1332
note(gettext('New branch bound to %s') % from_location)
1334
# Switch to the new branch
1335
wt, _ = WorkingTree.open_containing('.')
1336
_mod_switch.switch(wt.bzrdir, branch)
1337
note(gettext('Switched to branch: %s'),
1338
urlutils.unescape_for_display(branch.base, 'utf-8'))
1341
class cmd_branches(Command):
1342
__doc__ = """List the branches available at the current location.
1344
This command will print the names of all the branches at the current location.
1347
takes_args = ['location?']
1349
def run(self, location="."):
1350
dir = bzrdir.BzrDir.open_containing(location)[0]
1351
for branch in dir.list_branches():
1352
if branch.name is None:
1353
self.outf.write(gettext(" (default)\n"))
1355
self.outf.write(" %s\n" % branch.name.encode(self.outf.encoding))
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'))
1358
1276
class cmd_checkout(Command):
1359
__doc__ = """Create a new checkout of an existing branch.
1277
"""Create a new checkout of an existing branch.
1361
1279
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1362
1280
the branch found in '.'. This is useful if you have removed the working tree
1469
1388
If you want to discard your local changes, you can just do a
1470
1389
'bzr revert' instead of 'bzr commit' after the update.
1472
If you want to restore a file that has been removed locally, use
1473
'bzr revert' instead of 'bzr update'.
1475
If the tree's branch is bound to a master branch, it will also update
1476
the branch from the master.
1479
1392
_see_also = ['pull', 'working-trees', 'status-flags']
1480
1393
takes_args = ['dir?']
1481
takes_options = ['revision',
1483
help="Show base revision text in conflicts."),
1485
1394
aliases = ['up']
1487
def run(self, dir='.', revision=None, show_base=None):
1488
if revision is not None and len(revision) != 1:
1489
raise errors.BzrCommandError(gettext(
1490
"bzr update --revision takes exactly one revision"))
1396
def run(self, dir='.'):
1491
1397
tree = WorkingTree.open_containing(dir)[0]
1492
branch = tree.branch
1493
1398
possible_transports = []
1494
master = branch.get_master_branch(
1399
master = tree.branch.get_master_branch(
1495
1400
possible_transports=possible_transports)
1496
1401
if master is not None:
1497
1403
branch_location = master.base
1405
tree.lock_tree_write()
1500
1406
branch_location = tree.branch.base
1501
tree.lock_tree_write()
1502
self.add_cleanup(tree.unlock)
1503
1407
# get rid of the final '/' and be ready for display
1504
branch_location = urlutils.unescape_for_display(
1505
branch_location.rstrip('/'),
1507
existing_pending_merges = tree.get_parent_ids()[1:]
1511
# may need to fetch data into a heavyweight checkout
1512
# XXX: this may take some time, maybe we should display a
1514
old_tip = branch.update(possible_transports)
1515
if revision is not None:
1516
revision_id = revision[0].as_revision_id(branch)
1518
revision_id = branch.last_revision()
1519
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1520
revno = branch.revision_id_to_dotted_revno(revision_id)
1521
note(gettext("Tree is up to date at revision {0} of branch {1}"
1522
).format('.'.join(map(str, revno)), branch_location))
1524
view_info = _get_view_info_for_change_reporter(tree)
1525
change_reporter = delta._ChangeReporter(
1526
unversioned_filter=tree.is_ignored,
1527
view_info=view_info)
1408
branch_location = urlutils.unescape_for_display(branch_location[:-1],
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)
1529
1423
conflicts = tree.update(
1531
possible_transports=possible_transports,
1532
revision=revision_id,
1534
show_base=show_base)
1535
except errors.NoSuchRevision, e:
1536
raise errors.BzrCommandError(gettext(
1537
"branch has no revision %s\n"
1538
"bzr update --revision only works"
1539
" for a revision in the branch history")
1541
revno = tree.branch.revision_id_to_dotted_revno(
1542
_mod_revision.ensure_null(tree.last_revision()))
1543
note(gettext('Updated to revision {0} of branch {1}').format(
1544
'.'.join(map(str, revno)), branch_location))
1545
parent_ids = tree.get_parent_ids()
1546
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1547
note(gettext('Your local commits will now show as pending merges with '
1548
"'bzr status', and can be committed with 'bzr commit'."))
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'.")
1555
1441
class cmd_info(Command):
1556
__doc__ = """Show information about a working tree, branch or repository.
1442
"""Show information about a working tree, branch or repository.
1558
1444
This command will show all known locations and formats associated to the
1559
1445
tree, branch or repository.
1611
1496
RegistryOption.from_kwargs('file-deletion-strategy',
1612
1497
'The file deletion mode to be used.',
1613
1498
title='Deletion Strategy', value_switches=True, enum_switch=False,
1614
safe='Backup changed files (default).',
1499
safe='Only delete files if they can be'
1500
' safely recovered (default).',
1615
1501
keep='Delete from bzr but leave the working copy.',
1616
no_backup='Don\'t backup changed files.',
1617
1502
force='Delete all the specified files, even if they can not be '
1618
'recovered and even if they are non-empty directories. '
1619
'(deprecated, use no-backup)')]
1503
'recovered and even if they are non-empty directories.')]
1620
1504
aliases = ['rm', 'del']
1621
1505
encoding_type = 'replace'
1623
1507
def run(self, file_list, verbose=False, new=False,
1624
1508
file_deletion_strategy='safe'):
1625
if file_deletion_strategy == 'force':
1626
note(gettext("(The --force option is deprecated, rather use --no-backup "
1628
file_deletion_strategy = 'no-backup'
1630
tree, file_list = WorkingTree.open_containing_paths(file_list)
1509
tree, file_list = tree_files(file_list)
1632
1511
if file_list is not None:
1633
1512
file_list = [f for f in file_list]
1635
self.add_cleanup(tree.lock_write().unlock)
1636
# Heuristics should probably all move into tree.remove_smart or
1639
added = tree.changes_from(tree.basis_tree(),
1640
specific_files=file_list).added
1641
file_list = sorted([f[0] for f in added], reverse=True)
1642
if len(file_list) == 0:
1643
raise errors.BzrCommandError(gettext('No matching files.'))
1644
elif file_list is None:
1645
# missing files show up in iter_changes(basis) as
1646
# versioned-with-no-kind.
1648
for change in tree.iter_changes(tree.basis_tree()):
1649
# Find paths in the working tree that have no kind:
1650
if change[1][1] is not None and change[6][1] is None:
1651
missing.append(change[1][1])
1652
file_list = sorted(missing, reverse=True)
1653
file_deletion_strategy = 'keep'
1654
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1655
keep_files=file_deletion_strategy=='keep',
1656
force=(file_deletion_strategy=='no-backup'))
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')
1659
1541
class cmd_file_id(Command):
1660
__doc__ = """Print file_id of a particular file or directory.
1542
"""Print file_id of a particular file or directory.
1662
1544
The file_id is assigned when the file is first added and remains the
1663
1545
same through all revisions where the file exists, even when it is
2091
1932
elif ':' in prefix:
2092
1933
old_label, new_label = prefix.split(":")
2094
raise errors.BzrCommandError(gettext(
1935
raise errors.BzrCommandError(
2095
1936
'--prefix expects two values separated by a colon'
2096
' (eg "old/:new/")'))
1937
' (eg "old/:new/")')
2098
1939
if revision and len(revision) > 2:
2099
raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2100
' one or two revision specifiers'))
2102
if using is not None and format is not None:
2103
raise errors.BzrCommandError(gettext(
2104
'{0} and {1} are mutually exclusive').format(
2105
'--using', '--format'))
1940
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1941
' one or two revision specifiers')
2107
1943
(old_tree, new_tree,
2108
1944
old_branch, new_branch,
2109
specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2110
file_list, revision, old, new, self.add_cleanup, apply_view=True)
2111
# GNU diff on Windows uses ANSI encoding for filenames
2112
path_encoding = osutils.get_diff_header_encoding()
1945
specific_files, extra_trees) = get_trees_and_branches_to_diff(
1946
file_list, revision, old, new, apply_view=True)
2113
1947
return show_diff_trees(old_tree, new_tree, sys.stdout,
2114
1948
specific_files=specific_files,
2115
1949
external_diff_options=diff_options,
2116
1950
old_label=old_label, new_label=new_label,
2117
extra_trees=extra_trees,
2118
path_encoding=path_encoding,
1951
extra_trees=extra_trees, using=using)
2123
1954
class cmd_deleted(Command):
2124
__doc__ = """List files deleted in the working tree.
1955
"""List files deleted in the working tree.
2126
1957
# TODO: Show files deleted since a previous revision, or
2127
1958
# between two revisions.
2130
1961
# level of effort but possibly much less IO. (Or possibly not,
2131
1962
# if the directories are very large...)
2132
1963
_see_also = ['status', 'ls']
2133
takes_options = ['directory', 'show-ids']
1964
takes_options = ['show-ids']
2135
1966
@display_command
2136
def run(self, show_ids=False, directory=u'.'):
2137
tree = WorkingTree.open_containing(directory)[0]
2138
self.add_cleanup(tree.lock_read().unlock)
2139
old = tree.basis_tree()
2140
self.add_cleanup(old.lock_read().unlock)
2141
for path, ie in old.inventory.iter_entries():
2142
if not tree.has_id(ie.file_id):
2143
self.outf.write(path)
2145
self.outf.write(' ')
2146
self.outf.write(ie.file_id)
2147
self.outf.write('\n')
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')
2150
1987
class cmd_modified(Command):
2151
__doc__ = """List files modified in working tree.
1988
"""List files modified in working tree.
2155
1992
_see_also = ['status', 'ls']
2156
takes_options = ['directory', 'null']
1995
help='Write an ascii NUL (\\0) separator '
1996
'between files rather than a newline.')
2158
1999
@display_command
2159
def run(self, null=False, directory=u'.'):
2160
tree = WorkingTree.open_containing(directory)[0]
2161
self.add_cleanup(tree.lock_read().unlock)
2000
def run(self, null=False):
2001
tree = WorkingTree.open_containing(u'.')[0]
2162
2002
td = tree.changes_from(tree.basis_tree())
2164
2003
for path, id, kind, text_modified, meta_modified in td.modified:
2166
2005
self.outf.write(path + '\0')
2171
2010
class cmd_added(Command):
2172
__doc__ = """List files added in working tree.
2011
"""List files added in working tree.
2176
2015
_see_also = ['status', 'ls']
2177
takes_options = ['directory', 'null']
2018
help='Write an ascii NUL (\\0) separator '
2019
'between files rather than a newline.')
2179
2022
@display_command
2180
def run(self, null=False, directory=u'.'):
2181
wt = WorkingTree.open_containing(directory)[0]
2182
self.add_cleanup(wt.lock_read().unlock)
2183
basis = wt.basis_tree()
2184
self.add_cleanup(basis.lock_read().unlock)
2185
basis_inv = basis.inventory
2188
if basis_inv.has_id(file_id):
2190
if inv.is_root(file_id) and len(basis_inv) == 0:
2192
path = inv.id2path(file_id)
2193
if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2196
self.outf.write(path + '\0')
2198
self.outf.write(osutils.quotefn(path) + '\n')
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')
2201
2050
class cmd_root(Command):
2202
__doc__ = """Show the tree root directory.
2051
"""Show the tree root directory.
2204
2053
The root is the nearest enclosing directory with a .bzr control
2472
2285
show_diff=False,
2473
include_merged=None,
2475
exclude_common_ancestry=False,
2479
match_committer=None,
2483
include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2286
include_merges=False):
2485
2287
from bzrlib.log import (
2487
2289
make_log_request_dict,
2488
2290
_get_info_for_log_files,
2490
2292
direction = (forward and 'forward') or 'reverse'
2491
if symbol_versioning.deprecated_passed(include_merges):
2492
ui.ui_factory.show_user_warning(
2493
'deprecated_command_option',
2494
deprecated_name='--include-merges',
2495
recommended_name='--include-merged',
2496
deprecated_in_version='2.5',
2497
command=self.invoked_as)
2498
if include_merged is None:
2499
include_merged = include_merges
2501
raise errors.BzrCommandError(gettext(
2502
'{0} and {1} are mutually exclusive').format(
2503
'--include-merges', '--include-merged'))
2504
if include_merged is None:
2505
include_merged = False
2506
if (exclude_common_ancestry
2507
and (revision is None or len(revision) != 2)):
2508
raise errors.BzrCommandError(gettext(
2509
'--exclude-common-ancestry requires -r with two revisions'))
2511
2294
if levels is None:
2514
raise errors.BzrCommandError(gettext(
2515
'{0} and {1} are mutually exclusive').format(
2516
'--levels', '--include-merged'))
2297
raise errors.BzrCommandError(
2298
'--levels and --include-merges are mutually exclusive')
2518
2300
if change is not None:
2519
2301
if len(change) > 1:
2520
2302
raise errors.RangeInChangeOption()
2521
2303
if revision is not None:
2522
raise errors.BzrCommandError(gettext(
2523
'{0} and {1} are mutually exclusive').format(
2524
'--revision', '--change'))
2304
raise errors.BzrCommandError(
2305
'--revision and --change are mutually exclusive')
2526
2307
revision = change
2529
2310
filter_by_dir = False
2531
# find the file ids to log and check for directory filtering
2532
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2533
revision, file_list, self.add_cleanup)
2534
for relpath, file_id, kind in file_info_list:
2536
raise errors.BzrCommandError(gettext(
2537
"Path unknown at end or start of revision range: %s") %
2539
# If the relpath is the top of the tree, we log everything
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()
2544
file_ids.append(file_id)
2545
filter_by_dir = filter_by_dir or (
2546
kind in ['directory', 'tree-reference'])
2549
# FIXME ? log the current subdir only RBC 20060203
2550
if revision is not None \
2551
and len(revision) > 0 and revision[0].get_branch():
2552
location = revision[0].get_branch()
2555
dir, relpath = bzrdir.BzrDir.open_containing(location)
2556
b = dir.open_branch()
2557
self.add_cleanup(b.lock_read().unlock)
2558
rev1, rev2 = _get_revision_range(revision, b, self.name())
2560
if b.get_config().validate_signatures_in_log():
2564
if not gpg.GPGStrategy.verify_signatures_available():
2565
raise errors.GpgmeNotInstalled(None)
2567
# Decide on the type of delta & diff filtering to use
2568
# TODO: add an --all-files option to make this configurable & consistent
2576
diff_type = 'partial'
2580
# Build the log formatter
2581
if log_format is None:
2582
log_format = log.log_formatter_registry.get_default(b)
2583
# Make a non-encoding output to include the diffs - bug 328007
2584
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2585
lf = log_format(show_ids=show_ids, to_file=self.outf,
2586
to_exact_file=unencoded_output,
2587
show_timezone=timezone,
2588
delta_format=get_verbosity_level(),
2590
show_advice=levels is None,
2591
author_list_handler=authors)
2593
# Choose the algorithm for doing the logging. It's annoying
2594
# having multiple code paths like this but necessary until
2595
# the underlying repository format is faster at generating
2596
# deltas or can provide everything we need from the indices.
2597
# The default algorithm - match-using-deltas - works for
2598
# multiple files and directories and is faster for small
2599
# amounts of history (200 revisions say). However, it's too
2600
# slow for logging a single file in a repository with deep
2601
# history, i.e. > 10K revisions. In the spirit of "do no
2602
# evil when adding features", we continue to use the
2603
# original algorithm - per-file-graph - for the "single
2604
# file that isn't a directory without showing a delta" case.
2605
partial_history = revision and b.repository._format.supports_chks
2606
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2607
or delta_type or partial_history)
2611
match_dict[''] = match
2613
match_dict['message'] = match_message
2615
match_dict['committer'] = match_committer
2617
match_dict['author'] = match_author
2619
match_dict['bugs'] = match_bugs
2621
# Build the LogRequest and execute it
2622
if len(file_ids) == 0:
2624
rqst = make_log_request_dict(
2625
direction=direction, specific_fileids=file_ids,
2626
start_revision=rev1, end_revision=rev2, limit=limit,
2627
message_search=message, delta_type=delta_type,
2628
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2629
exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2630
signature=signatures, omit_merges=omit_merges,
2632
Logger(b, rqst).show(lf)
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)
2635
2398
def _get_revision_range(revisionspec_list, branch, command_name):
2724
2486
help='Recurse into subdirectories.'),
2725
2487
Option('from-root',
2726
2488
help='Print paths relative to the root of the branch.'),
2727
Option('unknown', short_name='u',
2728
help='Print unknown files.'),
2489
Option('unknown', help='Print unknown files.'),
2729
2490
Option('versioned', help='Print versioned files.',
2730
2491
short_name='V'),
2731
Option('ignored', short_name='i',
2732
help='Print ignored files.'),
2733
Option('kind', short_name='k',
2492
Option('ignored', help='Print ignored files.'),
2494
help='Write an ascii NUL (\\0) separator '
2495
'between files rather than a newline.'),
2734
2497
help='List entries of a particular kind: file, directory, symlink.',
2740
2501
@display_command
2741
2502
def run(self, revision=None, verbose=False,
2742
2503
recursive=False, from_root=False,
2743
2504
unknown=False, versioned=False, ignored=False,
2744
null=False, kind=None, show_ids=False, path=None, directory=None):
2505
null=False, kind=None, show_ids=False, path=None):
2746
2507
if kind and kind not in ('file', 'directory', 'symlink'):
2747
raise errors.BzrCommandError(gettext('invalid kind specified'))
2508
raise errors.BzrCommandError('invalid kind specified')
2749
2510
if verbose and null:
2750
raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
2511
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2751
2512
all = not (unknown or versioned or ignored)
2753
2514
selection = {'I':ignored, '?':unknown, 'V':versioned}
2780
2541
apply_view = True
2781
2542
view_str = views.view_display_str(view_files)
2782
note(gettext("Ignoring files outside view. View is %s") % view_str)
2784
self.add_cleanup(tree.lock_read().unlock)
2785
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2786
from_dir=relpath, recursive=recursive):
2787
# Apply additional masking
2788
if not all and not selection[fc]:
2790
if kind is not None and fkind != kind:
2795
fullpath = osutils.pathjoin(relpath, fp)
2798
views.check_path_in_view(tree, fullpath)
2799
except errors.FileOutsideView:
2804
fp = osutils.pathjoin(prefix, fp)
2805
kindch = entry.kind_character()
2806
outstring = fp + kindch
2807
ui.ui_factory.clear_term()
2809
outstring = '%-8s %s' % (fc, outstring)
2810
if show_ids and fid is not None:
2811
outstring = "%-50s %s" % (outstring, fid)
2812
self.outf.write(outstring + '\n')
2814
self.outf.write(fp + '\0')
2817
self.outf.write(fid)
2818
self.outf.write('\0')
2826
self.outf.write('%-50s %s\n' % (outstring, my_id))
2543
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:
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)
2828
2574
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')
2831
2595
class cmd_unknowns(Command):
2832
__doc__ = """List unknown files.
2596
"""List unknown files.
2836
2600
_see_also = ['ls']
2837
takes_options = ['directory']
2839
2602
@display_command
2840
def run(self, directory=u'.'):
2841
for f in WorkingTree.open_containing(directory)[0].unknowns():
2604
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2842
2605
self.outf.write(osutils.quotefn(f) + '\n')
2845
2608
class cmd_ignore(Command):
2846
__doc__ = """Ignore specified files or patterns.
2609
"""Ignore specified files or patterns.
2848
2611
See ``bzr help patterns`` for details on the syntax of patterns.
2907
2644
Ignore everything but the "debian" toplevel directory::
2909
2646
bzr ignore "RE:(?!debian/).*"
2911
Ignore everything except the "local" toplevel directory,
2912
but always ignore autosave files ending in ~, even under local/::
2915
bzr ignore "!./local"
2919
2649
_see_also = ['status', 'ignored', 'patterns']
2920
2650
takes_args = ['name_pattern*']
2921
takes_options = ['directory',
2922
Option('default-rules',
2923
help='Display the default ignore rules that bzr uses.')
2652
Option('old-default-rules',
2653
help='Write out the ignore rules bzr < 0.9 always used.')
2926
def run(self, name_pattern_list=None, default_rules=None,
2656
def run(self, name_pattern_list=None, old_default_rules=None):
2928
2657
from bzrlib import ignores
2929
if default_rules is not None:
2930
# dump the default rules and exit
2931
for pattern in ignores.USER_DEFAULTS:
2932
self.outf.write("%s\n" % pattern)
2658
if old_default_rules is not None:
2659
# dump the rules and exit
2660
for pattern in ignores.OLD_DEFAULTS:
2934
2663
if not name_pattern_list:
2935
raise errors.BzrCommandError(gettext("ignore requires at least one "
2936
"NAME_PATTERN or --default-rules."))
2664
raise errors.BzrCommandError("ignore requires at least one "
2665
"NAME_PATTERN or --old-default-rules")
2937
2666
name_pattern_list = [globbing.normalize_pattern(p)
2938
2667
for p in name_pattern_list]
2940
bad_patterns_count = 0
2941
for p in name_pattern_list:
2942
if not globbing.Globster.is_pattern_valid(p):
2943
bad_patterns_count += 1
2944
bad_patterns += ('\n %s' % p)
2946
msg = (ngettext('Invalid ignore pattern found. %s',
2947
'Invalid ignore patterns found. %s',
2948
bad_patterns_count) % bad_patterns)
2949
ui.ui_factory.show_error(msg)
2950
raise errors.InvalidPattern('')
2951
2668
for name_pattern in name_pattern_list:
2952
2669
if (name_pattern[0] == '/' or
2953
2670
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2954
raise errors.BzrCommandError(gettext(
2955
"NAME_PATTERN should not be an absolute path"))
2956
tree, relpath = WorkingTree.open_containing(directory)
2671
raise errors.BzrCommandError(
2672
"NAME_PATTERN should not be an absolute path")
2673
tree, relpath = WorkingTree.open_containing(u'.')
2957
2674
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2958
2675
ignored = globbing.Globster(name_pattern_list)
2960
self.add_cleanup(tree.lock_read().unlock)
2961
2678
for entry in tree.list_files():
2963
2680
if id is not None:
2964
2681
filename = entry[0]
2965
2682
if ignored.match(filename):
2966
matches.append(filename)
2683
matches.append(filename.encode('utf-8'))
2967
2685
if len(matches) > 0:
2968
self.outf.write(gettext("Warning: the following files are version "
2969
"controlled and match your ignore pattern:\n%s"
2970
"\nThese files will continue to be version controlled"
2971
" unless you 'bzr remove' them.\n") % ("\n".join(matches),))
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),)
2974
2692
class cmd_ignored(Command):
2975
__doc__ = """List ignored files and the patterns that matched them.
2693
"""List ignored files and the patterns that matched them.
2977
2695
List all the ignored files and the ignore pattern that caused the file to
2985
2703
encoding_type = 'replace'
2986
2704
_see_also = ['ignore', 'ls']
2987
takes_options = ['directory']
2989
2706
@display_command
2990
def run(self, directory=u'.'):
2991
tree = WorkingTree.open_containing(directory)[0]
2992
self.add_cleanup(tree.lock_read().unlock)
2993
for path, file_class, kind, file_id, entry in tree.list_files():
2994
if file_class != 'I':
2996
## XXX: Slightly inefficient since this was already calculated
2997
pat = tree.is_ignored(path)
2998
self.outf.write('%-50s %s\n' % (path, pat))
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))
3001
2721
class cmd_lookup_revision(Command):
3002
__doc__ = """Lookup the revision-id from a revision-number
2722
"""Lookup the revision-id from a revision-number
3005
2725
bzr lookup-revision 33
3008
2728
takes_args = ['revno']
3009
takes_options = ['directory']
3011
2730
@display_command
3012
def run(self, revno, directory=u'.'):
2731
def run(self, revno):
3014
2733
revno = int(revno)
3015
2734
except ValueError:
3016
raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3018
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3019
self.outf.write("%s\n" % revid)
2735
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2737
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3022
2740
class cmd_export(Command):
3023
__doc__ = """Export current or past revision to a destination directory or archive.
2741
"""Export current or past revision to a destination directory or archive.
3025
2743
If no revision is specified this exports the last committed revision.
3105
2818
@display_command
3106
2819
def run(self, filename, revision=None, name_from_revision=False,
3107
filters=False, directory=None):
3108
2821
if revision is not None and len(revision) != 1:
3109
raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3110
" one revision specifier"))
2822
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2823
" one revision specifier")
3111
2824
tree, branch, relpath = \
3112
_open_directory_or_containing_tree_or_branch(filename, directory)
3113
self.add_cleanup(branch.lock_read().unlock)
3114
return self._run(tree, branch, relpath, filename, revision,
3115
name_from_revision, filters)
2825
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2828
return self._run(tree, branch, relpath, filename, revision,
2829
name_from_revision, filters)
3117
2833
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
3119
2835
if tree is None:
3120
2836
tree = b.basis_tree()
3121
2837
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3122
self.add_cleanup(rev_tree.lock_read().unlock)
3124
2839
old_file_id = rev_tree.path2id(relpath)
3126
# TODO: Split out this code to something that generically finds the
3127
# best id for a path across one or more trees; it's like
3128
# find_ids_across_trees but restricted to find just one. -- mbp
3130
2841
if name_from_revision:
3131
2842
# Try in revision if requested
3132
2843
if old_file_id is None:
3133
raise errors.BzrCommandError(gettext(
3134
"{0!r} is not present in revision {1}").format(
2844
raise errors.BzrCommandError(
2845
"%r is not present in revision %s" % (
3135
2846
filename, rev_tree.get_revision_id()))
3137
actual_file_id = old_file_id
2848
content = rev_tree.get_file_text(old_file_id)
3139
2850
cur_file_id = tree.path2id(relpath)
3140
if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3141
actual_file_id = cur_file_id
3142
elif old_file_id is not None:
3143
actual_file_id = old_file_id
3145
raise errors.BzrCommandError(gettext(
3146
"{0!r} is not present in revision {1}").format(
2852
if cur_file_id is not None:
2853
# Then try with the actual file id
2855
content = rev_tree.get_file_text(cur_file_id)
2857
except errors.NoSuchId:
2858
# The actual file id didn't exist at that time
2860
if not found and old_file_id is not None:
2861
# Finally try with the old file id
2862
content = rev_tree.get_file_text(old_file_id)
2865
# Can't be found anywhere
2866
raise errors.BzrCommandError(
2867
"%r is not present in revision %s" % (
3147
2868
filename, rev_tree.get_revision_id()))
3149
from bzrlib.filter_tree import ContentFilterTree
3150
filter_tree = ContentFilterTree(rev_tree,
3151
rev_tree._content_filter_stack)
3152
content = filter_tree.get_file_text(actual_file_id)
2870
from bzrlib.filters import (
2871
ContentFilterContext,
2872
filtered_output_bytes,
2874
filters = rev_tree._content_filter_stack(relpath)
2875
chunks = content.splitlines(True)
2876
content = filtered_output_bytes(chunks, filters,
2877
ContentFilterContext(relpath, rev_tree))
2878
self.outf.writelines(content)
3154
content = rev_tree.get_file_text(actual_file_id)
3156
self.outf.write(content)
2880
self.outf.write(content)
3159
2883
class cmd_local_time_offset(Command):
3160
__doc__ = """Show the offset in seconds from GMT to local time."""
2884
"""Show the offset in seconds from GMT to local time."""
3162
2886
@display_command
3164
self.outf.write("%s\n" % osutils.local_time_offset())
2888
print osutils.local_time_offset()
3168
2892
class cmd_commit(Command):
3169
__doc__ = """Commit changes into a new revision.
2893
"""Commit changes into a new revision.
3171
2895
An explanatory message needs to be given for each commit. This is
3172
2896
often done by using the --message option (getting the message from the
3255
3004
"the master branch until a normal commit "
3256
3005
"is performed."
3258
Option('show-diff', short_name='p',
3259
3008
help='When no message is supplied, show the diff along'
3260
3009
' with the status summary in the message editor.'),
3262
help='When committing to a foreign version control '
3263
'system do not push data that can not be natively '
3266
3011
aliases = ['ci', 'checkin']
3268
3013
def _iter_bug_fix_urls(self, fixes, branch):
3269
default_bugtracker = None
3270
3014
# Configure the properties for bug fixing attributes.
3271
3015
for fixed_bug in fixes:
3272
3016
tokens = fixed_bug.split(':')
3273
if len(tokens) == 1:
3274
if default_bugtracker is None:
3275
branch_config = branch.get_config()
3276
default_bugtracker = branch_config.get_user_option(
3278
if default_bugtracker is None:
3279
raise errors.BzrCommandError(gettext(
3280
"No tracker specified for bug %s. Use the form "
3281
"'tracker:id' or specify a default bug tracker "
3282
"using the `bugtracker` option.\nSee "
3283
"\"bzr help bugs\" for more information on this "
3284
"feature. Commit refused.") % fixed_bug)
3285
tag = default_bugtracker
3287
elif len(tokens) != 2:
3288
raise errors.BzrCommandError(gettext(
3017
if len(tokens) != 2:
3018
raise errors.BzrCommandError(
3289
3019
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3290
3020
"See \"bzr help bugs\" for more information on this "
3291
"feature.\nCommit refused.") % fixed_bug)
3293
tag, bug_id = tokens
3021
"feature.\nCommit refused." % fixed_bug)
3022
tag, bug_id = tokens
3295
3024
yield bugtracker.get_bug_url(tag, branch, bug_id)
3296
3025
except errors.UnknownBugTrackerAbbreviation:
3297
raise errors.BzrCommandError(gettext(
3298
'Unrecognized bug %s. Commit refused.') % fixed_bug)
3026
raise errors.BzrCommandError(
3027
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3299
3028
except errors.MalformedBugIdentifier, e:
3300
raise errors.BzrCommandError(gettext(
3301
"%s\nCommit refused.") % (str(e),))
3029
raise errors.BzrCommandError(
3030
"%s\nCommit refused." % (str(e),))
3303
3032
def run(self, message=None, file=None, verbose=False, selected_list=None,
3304
3033
unchanged=False, strict=False, local=False, fixes=None,
3305
author=None, show_diff=False, exclude=None, commit_time=None,
3034
author=None, show_diff=False, exclude=None, commit_time=None):
3307
3035
from bzrlib.errors import (
3308
3036
PointlessCommit,
3309
3037
ConflictsInTree,
3357
3090
'(use --file "%(f)s" to take commit message from that file)'
3358
3091
% { 'f': message })
3359
3092
ui.ui_factory.show_warning(warning_msg)
3361
message = message.replace('\r\n', '\n')
3362
message = message.replace('\r', '\n')
3364
raise errors.BzrCommandError(gettext(
3365
"please specify either --message or --file"))
3367
3094
def get_message(commit_obj):
3368
3095
"""Callback to get commit message"""
3372
my_message = f.read().decode(osutils.get_user_encoding())
3375
elif message is not None:
3376
my_message = message
3378
# No message supplied: make one up.
3379
# text is the status of the tree
3380
text = make_commit_message_template_encoded(tree,
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,
3381
3102
selected_list, diff=show_diff,
3382
3103
output_encoding=osutils.get_user_encoding())
3383
# start_message is the template generated from hooks
3384
# XXX: Warning - looks like hooks return unicode,
3385
# make_commit_message_template_encoded returns user encoding.
3386
# We probably want to be using edit_commit_message instead to
3388
my_message = set_commit_message(commit_obj)
3389
if my_message is None:
3390
start_message = generate_commit_message_template(commit_obj)
3391
my_message = edit_commit_message_encoded(text,
3392
start_message=start_message)
3393
if my_message is None:
3394
raise errors.BzrCommandError(gettext("please specify a commit"
3395
" message with either --message or --file"))
3396
if my_message == "":
3397
raise errors.BzrCommandError(gettext("Empty commit message specified."
3398
" Please specify a commit message with either"
3399
" --message or --file or leave a blank message"
3400
" with --message \"\"."))
3104
start_message = generate_commit_message_template(commit_obj)
3105
my_message = edit_commit_message_encoded(t,
3106
start_message=start_message)
3107
if my_message is None:
3108
raise errors.BzrCommandError("please specify a commit"
3109
" 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
if my_message == "":
3117
raise errors.BzrCommandError("empty commit message specified")
3401
3118
return my_message
3403
3120
# The API permits a commit with a filter of [] to mean 'select nothing'
3411
3128
reporter=None, verbose=verbose, revprops=properties,
3412
3129
authors=author, timestamp=commit_stamp,
3413
3130
timezone=offset,
3414
exclude=tree.safe_relpath_files(exclude),
3131
exclude=safe_relpath_files(tree, exclude))
3416
3132
except PointlessCommit:
3417
raise errors.BzrCommandError(gettext("No changes to commit."
3418
" Please 'bzr add' the files you want to commit, or use"
3419
" --unchanged to force an empty commit."))
3133
# FIXME: This should really happen before the file is read in;
3134
# perhaps prepare the commit; get the message; then actually commit
3135
raise errors.BzrCommandError("No changes to commit."
3136
" Use --unchanged to commit anyhow.")
3420
3137
except ConflictsInTree:
3421
raise errors.BzrCommandError(gettext('Conflicts detected in working '
3138
raise errors.BzrCommandError('Conflicts detected in working '
3422
3139
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
3424
3141
except StrictCommitFailed:
3425
raise errors.BzrCommandError(gettext("Commit refused because there are"
3426
" unknown files in the working tree."))
3142
raise errors.BzrCommandError("Commit refused because there are"
3143
" unknown files in the working tree.")
3427
3144
except errors.BoundBranchOutOfDate, e:
3428
e.extra_help = (gettext("\n"
3429
'To commit to master branch, run update and then commit.\n'
3430
'You can also pass --local to commit to continue working '
3145
raise errors.BzrCommandError(str(e) + "\n"
3146
'To commit to master branch, run update and then commit.\n'
3147
'You can also pass --local to commit to continue working '
3435
3151
class cmd_check(Command):
3436
__doc__ = """Validate working tree structure, branch consistency and repository history.
3152
"""Validate working tree structure, branch consistency and repository history.
3438
3154
This command checks various invariants about branch and repository storage
3439
3155
to detect data corruption or bzr bugs.
3505
3221
class cmd_upgrade(Command):
3506
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3508
When the default format has changed after a major new release of
3509
Bazaar, you may be informed during certain operations that you
3510
should upgrade. Upgrading to a newer format may improve performance
3511
or make new features available. It may however limit interoperability
3512
with older repositories or with older versions of Bazaar.
3514
If you wish to upgrade to a particular format rather than the
3515
current default, that can be specified using the --format option.
3516
As a consequence, you can use the upgrade command this way to
3517
"downgrade" to an earlier format, though some conversions are
3518
a one way process (e.g. changing from the 1.x default to the
3519
2.x default) so downgrading is not always possible.
3521
A backup.bzr.~#~ directory is created at the start of the conversion
3522
process (where # is a number). By default, this is left there on
3523
completion. If the conversion fails, delete the new .bzr directory
3524
and rename this one back in its place. Use the --clean option to ask
3525
for the backup.bzr directory to be removed on successful conversion.
3526
Alternatively, you can delete it by hand if everything looks good
3529
If the location given is a shared repository, dependent branches
3530
are also converted provided the repository converts successfully.
3531
If the conversion of a branch fails, remaining branches are still
3534
For more information on upgrades, see the Bazaar Upgrade Guide,
3535
http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
3222
"""Upgrade branch storage to current format.
3224
The check command or bzr developers may sometimes advise you to run
3225
this command. When the default format has changed you may also be warned
3226
during other operations to upgrade.
3538
_see_also = ['check', 'reconcile', 'formats']
3229
_see_also = ['check']
3539
3230
takes_args = ['url?']
3540
3231
takes_options = [
3541
RegistryOption('format',
3542
help='Upgrade to a specific format. See "bzr help'
3543
' formats" for details.',
3544
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3545
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3546
value_switches=True, title='Branch format'),
3548
help='Remove the backup.bzr directory if successful.'),
3550
help="Show what would be done, but don't actually do anything."),
3232
RegistryOption('format',
3233
help='Upgrade to a specific format. See "bzr help'
3234
' formats" for details.',
3235
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3236
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3237
value_switches=True, title='Branch format'),
3553
def run(self, url='.', format=None, clean=False, dry_run=False):
3240
def run(self, url='.', format=None):
3554
3241
from bzrlib.upgrade import upgrade
3555
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3557
if len(exceptions) == 1:
3558
# Compatibility with historical behavior
3242
upgrade(url, format)
3564
3245
class cmd_whoami(Command):
3565
__doc__ = """Show or set bzr user id.
3246
"""Show or set bzr user id.
3568
3249
Show the email of the current user::
3584
3264
encoding_type = 'replace'
3586
3266
@display_command
3587
def run(self, email=False, branch=False, name=None, directory=None):
3267
def run(self, email=False, branch=False, name=None):
3588
3268
if name is None:
3589
if directory is None:
3590
# use branch if we're inside one; otherwise global config
3592
c = Branch.open_containing(u'.')[0].get_config()
3593
except errors.NotBranchError:
3594
c = _mod_config.GlobalConfig()
3596
c = Branch.open(directory).get_config()
3269
# use branch if we're inside one; otherwise global config
3271
c = Branch.open_containing('.')[0].get_config()
3272
except errors.NotBranchError:
3273
c = config.GlobalConfig()
3598
3275
self.outf.write(c.user_email() + '\n')
3600
3277
self.outf.write(c.username() + '\n')
3604
raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3607
3280
# display a warning if an email address isn't included in the given name.
3609
_mod_config.extract_email_address(name)
3282
config.extract_email_address(name)
3610
3283
except errors.NoEmailInUsername, e:
3611
3284
warning('"%s" does not seem to contain an email address. '
3612
3285
'This is allowed, but not recommended.', name)
3614
3287
# use global config unless --branch given
3616
if directory is None:
3617
c = Branch.open_containing(u'.')[0].get_config()
3619
c = Branch.open(directory).get_config()
3289
c = Branch.open_containing('.')[0].get_config()
3621
c = _mod_config.GlobalConfig()
3291
c = config.GlobalConfig()
3622
3292
c.set_user_option('email', name)
3625
3295
class cmd_nick(Command):
3626
__doc__ = """Print or set the branch nickname.
3296
"""Print or set the branch nickname.
3628
3298
If unset, the tree root directory name is used as the nickname.
3629
3299
To print the current nickname, execute with no argument.
3861
3532
from bzrlib.tests import SubUnitBzrRunner
3862
3533
except ImportError:
3863
raise errors.BzrCommandError(gettext("subunit not available. subunit "
3864
"needs to be installed to use --subunit."))
3534
raise errors.BzrCommandError("subunit not available. subunit "
3535
"needs to be installed to use --subunit.")
3865
3536
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3866
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3867
# stdout, which would corrupt the subunit stream.
3868
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3869
# following code can be deleted when it's sufficiently deployed
3870
# -- vila/mgz 20100514
3871
if (sys.platform == "win32"
3872
and getattr(sys.stdout, 'fileno', None) is not None):
3874
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3876
3538
self.additional_selftest_args.setdefault(
3877
3539
'suite_decorators', []).append(parallel)
3879
raise errors.BzrCommandError(gettext(
3880
"--benchmark is no longer supported from bzr 2.2; "
3881
"use bzr-usertest instead"))
3882
test_suite_factory = None
3884
exclude_pattern = None
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)
3886
exclude_pattern = '(' + '|'.join(exclude) + ')'
3888
self._disable_fsync()
3889
selftest_kwargs = {"verbose": verbose,
3891
"stop_on_failure": one,
3892
"transport": transport,
3893
"test_suite_factory": test_suite_factory,
3894
"lsprof_timed": lsprof_timed,
3895
"lsprof_tests": lsprof_tests,
3896
"matching_tests_first": first,
3897
"list_only": list_only,
3898
"random_seed": randomize,
3899
"exclude_pattern": exclude_pattern,
3901
"load_list": load_list,
3902
"debug_flags": debugflag,
3903
"starting_with": starting_with
3905
selftest_kwargs.update(self.additional_selftest_args)
3907
# Make deprecation warnings visible, unless -Werror is set
3908
cleanup = symbol_versioning.activate_deprecation_warnings(
3547
test_suite_factory = None
3911
result = tests.selftest(**selftest_kwargs)
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)
3570
if benchfile is not None:
3914
3572
return int(not result)
3916
def _disable_fsync(self):
3917
"""Change the 'os' functionality to not synchronize."""
3918
self._orig_fsync = getattr(os, 'fsync', None)
3919
if self._orig_fsync is not None:
3920
os.fsync = lambda filedes: None
3921
self._orig_fdatasync = getattr(os, 'fdatasync', None)
3922
if self._orig_fdatasync is not None:
3923
os.fdatasync = lambda filedes: None
3926
3575
class cmd_version(Command):
3927
__doc__ = """Show version of bzr."""
3576
"""Show version of bzr."""
3929
3578
encoding_type = 'replace'
3930
3579
takes_options = [
3964
3613
branch1 = Branch.open_containing(branch)[0]
3965
3614
branch2 = Branch.open_containing(other)[0]
3966
self.add_cleanup(branch1.lock_read().unlock)
3967
self.add_cleanup(branch2.lock_read().unlock)
3968
last1 = ensure_null(branch1.last_revision())
3969
last2 = ensure_null(branch2.last_revision())
3971
graph = branch1.repository.get_graph(branch2.repository)
3972
base_rev_id = graph.find_unique_lca(last1, last2)
3974
self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
3619
last1 = ensure_null(branch1.last_revision())
3620
last2 = ensure_null(branch2.last_revision())
3622
graph = branch1.repository.get_graph(branch2.repository)
3623
base_rev_id = graph.find_unique_lca(last1, last2)
3625
print 'merge base is revision %s' % base_rev_id
3977
3632
class cmd_merge(Command):
3978
__doc__ = """Perform a three-way merge.
3633
"""Perform a three-way merge.
3980
3635
The source of the merge can be specified either in the form of a branch,
3981
3636
or in the form of a path to a file containing a merge directive generated
3982
3637
with bzr send. If neither is specified, the default is the upstream branch
3983
or the branch most recently merged using --remember. The source of the
3984
merge may also be specified in the form of a path to a file in another
3985
branch: in this case, only the modifications to that file are merged into
3986
the current working tree.
3988
When merging from a branch, by default bzr will try to merge in all new
3989
work from the other branch, automatically determining an appropriate base
3990
revision. If this fails, you may need to give an explicit base.
3992
To pick a different ending revision, pass "--revision OTHER". bzr will
3993
try to merge in all new work up to and including revision OTHER.
3995
If you specify two values, "--revision BASE..OTHER", only revisions BASE
3996
through OTHER, excluding BASE but including OTHER, will be merged. If this
3997
causes some revisions to be skipped, i.e. if the destination branch does
3998
not already contain revision BASE, such a merge is commonly referred to as
3999
a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4000
cherrypicks. The changes look like a normal commit, and the history of the
4001
changes from the other branch is not stored in the commit.
4003
Revision numbers are always relative to the source branch.
3638
or the branch most recently merged using --remember.
3640
When merging a branch, by default the tip will be merged. To pick a different
3641
revision, pass --revision. If you specify two values, the first will be used as
3642
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3643
available revisions, like this is commonly referred to as "cherrypicking".
3645
Revision numbers are always relative to the branch being merged.
3647
By default, bzr will try to merge in all new work from the other
3648
branch, automatically determining an appropriate base. If this
3649
fails, you may need to give an explicit base.
4005
3651
Merge will do its best to combine the changes in two branches, but there
4006
3652
are some kinds of problems only a human can fix. When it encounters those,
4010
3656
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
4012
If there is no default branch set, the first merge will set it (use
4013
--no-remember to avoid setting it). After that, you can omit the branch
4014
to use the default. To change the default, use --remember. The value will
4015
only be saved if the remote location can be accessed.
3658
If there is no default branch set, the first merge will set it. After
3659
that, you can omit the branch to use the default. To change the
3660
default, use --remember. The value will only be saved if the remote
3661
location can be accessed.
4017
3663
The results of the merge are placed into the destination working
4018
3664
directory, where they can be reviewed (with bzr diff), tested, and then
4019
3665
committed to record the result of the merge.
4021
3667
merge refuses to run if there are any uncommitted changes, unless
4022
--force is given. If --force is given, then the changes from the source
4023
will be merged with the current working tree, including any uncommitted
4024
changes in the tree. The --force option can also be used to create a
4025
merge revision which has more than two parents.
4027
If one would like to merge changes from the working tree of the other
4028
branch without merging any committed revisions, the --uncommitted option
4031
3670
To select only some changes to merge, use "merge -i", which will prompt
4032
3671
you to apply each diff hunk and file change, similar to "shelve".
4035
To merge all new revisions from bzr.dev::
3674
To merge the latest revision from bzr.dev::
4037
3676
bzr merge ../bzr.dev
4118
3749
view_info = _get_view_info_for_change_reporter(tree)
4119
3750
change_reporter = delta._ChangeReporter(
4120
3751
unversioned_filter=tree.is_ignored, view_info=view_info)
4121
pb = ui.ui_factory.nested_progress_bar()
4122
self.add_cleanup(pb.finished)
4123
self.add_cleanup(tree.lock_write().unlock)
4124
if location is not None:
4126
mergeable = bundle.read_mergeable_from_url(location,
4127
possible_transports=possible_transports)
4128
except errors.NotABundle:
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.')
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)
4132
raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4133
' with bundles or merge directives.'))
4135
if revision is not None:
4136
raise errors.BzrCommandError(gettext(
4137
'Cannot use -r with merge directives or bundles'))
4138
merger, verified = _mod_merge.Merger.from_mergeable(tree,
4141
if merger is None and uncommitted:
4142
if revision is not None and len(revision) > 0:
4143
raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4144
' --revision at the same time.'))
4145
merger = self.get_merger_from_uncommitted(tree, location, None)
4146
allow_pending = False
4149
merger, allow_pending = self._get_merger_from_branch(tree,
4150
location, revision, remember, possible_transports, None)
4152
merger.merge_type = merge_type
4153
merger.reprocess = reprocess
4154
merger.show_base = show_base
4155
self.sanity_check_merger(merger)
4156
if (merger.base_rev_id == merger.other_rev_id and
4157
merger.other_rev_id is not None):
4158
# check if location is a nonexistent file (and not a branch) to
4159
# disambiguate the 'Nothing to do'
4160
if merger.interesting_files:
4161
if not merger.other_tree.has_filename(
4162
merger.interesting_files[0]):
4163
note(gettext("merger: ") + str(merger))
4164
raise errors.PathsDoNotExist([location])
4165
note(gettext('Nothing to do.'))
4167
if pull and not preview:
4168
if merger.interesting_files is not None:
4169
raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4170
if (merger.base_rev_id == tree.last_revision()):
4171
result = tree.pull(merger.other_branch, False,
4172
merger.other_rev_id)
4173
result.report(self.outf)
4175
if merger.this_basis is None:
4176
raise errors.BzrCommandError(gettext(
4177
"This branch has no commits."
4178
" (perhaps you would prefer 'bzr pull')"))
4180
return self._do_preview(merger)
4182
return self._do_interactive(merger)
4184
return self._do_merge(merger, change_reporter, allow_pending,
4187
def _get_preview(self, merger):
3812
return self._do_merge(merger, change_reporter, allow_pending,
3815
for cleanup in reversed(cleanups):
3818
def _get_preview(self, merger, cleanups):
4188
3819
tree_merger = merger.make_merger()
4189
3820
tt = tree_merger.make_preview_transform()
4190
self.add_cleanup(tt.finalize)
3821
cleanups.append(tt.finalize)
4191
3822
result_tree = tt.get_preview_tree()
4192
3823
return result_tree
4194
def _do_preview(self, merger):
3825
def _do_preview(self, merger, cleanups):
4195
3826
from bzrlib.diff import show_diff_trees
4196
result_tree = self._get_preview(merger)
4197
path_encoding = osutils.get_diff_header_encoding()
3827
result_tree = self._get_preview(merger, cleanups)
4198
3828
show_diff_trees(merger.this_tree, result_tree, self.outf,
4199
old_label='', new_label='',
4200
path_encoding=path_encoding)
3829
old_label='', new_label='')
4202
3831
def _do_merge(self, merger, change_reporter, allow_pending, verified):
4203
3832
merger.change_reporter = change_reporter
4396
4019
def run(self, file_list=None, merge_type=None, show_base=False,
4397
4020
reprocess=False):
4398
from bzrlib.conflicts import restore
4399
4021
if merge_type is None:
4400
4022
merge_type = _mod_merge.Merge3Merger
4401
tree, file_list = WorkingTree.open_containing_paths(file_list)
4402
self.add_cleanup(tree.lock_write().unlock)
4403
parents = tree.get_parent_ids()
4404
if len(parents) != 2:
4405
raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
4406
" merges. Not cherrypicking or"
4408
repository = tree.branch.repository
4409
interesting_ids = None
4411
conflicts = tree.conflicts()
4412
if file_list is not None:
4413
interesting_ids = set()
4414
for filename in file_list:
4415
file_id = tree.path2id(filename)
4417
raise errors.NotVersionedError(filename)
4418
interesting_ids.add(file_id)
4419
if tree.kind(file_id) != "directory":
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":
4422
for name, ie in tree.inventory.iter_entries(file_id):
4423
interesting_ids.add(ie.file_id)
4424
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4426
# Remerge only supports resolving contents conflicts
4427
allowed_conflicts = ('text conflict', 'contents conflict')
4428
restore_files = [c.path for c in conflicts
4429
if c.typestring in allowed_conflicts]
4430
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4431
tree.set_conflicts(ConflictList(new_conflicts))
4432
if file_list is not None:
4433
restore_files = file_list
4434
for filename in restore_files:
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])
4436
restore(tree.abspath(filename))
4437
except errors.NotConflicted:
4439
# Disable pending merges, because the file texts we are remerging
4440
# have not had those merges performed. If we use the wrong parents
4441
# list, we imply that the working tree text has seen and rejected
4442
# all the changes from the other tree, when in fact those changes
4443
# have not yet been seen.
4444
tree.set_parent_ids(parents[:1])
4446
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4447
merger.interesting_ids = interesting_ids
4448
merger.merge_type = merge_type
4449
merger.show_base = show_base
4450
merger.reprocess = reprocess
4451
conflicts = merger.do_merge()
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)
4453
tree.set_parent_ids(parents)
4454
4082
if conflicts > 0:
4484
4111
created as above. Directories containing unknown files will not be
4487
The working tree contains a list of revisions that have been merged but
4488
not yet committed. These revisions will be included as additional parents
4489
of the next commit. Normally, using revert clears that list as well as
4490
reverting the files. If any files are specified, revert leaves the list
4491
of uncommitted merges alone and reverts only the files. Use ``bzr revert
4492
.`` in the tree root to revert all files but keep the recorded merges,
4493
and ``bzr revert --forget-merges`` to clear the pending merge list without
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
4494
4120
reverting any files.
4496
Using "bzr revert --forget-merges", it is possible to apply all of the
4497
changes from a branch in a single revision. To do this, perform the merge
4498
as desired. Then doing revert with the "--forget-merges" option will keep
4499
the content of the tree as it was, but it will clear the list of pending
4500
merges. The next commit will then contain all of the changes that are
4501
present in the other branch, but without any other parent revisions.
4502
Because this technique forgets where these changes originated, it may
4503
cause additional conflicts on later merges involving the same source and
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
4504
4130
target branches.
4507
_see_also = ['cat', 'export', 'merge', 'shelve']
4133
_see_also = ['cat', 'export']
4508
4134
takes_options = [
4510
4136
Option('no-backup', "Do not save backups of reverted files."),
4705
4314
_get_revision_range(revision,
4706
4315
remote_branch, self.name()))
4708
local_extra, remote_extra = find_unmerged(
4709
local_branch, remote_branch, restrict,
4710
backward=not reverse,
4711
include_merged=include_merged,
4712
local_revid_range=local_revid_range,
4713
remote_revid_range=remote_revid_range)
4715
if log_format is None:
4716
registry = log.log_formatter_registry
4717
log_format = registry.get_default(local_branch)
4718
lf = log_format(to_file=self.outf,
4720
show_timezone='original')
4723
if local_extra and not theirs_only:
4724
message(ngettext("You have %d extra revision:\n",
4725
"You have %d extra revisions:\n",
4728
for revision in iter_log_revisions(local_extra,
4729
local_branch.repository,
4731
lf.log_revision(revision)
4732
printed_local = True
4735
printed_local = False
4737
if remote_extra and not mine_only:
4738
if printed_local is True:
4740
message(ngettext("You are missing %d revision:\n",
4741
"You are missing %d revisions:\n",
4742
len(remote_extra)) %
4744
for revision in iter_log_revisions(remote_extra,
4745
remote_branch.repository,
4747
lf.log_revision(revision)
4750
if mine_only and not local_extra:
4751
# We checked local, and found nothing extra
4752
message(gettext('This branch has no new revisions.\n'))
4753
elif theirs_only and not remote_extra:
4754
# We checked remote, and found nothing extra
4755
message(gettext('Other branch has no new revisions.\n'))
4756
elif not (mine_only or theirs_only or local_extra or
4758
# We checked both branches, and neither one had extra
4760
message(gettext("Branches are up to date.\n"))
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()
4762
4374
if not status_code and parent is None and other_branch is not None:
4763
self.add_cleanup(local_branch.lock_write().unlock)
4764
# handle race conditions - a parent might be set while we run.
4765
if local_branch.get_parent() is None:
4766
local_branch.set_parent(remote_branch.base)
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()
4767
4382
return status_code
4770
4385
class cmd_pack(Command):
4771
__doc__ = """Compress the data within a repository.
4773
This operation compresses the data within a bazaar repository. As
4774
bazaar supports automatic packing of repository, this operation is
4775
normally not required to be done manually.
4777
During the pack operation, bazaar takes a backup of existing repository
4778
data, i.e. pack files. This backup is eventually removed by bazaar
4779
automatically when it is safe to do so. To save disk space by removing
4780
the backed up pack files, the --clean-obsolete-packs option may be
4783
Warning: If you use --clean-obsolete-packs and your machine crashes
4784
during or immediately after repacking, you may be left with a state
4785
where the deletion has been written to disk but the new packs have not
4786
been. In this case the repository may be unusable.
4386
"""Compress the data within a repository."""
4789
4388
_see_also = ['repositories']
4790
4389
takes_args = ['branch_or_repo?']
4792
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4795
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4391
def run(self, branch_or_repo='.'):
4796
4392
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4798
4394
branch = dir.open_branch()
4799
4395
repository = branch.repository
4800
4396
except errors.NotBranchError:
4801
4397
repository = dir.open_repository()
4802
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4805
4401
class cmd_plugins(Command):
4806
__doc__ = """List the installed plugins.
4402
"""List the installed plugins.
4808
4404
This command displays the list of installed plugins including
4809
4405
version of plugin and a short description of each.
4816
4412
adding new commands, providing additional network transports and
4817
4413
customizing log output.
4819
See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4820
for further information on plugins including where to find them and how to
4821
install them. Instructions are also provided there on how to write new
4822
plugins using the Python programming language.
4415
See the Bazaar web site, http://bazaar-vcs.org, for further
4416
information on plugins including where to find them and how to
4417
install them. Instructions are also provided there on how to
4418
write new plugins using the Python programming language.
4824
4420
takes_options = ['verbose']
4826
4422
@display_command
4827
4423
def run(self, verbose=False):
4828
from bzrlib import plugin
4829
# Don't give writelines a generator as some codecs don't like that
4830
self.outf.writelines(
4831
list(plugin.describe_plugins(show_paths=verbose)))
4424
import bzrlib.plugin
4425
from inspect import getdoc
4427
for name, plugin in bzrlib.plugin.plugins().items():
4428
version = plugin.__version__
4429
if version == 'unknown':
4431
name_ver = '%s %s' % (name, version)
4432
d = getdoc(plugin.module)
4434
doc = d.split('\n')[0]
4436
doc = '(no description)'
4437
result.append((name_ver, doc, plugin.path()))
4438
for name_ver, doc, path in sorted(result):
4834
4446
class cmd_testament(Command):
4835
__doc__ = """Show testament (signing-form) of a revision."""
4447
"""Show testament (signing-form) of a revision."""
4836
4448
takes_options = [
4838
4450
Option('long', help='Produce long-format testament.'),
4880
4495
Option('long', help='Show commit date in annotations.'),
4885
4499
encoding_type = 'exact'
4887
4501
@display_command
4888
4502
def run(self, filename, all=False, long=False, revision=None,
4889
show_ids=False, directory=None):
4890
from bzrlib.annotate import (
4504
from bzrlib.annotate import annotate_file, annotate_file_tree
4893
4505
wt, branch, relpath = \
4894
_open_directory_or_containing_tree_or_branch(filename, directory)
4506
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4895
4507
if wt is not None:
4896
self.add_cleanup(wt.lock_read().unlock)
4898
self.add_cleanup(branch.lock_read().unlock)
4899
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4900
self.add_cleanup(tree.lock_read().unlock)
4901
if wt is not None and revision is None:
4902
file_id = wt.path2id(relpath)
4904
file_id = tree.path2id(relpath)
4906
raise errors.NotVersionedError(filename)
4907
if wt is not None and revision is None:
4908
# If there is a tree and we're not annotating historical
4909
# versions, annotate the working tree's content.
4910
annotate_file_tree(wt, file_id, self.outf, long, all,
4913
annotate_file_tree(tree, file_id, self.outf, long, all,
4914
show_ids=show_ids, branch=branch)
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,
4917
4535
class cmd_re_sign(Command):
4918
__doc__ = """Create a digital signature for an existing revision."""
4536
"""Create a digital signature for an existing revision."""
4919
4537
# TODO be able to replace existing ones.
4921
4539
hidden = True # is this right ?
4922
4540
takes_args = ['revision_id*']
4923
takes_options = ['directory', 'revision']
4541
takes_options = ['revision']
4925
def run(self, revision_id_list=None, revision=None, directory=u'.'):
4543
def run(self, revision_id_list=None, revision=None):
4926
4544
if revision_id_list is not None and revision is not None:
4927
raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
4545
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4928
4546
if revision_id_list is None and revision is None:
4929
raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
4930
b = WorkingTree.open_containing(directory)[0].branch
4931
self.add_cleanup(b.lock_write().unlock)
4932
return self._run(b, revision_id_list, revision)
4547
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)
4934
4555
def _run(self, b, revision_id_list, revision):
4935
4556
import bzrlib.gpg as gpg
4994
4614
_see_also = ['checkouts', 'unbind']
4995
4615
takes_args = ['location?']
4996
takes_options = ['directory']
4998
def run(self, location=None, directory=u'.'):
4999
b, relpath = Branch.open_containing(directory)
4618
def run(self, location=None):
4619
b, relpath = Branch.open_containing(u'.')
5000
4620
if location is None:
5002
4622
location = b.get_old_bound_location()
5003
4623
except errors.UpgradeRequired:
5004
raise errors.BzrCommandError(gettext('No location supplied. '
5005
'This format does not remember old locations.'))
4624
raise errors.BzrCommandError('No location supplied. '
4625
'This format does not remember old locations.')
5007
4627
if location is None:
5008
if b.get_bound_location() is not None:
5009
raise errors.BzrCommandError(gettext('Branch is already bound'))
5011
raise errors.BzrCommandError(gettext('No location supplied '
5012
'and no previous location known'))
4628
raise errors.BzrCommandError('No location supplied and no '
4629
'previous location known')
5013
4630
b_other = Branch.open(location)
5015
4632
b.bind(b_other)
5016
4633
except errors.DivergedBranches:
5017
raise errors.BzrCommandError(gettext('These branches have diverged.'
5018
' Try merging, and then bind again.'))
4634
raise errors.BzrCommandError('These branches have diverged.'
4635
' Try merging, and then bind again.')
5019
4636
if b.get_config().has_explicit_nickname():
5020
4637
b.nick = b_other.nick
5023
4640
class cmd_unbind(Command):
5024
__doc__ = """Convert the current checkout into a regular branch.
4641
"""Convert the current checkout into a regular branch.
5026
4643
After unbinding, the local branch is considered independent and subsequent
5027
4644
commits will be local only.
5128
4749
end_revision=last_revno)
5131
self.outf.write(gettext('Dry-run, pretending to remove'
5132
' the above revisions.\n'))
4752
print 'Dry-run, pretending to remove the above revisions.'
4754
val = raw_input('Press <enter> to continue')
5134
self.outf.write(gettext('The above revision(s) will be removed.\n'))
5137
if not ui.ui_factory.confirm_action(
5138
gettext(u'Uncommit these revisions'),
5139
'bzrlib.builtins.uncommit',
5141
self.outf.write(gettext('Canceled\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'):
5144
4763
mutter('Uncommitting from {%s} to {%s}',
5145
4764
last_rev_id, rev_id)
5146
4765
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
5147
revno=revno, local=local, keep_tags=keep_tags)
5148
self.outf.write(gettext('You can restore the old tip by running:\n'
5149
' bzr pull . -r revid:%s\n') % last_rev_id)
4766
revno=revno, local=local)
4767
note('You can restore the old tip by running:\n'
4768
' bzr pull . -r revid:%s', last_rev_id)
5152
4771
class cmd_break_lock(Command):
5153
__doc__ = """Break a dead lock.
5155
This command breaks a lock on a repository, branch, working directory or
4772
"""Break a dead lock on a repository, branch or working directory.
5158
4774
CAUTION: Locks should only be broken when you are sure that the process
5159
4775
holding the lock has been stopped.
5161
You can get information on what locks are open via the 'bzr info
5162
[location]' command.
4777
You can get information on what locks are open via the 'bzr info' command.
5166
bzr break-lock bzr+ssh://example.com/bzr/foo
5167
bzr break-lock --conf ~/.bazaar
5170
4782
takes_args = ['location?']
5173
help='LOCATION is the directory where the config lock is.'),
5175
help='Do not ask for confirmation before breaking the lock.'),
5178
def run(self, location=None, config=False, force=False):
4784
def run(self, location=None, show=False):
5179
4785
if location is None:
5180
4786
location = u'.'
5182
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5184
{'bzrlib.lockdir.break': True})
5186
conf = _mod_config.LockableConfig(file_name=location)
5189
control, relpath = bzrdir.BzrDir.open_containing(location)
5191
control.break_lock()
5192
except NotImplementedError:
4787
control, relpath = bzrdir.BzrDir.open_containing(location)
4789
control.break_lock()
4790
except NotImplementedError:
5196
4794
class cmd_wait_until_signalled(Command):
5197
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4795
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5199
4797
This just prints a line to signal when it is ready, then blocks on stdin.
5458
5055
directly from the merge directive, without retrieving data from a
5461
`bzr send` creates a compact data set that, when applied using bzr
5462
merge, has the same effect as merging from the source branch.
5464
By default the merge directive is self-contained and can be applied to any
5465
branch containing submit_branch in its ancestory without needing access to
5468
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5469
revisions, but only a structured request to merge from the
5470
public_location. In that case the public_branch is needed and it must be
5471
up-to-date and accessible to the recipient. The public_branch is always
5472
included if known, so that people can check it later.
5474
The submit branch defaults to the parent of the source branch, but can be
5475
overridden. Both submit branch and public branch will be remembered in
5476
branch.conf the first time they are used for a particular branch. The
5477
source branch defaults to that containing the working directory, but can
5478
be changed using --from.
5480
Both the submit branch and the public branch follow the usual behavior with
5481
respect to --remember: If there is no default location set, the first send
5482
will set it (use --no-remember to avoid setting it). After that, you can
5483
omit the location to use the default. To change the default, use
5484
--remember. The value will only be saved if the location can be accessed.
5486
In order to calculate those changes, bzr must analyse the submit branch.
5487
Therefore it is most efficient for the submit branch to be a local mirror.
5488
If a public location is known for the submit_branch, that location is used
5489
in the merge directive.
5491
The default behaviour is to send the merge directive by mail, unless -o is
5492
given, in which case it is sent to a file.
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
5494
5071
Mail is sent using your preferred mail program. This should be transparent
5495
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
5072
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
5496
5073
If the preferred client can't be found (or used), your editor will be used.
5498
5075
To use a specific mail program, set the mail_client configuration option.
5657
5230
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5658
5231
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5660
If no tag name is specified it will be determined through the
5661
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5662
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5666
5234
_see_also = ['commit', 'tags']
5667
takes_args = ['tag_name?']
5235
takes_args = ['tag_name']
5668
5236
takes_options = [
5669
5237
Option('delete',
5670
5238
help='Delete this tag rather than placing it.',
5672
custom_help('directory',
5673
help='Branch in which to place the tag.'),
5241
help='Branch in which to place the tag.',
5674
5245
Option('force',
5675
5246
help='Replace existing tags.',
5680
def run(self, tag_name=None,
5251
def run(self, tag_name,
5686
5257
branch, relpath = Branch.open_containing(directory)
5687
self.add_cleanup(branch.lock_write().unlock)
5689
if tag_name is None:
5690
raise errors.BzrCommandError(gettext("No tag specified to delete."))
5691
branch.tags.delete_tag(tag_name)
5692
note(gettext('Deleted tag %s.') % tag_name)
5695
if len(revision) != 1:
5696
raise errors.BzrCommandError(gettext(
5697
"Tags can only be placed on a single revision, "
5699
revision_id = revision[0].as_revision_id(branch)
5701
revision_id = branch.last_revision()
5702
if tag_name is None:
5703
tag_name = branch.automatic_tag_name(revision_id)
5704
if tag_name is None:
5705
raise errors.BzrCommandError(gettext(
5706
"Please specify a tag name."))
5708
existing_target = branch.tags.lookup_tag(tag_name)
5709
except errors.NoSuchTag:
5710
existing_target = None
5711
if not force and existing_target not in (None, revision_id):
5712
raise errors.TagAlreadyExists(tag_name)
5713
if existing_target == revision_id:
5714
note(gettext('Tag %s already exists for that revision.') % tag_name)
5261
branch.tags.delete_tag(tag_name)
5262
self.outf.write('Deleted tag %s.\n' % tag_name)
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)
5716
5274
branch.tags.set_tag(tag_name, revision_id)
5717
if existing_target is None:
5718
note(gettext('Created tag %s.') % tag_name)
5720
note(gettext('Updated tag %s.') % tag_name)
5275
self.outf.write('Created tag %s.\n' % tag_name)
5723
5280
class cmd_tags(Command):
5724
__doc__ = """List tags.
5726
5283
This command shows a table of tag names and the revisions they reference.
5729
5286
_see_also = ['tag']
5730
5287
takes_options = [
5731
custom_help('directory',
5732
help='Branch whose tags should be displayed.'),
5733
RegistryOption('sort',
5289
help='Branch whose tags should be displayed.',
5293
RegistryOption.from_kwargs('sort',
5734
5294
'Sort tags by different criteria.', title='Sorting',
5735
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
5295
alpha='Sort tags lexicographically (default).',
5296
time='Sort tags chronologically.',
5741
5302
@display_command
5742
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5743
from bzrlib.tag import tag_sort_methods
5744
5309
branch, relpath = Branch.open_containing(directory)
5746
5311
tags = branch.tags.get_tag_dict().items()
5750
self.add_cleanup(branch.lock_read().unlock)
5752
graph = branch.repository.get_graph()
5753
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5754
revid1, revid2 = rev1.rev_id, rev2.rev_id
5755
# only show revisions between revid1 and revid2 (inclusive)
5756
tags = [(tag, revid) for tag, revid in tags if
5757
graph.is_between(revid, revid1, revid2)]
5759
sort = tag_sort_methods.get()
5762
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5763
for index, (tag, revid) in enumerate(tags):
5765
revno = branch.revision_id_to_dotted_revno(revid)
5766
if isinstance(revno, tuple):
5767
revno = '.'.join(map(str, revno))
5768
except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
5769
# Bad tag data/merges can lead to tagged revisions
5770
# which are not in this branch. Fail gracefully ...
5772
tags[index] = (tag, revno)
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)
5774
5351
for tag, revspec in tags:
5775
5352
self.outf.write('%-20s %s\n' % (tag, revspec))
5778
5355
class cmd_reconfigure(Command):
5779
__doc__ = """Reconfigure the type of a bzr directory.
5356
"""Reconfigure the type of a bzr directory.
5781
5358
A target configuration must be specified.
5793
5370
takes_args = ['location?']
5794
5371
takes_options = [
5795
5372
RegistryOption.from_kwargs(
5798
help='The relation between branch and tree.',
5374
title='Target type',
5375
help='The type to reconfigure the directory to.',
5799
5376
value_switches=True, enum_switch=False,
5800
5377
branch='Reconfigure to be an unbound branch with no working tree.',
5801
5378
tree='Reconfigure to be an unbound branch with a working tree.',
5802
5379
checkout='Reconfigure to be a bound branch with a working tree.',
5803
5380
lightweight_checkout='Reconfigure to be a lightweight'
5804
5381
' checkout (with no local history).',
5806
RegistryOption.from_kwargs(
5808
title='Repository type',
5809
help='Location fo the repository.',
5810
value_switches=True, enum_switch=False,
5811
5382
standalone='Reconfigure to be a standalone branch '
5812
5383
'(i.e. stop using shared repository).',
5813
5384
use_shared='Reconfigure to use a shared repository.',
5815
RegistryOption.from_kwargs(
5817
title='Trees in Repository',
5818
help='Whether new branches in the repository have trees.',
5819
value_switches=True, enum_switch=False,
5820
5385
with_trees='Reconfigure repository to create '
5821
5386
'working trees on branches by default.',
5822
5387
with_no_trees='Reconfigure repository to not create '
5849
5414
# At the moment you can use --stacked-on and a different
5850
5415
# reconfiguration shape at the same time; there seems no good reason
5852
if (tree_type is None and
5853
repository_type is None and
5854
repository_trees is None):
5417
if target_type is None:
5855
5418
if stacked_on or unstacked:
5858
raise errors.BzrCommandError(gettext('No target configuration '
5860
reconfiguration = None
5861
if tree_type == 'branch':
5421
raise errors.BzrCommandError('No target configuration '
5423
elif target_type == 'branch':
5862
5424
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5863
elif tree_type == 'tree':
5425
elif target_type == 'tree':
5864
5426
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5865
elif tree_type == 'checkout':
5427
elif target_type == 'checkout':
5866
5428
reconfiguration = reconfigure.Reconfigure.to_checkout(
5867
5429
directory, bind_to)
5868
elif tree_type == 'lightweight-checkout':
5430
elif target_type == 'lightweight-checkout':
5869
5431
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5870
5432
directory, bind_to)
5872
reconfiguration.apply(force)
5873
reconfiguration = None
5874
if repository_type == 'use-shared':
5433
elif target_type == 'use-shared':
5875
5434
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5876
elif repository_type == 'standalone':
5435
elif target_type == 'standalone':
5877
5436
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5879
reconfiguration.apply(force)
5880
reconfiguration = None
5881
if repository_trees == 'with-trees':
5437
elif target_type == 'with-trees':
5882
5438
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5883
5439
directory, True)
5884
elif repository_trees == 'with-no-trees':
5440
elif target_type == 'with-no-trees':
5885
5441
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5886
5442
directory, False)
5888
reconfiguration.apply(force)
5889
reconfiguration = None
5443
reconfiguration.apply(force)
5892
5446
class cmd_switch(Command):
5893
__doc__ = """Set the branch of a checkout and update.
5447
"""Set the branch of a checkout and update.
5895
5449
For lightweight checkouts, this changes the branch being referenced.
5896
5450
For heavyweight checkouts, this checks that there are no local commits
6076
tree, file_list = WorkingTree.open_containing_paths(file_list,
5624
tree, file_list = tree_files(file_list, apply_view=False)
6078
5625
current_view, view_dict = tree.views.get_view_info()
6079
5626
if name is None:
6080
5627
name = current_view
6083
raise errors.BzrCommandError(gettext(
6084
"Both --delete and a file list specified"))
5630
raise errors.BzrCommandError(
5631
"Both --delete and a file list specified")
6086
raise errors.BzrCommandError(gettext(
6087
"Both --delete and --switch specified"))
5633
raise errors.BzrCommandError(
5634
"Both --delete and --switch specified")
6089
5636
tree.views.set_view_info(None, {})
6090
self.outf.write(gettext("Deleted all views.\n"))
5637
self.outf.write("Deleted all views.\n")
6091
5638
elif name is None:
6092
raise errors.BzrCommandError(gettext("No current view to delete"))
5639
raise errors.BzrCommandError("No current view to delete")
6094
5641
tree.views.delete_view(name)
6095
self.outf.write(gettext("Deleted '%s' view.\n") % name)
5642
self.outf.write("Deleted '%s' view.\n" % name)
6098
raise errors.BzrCommandError(gettext(
6099
"Both --switch and a file list specified"))
5645
raise errors.BzrCommandError(
5646
"Both --switch and a file list specified")
6101
raise errors.BzrCommandError(gettext(
6102
"Both --switch and --all specified"))
5648
raise errors.BzrCommandError(
5649
"Both --switch and --all specified")
6103
5650
elif switch == 'off':
6104
5651
if current_view is None:
6105
raise errors.BzrCommandError(gettext("No current view to disable"))
5652
raise errors.BzrCommandError("No current view to disable")
6106
5653
tree.views.set_view_info(None, view_dict)
6107
self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
5654
self.outf.write("Disabled '%s' view.\n" % (current_view))
6109
5656
tree.views.set_view_info(switch, view_dict)
6110
5657
view_str = views.view_display_str(tree.views.lookup_view())
6111
self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
5658
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
6114
self.outf.write(gettext('Views defined:\n'))
5661
self.outf.write('Views defined:\n')
6115
5662
for view in sorted(view_dict):
6116
5663
if view == current_view:
6390
5896
self.outf.write('%s %s\n' % (path, location))
6393
class cmd_export_pot(Command):
6394
__doc__ = """Export command helps and error messages in po format."""
6399
from bzrlib.export_pot import export_pot
6400
export_pot(self.outf)
6403
def _register_lazy_builtins():
6404
# register lazy builtins from other modules; called at startup and should
6405
# be only called once.
6406
for (name, aliases, module_name) in [
6407
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6408
('cmd_config', [], 'bzrlib.config'),
6409
('cmd_dpush', [], 'bzrlib.foreign'),
6410
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6411
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6412
('cmd_conflicts', [], 'bzrlib.conflicts'),
6413
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6414
('cmd_verify_signatures', [],
6415
'bzrlib.commit_signature_commands'),
6416
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6418
builtin_command_registry.register_lazy(name, aliases, module_name)
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