156
180
:return: workingtree, [relative_paths]
158
if file_list is None or len(file_list) == 0:
159
tree = WorkingTree.open_containing(default_branch)[0]
160
if tree.supports_views() and apply_view:
161
view_files = tree.views.lookup_view()
163
file_list = view_files
164
view_str = views.view_display_str(view_files)
165
note("Ignoring files outside view. View is %s" % view_str)
166
return tree, file_list
167
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
168
return tree, safe_relpath_files(tree, file_list, canonicalize,
169
apply_view=apply_view)
172
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
173
"""Convert file_list into a list of relpaths in tree.
175
:param tree: A tree to operate on.
176
:param file_list: A list of user provided paths or None.
177
:param apply_view: if True and a view is set, apply it or check that
178
specified files are within it
179
:return: A list of relative paths.
180
:raises errors.PathNotChild: When a provided path is in a different tree
183
if file_list is None:
185
if tree.supports_views() and apply_view:
186
view_files = tree.views.lookup_view()
190
# tree.relpath exists as a "thunk" to osutils, but canonical_relpath
191
# doesn't - fix that up here before we enter the loop.
193
fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
196
for filename in file_list:
198
relpath = fixer(osutils.dereference_path(filename))
199
if view_files and not osutils.is_inside_any(view_files, relpath):
200
raise errors.FileOutsideView(filename, view_files)
201
new_list.append(relpath)
202
except errors.PathNotChild:
203
raise errors.FileInWrongBranch(tree.branch, filename)
182
return WorkingTree.open_containing_paths(
183
file_list, default_directory='.',
207
188
def _get_view_info_for_change_reporter(tree):
322
325
takes_args = ['revision_id?']
323
takes_options = ['revision']
326
takes_options = ['directory', 'revision']
324
327
# cat-revision is more for frontends so should be exact
325
328
encoding = 'strict'
330
def print_revision(self, revisions, revid):
331
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
332
record = stream.next()
333
if record.storage_kind == 'absent':
334
raise errors.NoSuchRevision(revisions, revid)
335
revtext = record.get_bytes_as('fulltext')
336
self.outf.write(revtext.decode('utf-8'))
328
def run(self, revision_id=None, revision=None):
339
def run(self, revision_id=None, revision=None, directory=u'.'):
329
340
if revision_id is not None and revision is not None:
330
raise errors.BzrCommandError('You can only supply one of'
331
' revision_id or --revision')
341
raise errors.BzrCommandError(gettext('You can only supply one of'
342
' revision_id or --revision'))
332
343
if revision_id is None and revision is None:
333
raise errors.BzrCommandError('You must supply either'
334
' --revision or a revision_id')
335
b = WorkingTree.open_containing(u'.')[0].branch
337
# TODO: jam 20060112 should cat-revision always output utf-8?
338
if revision_id is not None:
339
revision_id = osutils.safe_revision_id(revision_id, warn=False)
341
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
342
except errors.NoSuchRevision:
343
msg = "The repository %s contains no revision %s." % (b.repository.base,
345
raise errors.BzrCommandError(msg)
346
elif revision is not None:
349
raise errors.BzrCommandError('You cannot specify a NULL'
351
rev_id = rev.as_revision_id(b)
352
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
344
raise errors.BzrCommandError(gettext('You must supply either'
345
' --revision or a revision_id'))
347
b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
349
revisions = b.repository.revisions
350
if revisions is None:
351
raise errors.BzrCommandError(gettext('Repository %r does not support '
352
'access to raw revision texts'))
354
b.repository.lock_read()
356
# TODO: jam 20060112 should cat-revision always output utf-8?
357
if revision_id is not None:
358
revision_id = osutils.safe_revision_id(revision_id, warn=False)
360
self.print_revision(revisions, revision_id)
361
except errors.NoSuchRevision:
362
msg = gettext("The repository {0} contains no revision {1}.").format(
363
b.repository.base, revision_id)
364
raise errors.BzrCommandError(msg)
365
elif revision is not None:
368
raise errors.BzrCommandError(
369
gettext('You cannot specify a NULL revision.'))
370
rev_id = rev.as_revision_id(b)
371
self.print_revision(revisions, rev_id)
373
b.repository.unlock()
355
376
class cmd_dump_btree(Command):
356
"""Dump the contents of a btree index file to stdout.
377
__doc__ = """Dump the contents of a btree index file to stdout.
358
379
PATH is a btree index file, it can be any URL. This includes things like
359
380
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
435
466
To re-create the working tree, use "bzr checkout".
437
468
_see_also = ['checkout', 'working-trees']
438
takes_args = ['location?']
469
takes_args = ['location*']
439
470
takes_options = [
441
472
help='Remove the working tree even if it has '
442
'uncommitted changes.'),
473
'uncommitted or shelved changes.'),
445
def run(self, location='.', force=False):
446
d = bzrdir.BzrDir.open(location)
476
def run(self, location_list, force=False):
477
if not location_list:
480
for location in location_list:
481
d = controldir.ControlDir.open(location)
484
working = d.open_workingtree()
485
except errors.NoWorkingTree:
486
raise errors.BzrCommandError(gettext("No working tree to remove"))
487
except errors.NotLocalUrl:
488
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
489
" of a remote path"))
491
if (working.has_changes()):
492
raise errors.UncommittedChanges(working)
493
if working.get_shelf_manager().last_shelf() is not None:
494
raise errors.ShelvedChanges(working)
496
if working.user_url != working.branch.user_url:
497
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
498
" from a lightweight checkout"))
500
d.destroy_workingtree()
503
class cmd_repair_workingtree(Command):
504
__doc__ = """Reset the working tree state file.
506
This is not meant to be used normally, but more as a way to recover from
507
filesystem corruption, etc. This rebuilds the working inventory back to a
508
'known good' state. Any new modifications (adding a file, renaming, etc)
509
will be lost, though modified files will still be detected as such.
511
Most users will want something more like "bzr revert" or "bzr update"
512
unless the state file has become corrupted.
514
By default this attempts to recover the current state by looking at the
515
headers of the state file. If the state file is too corrupted to even do
516
that, you can supply --revision to force the state of the tree.
519
takes_options = ['revision', 'directory',
521
help='Reset the tree even if it doesn\'t appear to be'
526
def run(self, revision=None, directory='.', force=False):
527
tree, _ = WorkingTree.open_containing(directory)
528
self.add_cleanup(tree.lock_tree_write().unlock)
532
except errors.BzrError:
533
pass # There seems to be a real error here, so we'll reset
536
raise errors.BzrCommandError(gettext(
537
'The tree does not appear to be corrupt. You probably'
538
' want "bzr revert" instead. Use "--force" if you are'
539
' sure you want to reset the working tree.'))
543
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
449
working = d.open_workingtree()
450
except errors.NoWorkingTree:
451
raise errors.BzrCommandError("No working tree to remove")
452
except errors.NotLocalUrl:
453
raise errors.BzrCommandError("You cannot remove the working tree of a "
456
changes = working.changes_from(working.basis_tree())
457
if changes.has_changed():
458
raise errors.UncommittedChanges(working)
460
working_path = working.bzrdir.root_transport.base
461
branch_path = working.branch.bzrdir.root_transport.base
462
if working_path != branch_path:
463
raise errors.BzrCommandError("You cannot remove the working tree from "
464
"a lightweight checkout")
466
d.destroy_workingtree()
545
tree.reset_state(revision_ids)
546
except errors.BzrError, e:
547
if revision_ids is None:
548
extra = (gettext(', the header appears corrupt, try passing -r -1'
549
' to set the state to the last commit'))
552
raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
469
555
class cmd_revno(Command):
470
"""Show current revision number.
556
__doc__ = """Show current revision number.
472
558
This is equal to the number of revisions on this branch.
475
561
_see_also = ['info']
476
562
takes_args = ['location?']
564
Option('tree', help='Show revno of working tree.'),
479
def run(self, location=u'.'):
480
self.outf.write(str(Branch.open_containing(location)[0].revno()))
481
self.outf.write('\n')
569
def run(self, tree=False, location=u'.', revision=None):
570
if revision is not None and tree:
571
raise errors.BzrCommandError(gettext("--tree and --revision can "
572
"not be used together"))
576
wt = WorkingTree.open_containing(location)[0]
577
self.add_cleanup(wt.lock_read().unlock)
578
except (errors.NoWorkingTree, errors.NotLocalUrl):
579
raise errors.NoWorkingTree(location)
581
revid = wt.last_revision()
583
b = Branch.open_containing(location)[0]
584
self.add_cleanup(b.lock_read().unlock)
586
if len(revision) != 1:
587
raise errors.BzrCommandError(gettext(
588
"Tags can only be placed on a single revision, "
590
revid = revision[0].as_revision_id(b)
592
revid = b.last_revision()
594
revno_t = b.revision_id_to_dotted_revno(revid)
595
except errors.NoSuchRevision:
597
revno = ".".join(str(n) for n in revno_t)
599
self.outf.write(revno + '\n')
484
602
class cmd_revision_info(Command):
485
"""Show revision number and revision id for a given revision identifier.
603
__doc__ = """Show revision number and revision id for a given revision identifier.
488
606
takes_args = ['revision_info*']
489
607
takes_options = [
609
custom_help('directory',
492
610
help='Branch to examine, '
493
'rather than the one containing the working directory.',
611
'rather than the one containing the working directory.'),
612
Option('tree', help='Show revno of working tree.'),
500
def run(self, revision=None, directory=u'.', revision_info_list=[]):
616
def run(self, revision=None, directory=u'.', tree=False,
617
revision_info_list=[]):
620
wt = WorkingTree.open_containing(directory)[0]
622
self.add_cleanup(wt.lock_read().unlock)
623
except (errors.NoWorkingTree, errors.NotLocalUrl):
625
b = Branch.open_containing(directory)[0]
626
self.add_cleanup(b.lock_read().unlock)
503
628
if revision is not None:
504
revs.extend(revision)
629
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
505
630
if revision_info_list is not None:
506
for rev in revision_info_list:
507
revs.append(RevisionSpec.from_string(rev))
509
b = Branch.open_containing(directory)[0]
512
revs.append(RevisionSpec.from_string('-1'))
515
revision_id = rev.as_revision_id(b)
631
for rev_str in revision_info_list:
632
rev_spec = RevisionSpec.from_string(rev_str)
633
revision_ids.append(rev_spec.as_revision_id(b))
634
# No arguments supplied, default to the last revision
635
if len(revision_ids) == 0:
638
raise errors.NoWorkingTree(directory)
639
revision_ids.append(wt.last_revision())
641
revision_ids.append(b.last_revision())
645
for revision_id in revision_ids:
517
revno = '%4d' % (b.revision_id_to_revno(revision_id))
647
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
648
revno = '.'.join(str(i) for i in dotted_revno)
518
649
except errors.NoSuchRevision:
519
dotted_map = b.get_revision_id_to_revno_map()
520
revno = '.'.join(str(i) for i in dotted_map[revision_id])
521
print '%s %s' % (revno, revision_id)
651
maxlen = max(maxlen, len(revno))
652
revinfos.append([revno, revision_id])
656
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
524
659
class cmd_add(Command):
525
"""Add specified files or directories.
660
__doc__ = """Add specified files or directories.
527
662
In non-recursive mode, all the named items are added, regardless
528
663
of whether they were previously ignored. A warning is given if
586
731
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
587
732
to_file=self.outf, should_print=(not is_quiet()))
589
action = bzrlib.add.AddAction(to_file=self.outf,
734
action = bzrlib.add.AddWithSkipLargeAction(to_file=self.outf,
590
735
should_print=(not is_quiet()))
593
base_tree.lock_read()
595
file_list = self._maybe_expand_globs(file_list)
596
tree, file_list = tree_files_for_add(file_list)
597
added, ignored = tree.smart_add(file_list, not
598
no_recurse, action=action, save=not dry_run)
600
if base_tree is not None:
738
self.add_cleanup(base_tree.lock_read().unlock)
739
tree, file_list = tree_files_for_add(file_list)
740
added, ignored = tree.smart_add(file_list, not
741
no_recurse, action=action, save=not dry_run)
602
743
if len(ignored) > 0:
604
745
for glob in sorted(ignored.keys()):
605
746
for path in ignored[glob]:
606
self.outf.write("ignored %s matching \"%s\"\n"
610
for glob, paths in ignored.items():
611
match_len += len(paths)
612
self.outf.write("ignored %d file(s).\n" % match_len)
613
self.outf.write("If you wish to add ignored files, "
614
"please add them explicitly by name. "
615
"(\"bzr ignored\" gives a list)\n")
748
gettext("ignored {0} matching \"{1}\"\n").format(
618
752
class cmd_mkdir(Command):
619
"""Create a new versioned directory.
753
__doc__ = """Create a new versioned directory.
621
755
This is equivalent to creating the directory and then adding it.
624
758
takes_args = ['dir+']
762
help='No error if existing, make parent directories as needed.',
625
766
encoding_type = 'replace'
627
def run(self, dir_list):
630
wt, dd = WorkingTree.open_containing(d)
632
self.outf.write('added %s\n' % d)
769
def add_file_with_parents(cls, wt, relpath):
770
if wt.path2id(relpath) is not None:
772
cls.add_file_with_parents(wt, osutils.dirname(relpath))
776
def add_file_single(cls, wt, relpath):
779
def run(self, dir_list, parents=False):
781
add_file = self.add_file_with_parents
783
add_file = self.add_file_single
785
wt, relpath = WorkingTree.open_containing(dir)
790
if e.errno != errno.EEXIST:
794
add_file(wt, relpath)
796
self.outf.write(gettext('added %s\n') % dir)
635
799
class cmd_relpath(Command):
636
"""Show path of a file relative to root"""
800
__doc__ = """Show path of a file relative to root"""
638
802
takes_args = ['filename']
672
836
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
673
837
if kind and kind not in ['file', 'directory', 'symlink']:
674
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
838
raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
676
840
revision = _get_one_revision('inventory', revision)
677
work_tree, file_list = tree_files(file_list)
678
work_tree.lock_read()
680
if revision is not None:
681
tree = revision.as_tree(work_tree.branch)
683
extra_trees = [work_tree]
689
if file_list is not None:
690
file_ids = tree.paths2ids(file_list, trees=extra_trees,
691
require_versioned=True)
692
# find_ids_across_trees may include some paths that don't
694
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
695
for file_id in file_ids if file_id in tree)
697
entries = tree.inventory.entries()
700
if tree is not work_tree:
841
work_tree, file_list = WorkingTree.open_containing_paths(file_list)
842
self.add_cleanup(work_tree.lock_read().unlock)
843
if revision is not None:
844
tree = revision.as_tree(work_tree.branch)
846
extra_trees = [work_tree]
847
self.add_cleanup(tree.lock_read().unlock)
852
if file_list is not None:
853
file_ids = tree.paths2ids(file_list, trees=extra_trees,
854
require_versioned=True)
855
# find_ids_across_trees may include some paths that don't
858
(tree.id2path(file_id), tree.inventory[file_id])
859
for file_id in file_ids if tree.has_id(file_id))
861
entries = tree.inventory.entries()
703
864
for path, entry in entries:
704
865
if kind and kind != entry.kind:
745
906
return self.run_auto(names_list, after, dry_run)
747
raise errors.BzrCommandError('--dry-run requires --auto.')
908
raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
748
909
if names_list is None:
750
911
if len(names_list) < 2:
751
raise errors.BzrCommandError("missing file argument")
752
tree, rel_names = tree_files(names_list, canonicalize=False)
755
self._run(tree, names_list, rel_names, after)
912
raise errors.BzrCommandError(gettext("missing file argument"))
913
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
914
for file_name in rel_names[0:-1]:
916
raise errors.BzrCommandError(gettext("can not move root of branch"))
917
self.add_cleanup(tree.lock_tree_write().unlock)
918
self._run(tree, names_list, rel_names, after)
759
920
def run_auto(self, names_list, after, dry_run):
760
921
if names_list is not None and len(names_list) > 1:
761
raise errors.BzrCommandError('Only one path may be specified to'
922
raise errors.BzrCommandError(gettext('Only one path may be specified to'
764
raise errors.BzrCommandError('--after cannot be specified with'
766
work_tree, file_list = tree_files(names_list, default_branch='.')
767
work_tree.lock_write()
769
rename_map.RenameMap.guess_renames(work_tree, dry_run)
925
raise errors.BzrCommandError(gettext('--after cannot be specified with'
927
work_tree, file_list = WorkingTree.open_containing_paths(
928
names_list, default_directory='.')
929
self.add_cleanup(work_tree.lock_tree_write().unlock)
930
rename_map.RenameMap.guess_renames(work_tree, dry_run)
773
932
def _run(self, tree, names_list, rel_names, after):
774
933
into_existing = osutils.isdir(names_list[-1])
846
1006
dest = osutils.pathjoin(dest_parent, dest_tail)
847
1007
mutter("attempting to move %s => %s", src, dest)
848
1008
tree.rename_one(src, dest, after=after)
849
self.outf.write("%s => %s\n" % (src, dest))
1010
self.outf.write("%s => %s\n" % (src, dest))
852
1013
class cmd_pull(Command):
853
"""Turn this branch into a mirror of another branch.
1014
__doc__ = """Turn this branch into a mirror of another branch.
855
This command only works on branches that have not diverged. Branches are
856
considered diverged if the destination branch's most recent commit is one
857
that has not been merged (directly or indirectly) into the parent.
1016
By default, this command only works on branches that have not diverged.
1017
Branches are considered diverged if the destination branch's most recent
1018
commit is one that has not been merged (directly or indirectly) into the
859
1021
If branches have diverged, you can use 'bzr merge' to integrate the changes
860
1022
from one into the other. Once one branch has merged, the other should
861
1023
be able to pull it again.
863
If you want to forget your local changes and just update your branch to
864
match the remote one, use pull --overwrite.
866
If there is no default location set, the first pull will set it. After
867
that, you can omit the location to use the default. To change the
868
default, use --remember. The value will only be saved if the remote
869
location can be accessed.
1025
If you want to replace your local changes and just want your branch to
1026
match the remote one, use pull --overwrite. This will work even if the two
1027
branches have diverged.
1029
If there is no default location set, the first pull will set it (use
1030
--no-remember to avoid setting it). After that, you can omit the
1031
location to use the default. To change the default, use --remember. The
1032
value will only be saved if the remote location can be accessed.
1034
The --verbose option will display the revisions pulled using the log_format
1035
configuration option. You can use a different format by overriding it with
1036
-Olog_format=<other_format>.
871
1038
Note: The location can be specified either in the form of a branch,
872
1039
or in the form of a path to a file containing a merge directive generated
943
1115
branch_from = Branch.open(location,
944
1116
possible_transports=possible_transports)
946
if branch_to.get_parent() is None or remember:
1117
self.add_cleanup(branch_from.lock_read().unlock)
1118
# Remembers if asked explicitly or no previous location is set
1120
or (remember is None and branch_to.get_parent() is None)):
947
1121
branch_to.set_parent(branch_from.base)
949
if branch_from is not branch_to:
950
branch_from.lock_read()
952
if revision is not None:
953
revision_id = revision.as_revision_id(branch_from)
955
branch_to.lock_write()
957
if tree_to is not None:
958
view_info = _get_view_info_for_change_reporter(tree_to)
959
change_reporter = delta._ChangeReporter(
960
unversioned_filter=tree_to.is_ignored,
962
result = tree_to.pull(
963
branch_from, overwrite, revision_id, change_reporter,
964
possible_transports=possible_transports, local=local)
966
result = branch_to.pull(
967
branch_from, overwrite, revision_id, local=local)
969
result.report(self.outf)
970
if verbose and result.old_revid != result.new_revid:
971
log.show_branch_change(
972
branch_to, self.outf, result.old_revno,
977
if branch_from is not branch_to:
1123
if revision is not None:
1124
revision_id = revision.as_revision_id(branch_from)
1126
if tree_to is not None:
1127
view_info = _get_view_info_for_change_reporter(tree_to)
1128
change_reporter = delta._ChangeReporter(
1129
unversioned_filter=tree_to.is_ignored,
1130
view_info=view_info)
1131
result = tree_to.pull(
1132
branch_from, overwrite, revision_id, change_reporter,
1133
local=local, show_base=show_base)
1135
result = branch_to.pull(
1136
branch_from, overwrite, revision_id, local=local)
1138
result.report(self.outf)
1139
if verbose and result.old_revid != result.new_revid:
1140
log.show_branch_change(
1141
branch_to, self.outf, result.old_revno,
1143
if getattr(result, 'tag_conflicts', None):
981
1149
class cmd_push(Command):
982
"""Update a mirror of this branch.
1150
__doc__ = """Update a mirror of this branch.
984
1152
The target branch will not have its working tree populated because this
985
1153
is both expensive, and is not supported on remote file systems.
1031
1200
Option('strict',
1032
1201
help='Refuse to push if there are uncommitted changes in'
1033
' the working tree.'),
1202
' the working tree, --no-strict disables the check.'),
1204
help="Don't populate the working tree, even for protocols"
1205
" that support it."),
1035
1207
takes_args = ['location?']
1036
1208
encoding_type = 'replace'
1038
def run(self, location=None, remember=False, overwrite=False,
1210
def run(self, location=None, remember=None, overwrite=False,
1039
1211
create_prefix=False, verbose=False, revision=None,
1040
1212
use_existing_dir=False, directory=None, stacked_on=None,
1041
stacked=False, strict=None):
1213
stacked=False, strict=None, no_tree=False):
1042
1214
from bzrlib.push import _show_push_branch
1044
1216
if directory is None:
1045
1217
directory = '.'
1046
1218
# Get the source branch
1047
tree, br_from = bzrdir.BzrDir.open_tree_or_branch(directory)
1049
strict = br_from.get_config().get_user_option('push_strict')
1050
if strict is not None:
1051
# FIXME: This should be better supported by config
1053
bools = dict(yes=True, no=False, on=True, off=False,
1054
true=True, false=False)
1056
strict = bools[strict.lower()]
1060
changes = tree.changes_from(tree.basis_tree())
1061
if changes.has_changed():
1062
raise errors.UncommittedChanges(tree)
1220
_unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
1063
1221
# Get the tip's revision_id
1064
1222
revision = _get_one_revision('push', revision)
1065
1223
if revision is not None:
1066
1224
revision_id = revision.in_history(br_from).rev_id
1068
1226
revision_id = None
1227
if tree is not None and revision_id is None:
1228
tree.check_changed_or_out_of_date(
1229
strict, 'push_strict',
1230
more_error='Use --no-strict to force the push.',
1231
more_warning='Uncommitted changes will not be pushed.')
1070
1232
# Get the stacked_on branch, if any
1071
1233
if stacked_on is not None:
1072
1234
stacked_on = urlutils.normalize_url(stacked_on)
1082
1244
# error by the feedback given to them. RBC 20080227.
1083
1245
stacked_on = parent_url
1084
1246
if not stacked_on:
1085
raise errors.BzrCommandError(
1086
"Could not determine branch to refer to.")
1247
raise errors.BzrCommandError(gettext(
1248
"Could not determine branch to refer to."))
1088
1250
# Get the destination location
1089
1251
if location is None:
1090
1252
stored_loc = br_from.get_push_location()
1091
1253
if stored_loc is None:
1092
raise errors.BzrCommandError(
1093
"No push location known or specified.")
1254
parent_loc = br_from.get_parent()
1256
raise errors.BzrCommandError(gettext(
1257
"No push location known or specified. To push to the "
1258
"parent branch (at %s), use 'bzr push :parent'." %
1259
urlutils.unescape_for_display(parent_loc,
1260
self.outf.encoding)))
1262
raise errors.BzrCommandError(gettext(
1263
"No push location known or specified."))
1095
1265
display_url = urlutils.unescape_for_display(stored_loc,
1096
1266
self.outf.encoding)
1097
self.outf.write("Using saved push location: %s\n" % display_url)
1267
note(gettext("Using saved push location: %s") % display_url)
1098
1268
location = stored_loc
1100
1270
_show_push_branch(br_from, revision_id, location, self.outf,
1101
1271
verbose=verbose, overwrite=overwrite, remember=remember,
1102
1272
stacked_on=stacked_on, create_prefix=create_prefix,
1103
use_existing_dir=use_existing_dir)
1273
use_existing_dir=use_existing_dir, no_tree=no_tree)
1106
1276
class cmd_branch(Command):
1107
"""Create a new branch that is a copy of an existing branch.
1277
__doc__ = """Create a new branch that is a copy of an existing branch.
1109
1279
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1110
1280
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1116
1286
To retrieve the branch as of a particular revision, supply the --revision
1117
1287
parameter, as in "branch foo/bar -r 5".
1289
The synonyms 'clone' and 'get' for this command are deprecated.
1120
1292
_see_also = ['checkout']
1121
1293
takes_args = ['from_location', 'to_location?']
1122
takes_options = ['revision', Option('hardlink',
1123
help='Hard-link working tree files where possible.'),
1294
takes_options = ['revision',
1295
Option('hardlink', help='Hard-link working tree files where possible.'),
1296
Option('files-from', type=str,
1297
help="Get file contents from this tree."),
1124
1298
Option('no-tree',
1125
1299
help="Create a branch without a working-tree."),
1301
help="Switch the checkout in the current directory "
1302
"to the new branch."),
1126
1303
Option('stacked',
1127
1304
help='Create a stacked branch referring to the source branch. '
1128
1305
'The new branch will depend on the availability of the source '
1129
1306
'branch for all operations.'),
1130
1307
Option('standalone',
1131
1308
help='Do not use a shared repository, even if available.'),
1309
Option('use-existing-dir',
1310
help='By default branch will fail if the target'
1311
' directory exists, but does not already'
1312
' have a control directory. This flag will'
1313
' allow branch to proceed.'),
1315
help="Bind new branch to from location."),
1133
1317
aliases = ['get', 'clone']
1135
1319
def run(self, from_location, to_location=None, revision=None,
1136
hardlink=False, stacked=False, standalone=False, no_tree=False):
1320
hardlink=False, stacked=False, standalone=False, no_tree=False,
1321
use_existing_dir=False, switch=False, bind=False,
1323
from bzrlib import switch as _mod_switch
1137
1324
from bzrlib.tag import _merge_tags_if_possible
1139
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1325
if self.invoked_as in ['get', 'clone']:
1326
ui.ui_factory.show_user_warning(
1327
'deprecated_command',
1328
deprecated_name=self.invoked_as,
1329
recommended_name='branch',
1330
deprecated_in_version='2.4')
1331
accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
1141
if (accelerator_tree is not None and
1142
accelerator_tree.supports_content_filtering()):
1333
if not (hardlink or files_from):
1334
# accelerator_tree is usually slower because you have to read N
1335
# files (no readahead, lots of seeks, etc), but allow the user to
1336
# explicitly request it
1143
1337
accelerator_tree = None
1338
if files_from is not None and files_from != from_location:
1339
accelerator_tree = WorkingTree.open(files_from)
1144
1340
revision = _get_one_revision('branch', revision)
1147
if revision is not None:
1148
revision_id = revision.as_revision_id(br_from)
1150
# FIXME - wt.last_revision, fallback to branch, fall back to
1151
# None or perhaps NULL_REVISION to mean copy nothing
1153
revision_id = br_from.last_revision()
1341
self.add_cleanup(br_from.lock_read().unlock)
1342
if revision is not None:
1343
revision_id = revision.as_revision_id(br_from)
1345
# FIXME - wt.last_revision, fallback to branch, fall back to
1346
# None or perhaps NULL_REVISION to mean copy nothing
1348
revision_id = br_from.last_revision()
1349
if to_location is None:
1350
to_location = getattr(br_from, "name", None)
1154
1351
if to_location is None:
1155
1352
to_location = urlutils.derive_to_location(from_location)
1156
to_transport = transport.get_transport(to_location)
1353
to_transport = transport.get_transport(to_location)
1355
to_transport.mkdir('.')
1356
except errors.FileExists:
1158
to_transport.mkdir('.')
1159
except errors.FileExists:
1160
raise errors.BzrCommandError('Target directory "%s" already'
1161
' exists.' % to_location)
1162
except errors.NoSuchFile:
1163
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1358
to_dir = controldir.ControlDir.open_from_transport(
1360
except errors.NotBranchError:
1361
if not use_existing_dir:
1362
raise errors.BzrCommandError(gettext('Target directory "%s" '
1363
'already exists.') % to_location)
1368
to_dir.open_branch()
1369
except errors.NotBranchError:
1372
raise errors.AlreadyBranchError(to_location)
1373
except errors.NoSuchFile:
1374
raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
1166
1380
# preserve whatever source format we have.
1167
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1381
to_dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1168
1382
possible_transports=[to_transport],
1169
1383
accelerator_tree=accelerator_tree,
1170
1384
hardlink=hardlink, stacked=stacked,
1171
1385
force_new_repo=standalone,
1172
1386
create_tree_if_local=not no_tree,
1173
1387
source_branch=br_from)
1174
branch = dir.open_branch()
1388
branch = to_dir.open_branch(
1389
possible_transports=[
1390
br_from.bzrdir.root_transport, to_transport])
1175
1391
except errors.NoSuchRevision:
1176
1392
to_transport.delete_tree('.')
1177
msg = "The branch %s has no revision %s." % (from_location,
1393
msg = gettext("The branch {0} has no revision {1}.").format(
1394
from_location, revision)
1179
1395
raise errors.BzrCommandError(msg)
1180
_merge_tags_if_possible(br_from, branch)
1181
# If the source branch is stacked, the new branch may
1182
# be stacked whether we asked for that explicitly or not.
1183
# We therefore need a try/except here and not just 'if stacked:'
1397
branch = br_from.sprout(to_dir, revision_id=revision_id)
1398
_merge_tags_if_possible(br_from, branch)
1399
# If the source branch is stacked, the new branch may
1400
# be stacked whether we asked for that explicitly or not.
1401
# We therefore need a try/except here and not just 'if stacked:'
1403
note(gettext('Created new stacked branch referring to %s.') %
1404
branch.get_stacked_on_url())
1405
except (errors.NotStacked, errors.UnstackableBranchFormat,
1406
errors.UnstackableRepositoryFormat), e:
1407
note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
1409
# Bind to the parent
1410
parent_branch = Branch.open(from_location)
1411
branch.bind(parent_branch)
1412
note(gettext('New branch bound to %s') % from_location)
1414
# Switch to the new branch
1415
wt, _ = WorkingTree.open_containing('.')
1416
_mod_switch.switch(wt.bzrdir, branch)
1417
note(gettext('Switched to branch: %s'),
1418
urlutils.unescape_for_display(branch.base, 'utf-8'))
1421
class cmd_branches(Command):
1422
__doc__ = """List the branches available at the current location.
1424
This command will print the names of all the branches at the current
1428
takes_args = ['location?']
1430
Option('recursive', short_name='R',
1431
help='Recursively scan for branches rather than '
1432
'just looking in the specified location.')]
1434
def run(self, location=".", recursive=False):
1436
t = transport.get_transport(location)
1437
if not t.listable():
1438
raise errors.BzrCommandError(
1439
"Can't scan this type of location.")
1440
for b in controldir.ControlDir.find_branches(t):
1441
self.outf.write("%s\n" % urlutils.unescape_for_display(
1442
urlutils.relative_url(t.base, b.base),
1443
self.outf.encoding).rstrip("/"))
1445
dir = controldir.ControlDir.open_containing(location)[0]
1185
note('Created new stacked branch referring to %s.' %
1186
branch.get_stacked_on_url())
1187
except (errors.NotStacked, errors.UnstackableBranchFormat,
1188
errors.UnstackableRepositoryFormat), e:
1189
note('Branched %d revision(s).' % branch.revno())
1447
active_branch = dir.open_branch(name="")
1448
except errors.NotBranchError:
1449
active_branch = None
1450
branches = dir.get_branches()
1452
for name, branch in branches.iteritems():
1455
active = (active_branch is not None and
1456
active_branch.base == branch.base)
1457
names[name] = active
1458
# Only mention the current branch explicitly if it's not
1459
# one of the colocated branches
1460
if not any(names.values()) and active_branch is not None:
1461
self.outf.write("* %s\n" % gettext("(default)"))
1462
for name in sorted(names.keys()):
1463
active = names[name]
1468
self.outf.write("%s %s\n" % (
1469
prefix, name.encode(self.outf.encoding)))
1194
1472
class cmd_checkout(Command):
1195
"""Create a new checkout of an existing branch.
1473
__doc__ = """Create a new checkout of an existing branch.
1197
1475
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1198
1476
the branch found in '.'. This is useful if you have removed the working tree
1272
1555
@display_command
1273
1556
def run(self, dir=u'.'):
1274
1557
tree = WorkingTree.open_containing(dir)[0]
1277
new_inv = tree.inventory
1278
old_tree = tree.basis_tree()
1279
old_tree.lock_read()
1281
old_inv = old_tree.inventory
1283
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1284
for f, paths, c, v, p, n, k, e in iterator:
1285
if paths[0] == paths[1]:
1289
renames.append(paths)
1291
for old_name, new_name in renames:
1292
self.outf.write("%s => %s\n" % (old_name, new_name))
1558
self.add_cleanup(tree.lock_read().unlock)
1559
new_inv = tree.inventory
1560
old_tree = tree.basis_tree()
1561
self.add_cleanup(old_tree.lock_read().unlock)
1562
old_inv = old_tree.inventory
1564
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1565
for f, paths, c, v, p, n, k, e in iterator:
1566
if paths[0] == paths[1]:
1570
renames.append(paths)
1572
for old_name, new_name in renames:
1573
self.outf.write("%s => %s\n" % (old_name, new_name))
1299
1576
class cmd_update(Command):
1300
"""Update a tree to have the latest code committed to its branch.
1302
This will perform a merge into the working tree, and may generate
1303
conflicts. If you have any local changes, you will still
1304
need to commit them after the update for the update to be complete.
1306
If you want to discard your local changes, you can just do a
1307
'bzr revert' instead of 'bzr commit' after the update.
1577
__doc__ = """Update a working tree to a new revision.
1579
This will perform a merge of the destination revision (the tip of the
1580
branch, or the specified revision) into the working tree, and then make
1581
that revision the basis revision for the working tree.
1583
You can use this to visit an older revision, or to update a working tree
1584
that is out of date from its branch.
1586
If there are any uncommitted changes in the tree, they will be carried
1587
across and remain as uncommitted changes after the update. To discard
1588
these changes, use 'bzr revert'. The uncommitted changes may conflict
1589
with the changes brought in by the change in basis revision.
1591
If the tree's branch is bound to a master branch, bzr will also update
1592
the branch from the master.
1594
You cannot update just a single file or directory, because each Bazaar
1595
working tree has just a single basis revision. If you want to restore a
1596
file that has been removed locally, use 'bzr revert' instead of 'bzr
1597
update'. If you want to restore a file to its state in a previous
1598
revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
1599
out the old content of that file to a new location.
1601
The 'dir' argument, if given, must be the location of the root of a
1602
working tree to update. By default, the working tree that contains the
1603
current working directory is used.
1310
1606
_see_also = ['pull', 'working-trees', 'status-flags']
1311
1607
takes_args = ['dir?']
1608
takes_options = ['revision',
1610
help="Show base revision text in conflicts."),
1312
1612
aliases = ['up']
1314
def run(self, dir='.'):
1315
tree = WorkingTree.open_containing(dir)[0]
1614
def run(self, dir=None, revision=None, show_base=None):
1615
if revision is not None and len(revision) != 1:
1616
raise errors.BzrCommandError(gettext(
1617
"bzr update --revision takes exactly one revision"))
1619
tree = WorkingTree.open_containing('.')[0]
1621
tree, relpath = WorkingTree.open_containing(dir)
1624
raise errors.BzrCommandError(gettext(
1625
"bzr update can only update a whole tree, "
1626
"not a file or subdirectory"))
1627
branch = tree.branch
1316
1628
possible_transports = []
1317
master = tree.branch.get_master_branch(
1629
master = branch.get_master_branch(
1318
1630
possible_transports=possible_transports)
1319
1631
if master is not None:
1632
branch_location = master.base
1320
1633
tree.lock_write()
1635
branch_location = tree.branch.base
1322
1636
tree.lock_tree_write()
1637
self.add_cleanup(tree.unlock)
1638
# get rid of the final '/' and be ready for display
1639
branch_location = urlutils.unescape_for_display(
1640
branch_location.rstrip('/'),
1642
existing_pending_merges = tree.get_parent_ids()[1:]
1646
# may need to fetch data into a heavyweight checkout
1647
# XXX: this may take some time, maybe we should display a
1649
old_tip = branch.update(possible_transports)
1650
if revision is not None:
1651
revision_id = revision[0].as_revision_id(branch)
1653
revision_id = branch.last_revision()
1654
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1655
revno = branch.revision_id_to_dotted_revno(revision_id)
1656
note(gettext("Tree is up to date at revision {0} of branch {1}"
1657
).format('.'.join(map(str, revno)), branch_location))
1659
view_info = _get_view_info_for_change_reporter(tree)
1660
change_reporter = delta._ChangeReporter(
1661
unversioned_filter=tree.is_ignored,
1662
view_info=view_info)
1324
existing_pending_merges = tree.get_parent_ids()[1:]
1325
last_rev = _mod_revision.ensure_null(tree.last_revision())
1326
if last_rev == _mod_revision.ensure_null(
1327
tree.branch.last_revision()):
1328
# may be up to date, check master too.
1329
if master is None or last_rev == _mod_revision.ensure_null(
1330
master.last_revision()):
1331
revno = tree.branch.revision_id_to_revno(last_rev)
1332
note("Tree is up to date at revision %d." % (revno,))
1334
view_info = _get_view_info_for_change_reporter(tree)
1335
1664
conflicts = tree.update(
1336
delta._ChangeReporter(unversioned_filter=tree.is_ignored,
1337
view_info=view_info), possible_transports=possible_transports)
1338
revno = tree.branch.revision_id_to_revno(
1339
_mod_revision.ensure_null(tree.last_revision()))
1340
note('Updated to revision %d.' % (revno,))
1341
if tree.get_parent_ids()[1:] != existing_pending_merges:
1342
note('Your local commits will now show as pending merges with '
1343
"'bzr status', and can be committed with 'bzr commit'.")
1666
possible_transports=possible_transports,
1667
revision=revision_id,
1669
show_base=show_base)
1670
except errors.NoSuchRevision, e:
1671
raise errors.BzrCommandError(gettext(
1672
"branch has no revision %s\n"
1673
"bzr update --revision only works"
1674
" for a revision in the branch history")
1676
revno = tree.branch.revision_id_to_dotted_revno(
1677
_mod_revision.ensure_null(tree.last_revision()))
1678
note(gettext('Updated to revision {0} of branch {1}').format(
1679
'.'.join(map(str, revno)), branch_location))
1680
parent_ids = tree.get_parent_ids()
1681
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1682
note(gettext('Your local commits will now show as pending merges with '
1683
"'bzr status', and can be committed with 'bzr commit'."))
1352
1690
class cmd_info(Command):
1353
"""Show information about a working tree, branch or repository.
1691
__doc__ = """Show information about a working tree, branch or repository.
1355
1693
This command will show all known locations and formats associated to the
1356
1694
tree, branch or repository.
1407
1746
RegistryOption.from_kwargs('file-deletion-strategy',
1408
1747
'The file deletion mode to be used.',
1409
1748
title='Deletion Strategy', value_switches=True, enum_switch=False,
1410
safe='Only delete files if they can be'
1411
' safely recovered (default).',
1412
keep="Don't delete any files.",
1749
safe='Backup changed files (default).',
1750
keep='Delete from bzr but leave the working copy.',
1751
no_backup='Don\'t backup changed files.',
1413
1752
force='Delete all the specified files, even if they can not be '
1414
'recovered and even if they are non-empty directories.')]
1753
'recovered and even if they are non-empty directories. '
1754
'(deprecated, use no-backup)')]
1415
1755
aliases = ['rm', 'del']
1416
1756
encoding_type = 'replace'
1418
1758
def run(self, file_list, verbose=False, new=False,
1419
1759
file_deletion_strategy='safe'):
1420
tree, file_list = tree_files(file_list)
1760
if file_deletion_strategy == 'force':
1761
note(gettext("(The --force option is deprecated, rather use --no-backup "
1763
file_deletion_strategy = 'no-backup'
1765
tree, file_list = WorkingTree.open_containing_paths(file_list)
1422
1767
if file_list is not None:
1423
1768
file_list = [f for f in file_list]
1427
# Heuristics should probably all move into tree.remove_smart or
1430
added = tree.changes_from(tree.basis_tree(),
1431
specific_files=file_list).added
1432
file_list = sorted([f[0] for f in added], reverse=True)
1433
if len(file_list) == 0:
1434
raise errors.BzrCommandError('No matching files.')
1435
elif file_list is None:
1436
# missing files show up in iter_changes(basis) as
1437
# versioned-with-no-kind.
1439
for change in tree.iter_changes(tree.basis_tree()):
1440
# Find paths in the working tree that have no kind:
1441
if change[1][1] is not None and change[6][1] is None:
1442
missing.append(change[1][1])
1443
file_list = sorted(missing, reverse=True)
1444
file_deletion_strategy = 'keep'
1445
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1446
keep_files=file_deletion_strategy=='keep',
1447
force=file_deletion_strategy=='force')
1770
self.add_cleanup(tree.lock_write().unlock)
1771
# Heuristics should probably all move into tree.remove_smart or
1774
added = tree.changes_from(tree.basis_tree(),
1775
specific_files=file_list).added
1776
file_list = sorted([f[0] for f in added], reverse=True)
1777
if len(file_list) == 0:
1778
raise errors.BzrCommandError(gettext('No matching files.'))
1779
elif file_list is None:
1780
# missing files show up in iter_changes(basis) as
1781
# versioned-with-no-kind.
1783
for change in tree.iter_changes(tree.basis_tree()):
1784
# Find paths in the working tree that have no kind:
1785
if change[1][1] is not None and change[6][1] is None:
1786
missing.append(change[1][1])
1787
file_list = sorted(missing, reverse=True)
1788
file_deletion_strategy = 'keep'
1789
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1790
keep_files=file_deletion_strategy=='keep',
1791
force=(file_deletion_strategy=='no-backup'))
1452
1794
class cmd_file_id(Command):
1453
"""Print file_id of a particular file or directory.
1795
__doc__ = """Print file_id of a particular file or directory.
1455
1797
The file_id is assigned when the file is first added and remains the
1456
1798
same through all revisions where the file exists, even when it is
1823
2232
elif ':' in prefix:
1824
2233
old_label, new_label = prefix.split(":")
1826
raise errors.BzrCommandError(
2235
raise errors.BzrCommandError(gettext(
1827
2236
'--prefix expects two values separated by a colon'
1828
' (eg "old/:new/")')
2237
' (eg "old/:new/")'))
1830
2239
if revision and len(revision) > 2:
1831
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1832
' one or two revision specifiers')
1834
old_tree, new_tree, specific_files, extra_trees = \
1835
_get_trees_to_diff(file_list, revision, old, new,
2240
raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2241
' one or two revision specifiers'))
2243
if using is not None and format is not None:
2244
raise errors.BzrCommandError(gettext(
2245
'{0} and {1} are mutually exclusive').format(
2246
'--using', '--format'))
2248
(old_tree, new_tree,
2249
old_branch, new_branch,
2250
specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2251
file_list, revision, old, new, self.add_cleanup, apply_view=True)
2252
# GNU diff on Windows uses ANSI encoding for filenames
2253
path_encoding = osutils.get_diff_header_encoding()
1837
2254
return show_diff_trees(old_tree, new_tree, sys.stdout,
1838
2255
specific_files=specific_files,
1839
2256
external_diff_options=diff_options,
1840
2257
old_label=old_label, new_label=new_label,
1841
extra_trees=extra_trees, using=using)
2258
extra_trees=extra_trees,
2259
path_encoding=path_encoding,
1844
2264
class cmd_deleted(Command):
1845
"""List files deleted in the working tree.
2265
__doc__ = """List files deleted in the working tree.
1847
2267
# TODO: Show files deleted since a previous revision, or
1848
2268
# between two revisions.
1851
2271
# level of effort but possibly much less IO. (Or possibly not,
1852
2272
# if the directories are very large...)
1853
2273
_see_also = ['status', 'ls']
1854
takes_options = ['show-ids']
2274
takes_options = ['directory', 'show-ids']
1856
2276
@display_command
1857
def run(self, show_ids=False):
1858
tree = WorkingTree.open_containing(u'.')[0]
1861
old = tree.basis_tree()
1864
for path, ie in old.inventory.iter_entries():
1865
if not tree.has_id(ie.file_id):
1866
self.outf.write(path)
1868
self.outf.write(' ')
1869
self.outf.write(ie.file_id)
1870
self.outf.write('\n')
2277
def run(self, show_ids=False, directory=u'.'):
2278
tree = WorkingTree.open_containing(directory)[0]
2279
self.add_cleanup(tree.lock_read().unlock)
2280
old = tree.basis_tree()
2281
self.add_cleanup(old.lock_read().unlock)
2282
for path, ie in old.inventory.iter_entries():
2283
if not tree.has_id(ie.file_id):
2284
self.outf.write(path)
2286
self.outf.write(' ')
2287
self.outf.write(ie.file_id)
2288
self.outf.write('\n')
1877
2291
class cmd_modified(Command):
1878
"""List files modified in working tree.
2292
__doc__ = """List files modified in working tree.
1882
2296
_see_also = ['status', 'ls']
1885
help='Write an ascii NUL (\\0) separator '
1886
'between files rather than a newline.')
2297
takes_options = ['directory', 'null']
1889
2299
@display_command
1890
def run(self, null=False):
1891
tree = WorkingTree.open_containing(u'.')[0]
2300
def run(self, null=False, directory=u'.'):
2301
tree = WorkingTree.open_containing(directory)[0]
2302
self.add_cleanup(tree.lock_read().unlock)
1892
2303
td = tree.changes_from(tree.basis_tree())
1893
2305
for path, id, kind, text_modified, meta_modified in td.modified:
1895
2307
self.outf.write(path + '\0')
2241
2719
diff_type = 'full'
2245
# Build the log formatter
2246
if log_format is None:
2247
log_format = log.log_formatter_registry.get_default(b)
2248
lf = log_format(show_ids=show_ids, to_file=self.outf,
2249
show_timezone=timezone,
2250
delta_format=get_verbosity_level(),
2252
show_advice=levels is None)
2254
# Choose the algorithm for doing the logging. It's annoying
2255
# having multiple code paths like this but necessary until
2256
# the underlying repository format is faster at generating
2257
# deltas or can provide everything we need from the indices.
2258
# The default algorithm - match-using-deltas - works for
2259
# multiple files and directories and is faster for small
2260
# amounts of history (200 revisions say). However, it's too
2261
# slow for logging a single file in a repository with deep
2262
# history, i.e. > 10K revisions. In the spirit of "do no
2263
# evil when adding features", we continue to use the
2264
# original algorithm - per-file-graph - for the "single
2265
# file that isn't a directory without showing a delta" case.
2266
partial_history = revision and b.repository._format.supports_chks
2267
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2268
or delta_type or partial_history)
2270
# Build the LogRequest and execute it
2271
if len(file_ids) == 0:
2273
rqst = make_log_request_dict(
2274
direction=direction, specific_fileids=file_ids,
2275
start_revision=rev1, end_revision=rev2, limit=limit,
2276
message_search=message, delta_type=delta_type,
2277
diff_type=diff_type, _match_using_deltas=match_using_deltas)
2278
Logger(b, rqst).show(lf)
2721
# Build the log formatter
2722
if log_format is None:
2723
log_format = log.log_formatter_registry.get_default(b)
2724
# Make a non-encoding output to include the diffs - bug 328007
2725
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2726
lf = log_format(show_ids=show_ids, to_file=self.outf,
2727
to_exact_file=unencoded_output,
2728
show_timezone=timezone,
2729
delta_format=get_verbosity_level(),
2731
show_advice=levels is None,
2732
author_list_handler=authors)
2734
# Choose the algorithm for doing the logging. It's annoying
2735
# having multiple code paths like this but necessary until
2736
# the underlying repository format is faster at generating
2737
# deltas or can provide everything we need from the indices.
2738
# The default algorithm - match-using-deltas - works for
2739
# multiple files and directories and is faster for small
2740
# amounts of history (200 revisions say). However, it's too
2741
# slow for logging a single file in a repository with deep
2742
# history, i.e. > 10K revisions. In the spirit of "do no
2743
# evil when adding features", we continue to use the
2744
# original algorithm - per-file-graph - for the "single
2745
# file that isn't a directory without showing a delta" case.
2746
partial_history = revision and b.repository._format.supports_chks
2747
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2748
or delta_type or partial_history)
2752
match_dict[''] = match
2754
match_dict['message'] = match_message
2756
match_dict['committer'] = match_committer
2758
match_dict['author'] = match_author
2760
match_dict['bugs'] = match_bugs
2762
# Build the LogRequest and execute it
2763
if len(file_ids) == 0:
2765
rqst = make_log_request_dict(
2766
direction=direction, specific_fileids=file_ids,
2767
start_revision=rev1, end_revision=rev2, limit=limit,
2768
message_search=message, delta_type=delta_type,
2769
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2770
exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2771
signature=signatures, omit_merges=omit_merges,
2773
Logger(b, rqst).show(lf)
2283
2776
def _get_revision_range(revisionspec_list, branch, command_name):
2366
2865
help='Recurse into subdirectories.'),
2367
2866
Option('from-root',
2368
2867
help='Print paths relative to the root of the branch.'),
2369
Option('unknown', help='Print unknown files.'),
2868
Option('unknown', short_name='u',
2869
help='Print unknown files.'),
2370
2870
Option('versioned', help='Print versioned files.',
2371
2871
short_name='V'),
2372
Option('ignored', help='Print ignored files.'),
2374
help='Write an ascii NUL (\\0) separator '
2375
'between files rather than a newline.'),
2872
Option('ignored', short_name='i',
2873
help='Print ignored files.'),
2874
Option('kind', short_name='k',
2377
2875
help='List entries of a particular kind: file, directory, symlink.',
2381
2881
@display_command
2382
2882
def run(self, revision=None, verbose=False,
2383
2883
recursive=False, from_root=False,
2384
2884
unknown=False, versioned=False, ignored=False,
2385
null=False, kind=None, show_ids=False, path=None):
2885
null=False, kind=None, show_ids=False, path=None, directory=None):
2387
2887
if kind and kind not in ('file', 'directory', 'symlink'):
2388
raise errors.BzrCommandError('invalid kind specified')
2888
raise errors.BzrCommandError(gettext('invalid kind specified'))
2390
2890
if verbose and null:
2391
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2891
raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
2392
2892
all = not (unknown or versioned or ignored)
2394
2894
selection = {'I':ignored, '?':unknown, 'V':versioned}
2396
2896
if path is None:
2401
raise errors.BzrCommandError('cannot specify both --from-root'
2900
raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2405
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2903
tree, branch, relpath = \
2904
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2906
# Calculate the prefix to use
2910
prefix = relpath + '/'
2911
elif fs_path != '.' and not fs_path.endswith('/'):
2912
prefix = fs_path + '/'
2411
2914
if revision is not None or tree is None:
2412
2915
tree = _get_one_revision_tree('ls', revision, branch=branch)
2418
2921
apply_view = True
2419
2922
view_str = views.view_display_str(view_files)
2420
note("Ignoring files outside view. View is %s" % view_str)
2424
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2425
if fp.startswith(relpath):
2426
rp = fp[len(relpath):]
2427
fp = osutils.pathjoin(prefix, rp)
2428
if not recursive and '/' in rp:
2430
if not all and not selection[fc]:
2432
if kind is not None and fkind != kind:
2436
views.check_path_in_view(tree, fp)
2437
except errors.FileOutsideView:
2439
kindch = entry.kind_character()
2440
outstring = fp + kindch
2441
ui.ui_factory.clear_term()
2443
outstring = '%-8s %s' % (fc, outstring)
2444
if show_ids and fid is not None:
2445
outstring = "%-50s %s" % (outstring, fid)
2446
self.outf.write(outstring + '\n')
2448
self.outf.write(fp + '\0')
2451
self.outf.write(fid)
2452
self.outf.write('\0')
2460
self.outf.write('%-50s %s\n' % (outstring, my_id))
2462
self.outf.write(outstring + '\n')
2923
note(gettext("Ignoring files outside view. View is %s") % view_str)
2925
self.add_cleanup(tree.lock_read().unlock)
2926
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2927
from_dir=relpath, recursive=recursive):
2928
# Apply additional masking
2929
if not all and not selection[fc]:
2931
if kind is not None and fkind != kind:
2936
fullpath = osutils.pathjoin(relpath, fp)
2939
views.check_path_in_view(tree, fullpath)
2940
except errors.FileOutsideView:
2945
fp = osutils.pathjoin(prefix, fp)
2946
kindch = entry.kind_character()
2947
outstring = fp + kindch
2948
ui.ui_factory.clear_term()
2950
outstring = '%-8s %s' % (fc, outstring)
2951
if show_ids and fid is not None:
2952
outstring = "%-50s %s" % (outstring, fid)
2953
self.outf.write(outstring + '\n')
2955
self.outf.write(fp + '\0')
2958
self.outf.write(fid)
2959
self.outf.write('\0')
2967
self.outf.write('%-50s %s\n' % (outstring, my_id))
2969
self.outf.write(outstring + '\n')
2467
2972
class cmd_unknowns(Command):
2468
"""List unknown files.
2973
__doc__ = """List unknown files.
2472
2977
_see_also = ['ls']
2978
takes_options = ['directory']
2474
2980
@display_command
2476
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2981
def run(self, directory=u'.'):
2982
for f in WorkingTree.open_containing(directory)[0].unknowns():
2477
2983
self.outf.write(osutils.quotefn(f) + '\n')
2480
2986
class cmd_ignore(Command):
2481
"""Ignore specified files or patterns.
2987
__doc__ = """Ignore specified files or patterns.
2483
2989
See ``bzr help patterns`` for details on the syntax of patterns.
2991
If a .bzrignore file does not exist, the ignore command
2992
will create one and add the specified files or patterns to the newly
2993
created file. The ignore command will also automatically add the
2994
.bzrignore file to be versioned. Creating a .bzrignore file without
2995
the use of the ignore command will require an explicit add command.
2485
2997
To remove patterns from the ignore list, edit the .bzrignore file.
2486
2998
After adding, editing or deleting that file either indirectly by
2487
2999
using this command or directly by using an editor, be sure to commit
2490
Note: ignore patterns containing shell wildcards must be quoted from
3002
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
3003
the global ignore file can be found in the application data directory as
3004
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
3005
Global ignores are not touched by this command. The global ignore file
3006
can be edited directly using an editor.
3008
Patterns prefixed with '!' are exceptions to ignore patterns and take
3009
precedence over regular ignores. Such exceptions are used to specify
3010
files that should be versioned which would otherwise be ignored.
3012
Patterns prefixed with '!!' act as regular ignore patterns, but have
3013
precedence over the '!' exception patterns.
3017
* Ignore patterns containing shell wildcards must be quoted from
3020
* Ignore patterns starting with "#" act as comments in the ignore file.
3021
To ignore patterns that begin with that character, use the "RE:" prefix.
2494
3024
Ignore the top level Makefile::
2496
3026
bzr ignore ./Makefile
2498
Ignore class files in all directories::
3028
Ignore .class files in all directories...::
2500
3030
bzr ignore "*.class"
3032
...but do not ignore "special.class"::
3034
bzr ignore "!special.class"
3036
Ignore files whose name begins with the "#" character::
2502
3040
Ignore .o files under the lib directory::
2504
3042
bzr ignore "lib/**/*.o"
2510
3048
Ignore everything but the "debian" toplevel directory::
2512
3050
bzr ignore "RE:(?!debian/).*"
3052
Ignore everything except the "local" toplevel directory,
3053
but always ignore autosave files ending in ~, even under local/::
3056
bzr ignore "!./local"
2515
3060
_see_also = ['status', 'ignored', 'patterns']
2516
3061
takes_args = ['name_pattern*']
2518
Option('old-default-rules',
2519
help='Write out the ignore rules bzr < 0.9 always used.')
3062
takes_options = ['directory',
3063
Option('default-rules',
3064
help='Display the default ignore rules that bzr uses.')
2522
def run(self, name_pattern_list=None, old_default_rules=None):
3067
def run(self, name_pattern_list=None, default_rules=None,
2523
3069
from bzrlib import ignores
2524
if old_default_rules is not None:
2525
# dump the rules and exit
2526
for pattern in ignores.OLD_DEFAULTS:
3070
if default_rules is not None:
3071
# dump the default rules and exit
3072
for pattern in ignores.USER_DEFAULTS:
3073
self.outf.write("%s\n" % pattern)
2529
3075
if not name_pattern_list:
2530
raise errors.BzrCommandError("ignore requires at least one "
2531
"NAME_PATTERN or --old-default-rules")
3076
raise errors.BzrCommandError(gettext("ignore requires at least one "
3077
"NAME_PATTERN or --default-rules."))
2532
3078
name_pattern_list = [globbing.normalize_pattern(p)
2533
3079
for p in name_pattern_list]
3081
bad_patterns_count = 0
3082
for p in name_pattern_list:
3083
if not globbing.Globster.is_pattern_valid(p):
3084
bad_patterns_count += 1
3085
bad_patterns += ('\n %s' % p)
3087
msg = (ngettext('Invalid ignore pattern found. %s',
3088
'Invalid ignore patterns found. %s',
3089
bad_patterns_count) % bad_patterns)
3090
ui.ui_factory.show_error(msg)
3091
raise errors.InvalidPattern('')
2534
3092
for name_pattern in name_pattern_list:
2535
3093
if (name_pattern[0] == '/' or
2536
3094
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2537
raise errors.BzrCommandError(
2538
"NAME_PATTERN should not be an absolute path")
2539
tree, relpath = WorkingTree.open_containing(u'.')
3095
raise errors.BzrCommandError(gettext(
3096
"NAME_PATTERN should not be an absolute path"))
3097
tree, relpath = WorkingTree.open_containing(directory)
2540
3098
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2541
3099
ignored = globbing.Globster(name_pattern_list)
3101
self.add_cleanup(tree.lock_read().unlock)
2544
3102
for entry in tree.list_files():
2546
3104
if id is not None:
2547
3105
filename = entry[0]
2548
3106
if ignored.match(filename):
2549
matches.append(filename.encode('utf-8'))
3107
matches.append(filename)
2551
3108
if len(matches) > 0:
2552
print "Warning: the following files are version controlled and" \
2553
" match your ignore pattern:\n%s" \
2554
"\nThese files will continue to be version controlled" \
2555
" unless you 'bzr remove' them." % ("\n".join(matches),)
3109
self.outf.write(gettext("Warning: the following files are version "
3110
"controlled and match your ignore pattern:\n%s"
3111
"\nThese files will continue to be version controlled"
3112
" unless you 'bzr remove' them.\n") % ("\n".join(matches),))
2558
3115
class cmd_ignored(Command):
2559
"""List ignored files and the patterns that matched them.
3116
__doc__ = """List ignored files and the patterns that matched them.
2561
3118
List all the ignored files and the ignore pattern that caused the file to
2569
3126
encoding_type = 'replace'
2570
3127
_see_also = ['ignore', 'ls']
3128
takes_options = ['directory']
2572
3130
@display_command
2574
tree = WorkingTree.open_containing(u'.')[0]
2577
for path, file_class, kind, file_id, entry in tree.list_files():
2578
if file_class != 'I':
2580
## XXX: Slightly inefficient since this was already calculated
2581
pat = tree.is_ignored(path)
2582
self.outf.write('%-50s %s\n' % (path, pat))
3131
def run(self, directory=u'.'):
3132
tree = WorkingTree.open_containing(directory)[0]
3133
self.add_cleanup(tree.lock_read().unlock)
3134
for path, file_class, kind, file_id, entry in tree.list_files():
3135
if file_class != 'I':
3137
## XXX: Slightly inefficient since this was already calculated
3138
pat = tree.is_ignored(path)
3139
self.outf.write('%-50s %s\n' % (path, pat))
2587
3142
class cmd_lookup_revision(Command):
2588
"""Lookup the revision-id from a revision-number
3143
__doc__ = """Lookup the revision-id from a revision-number
2591
3146
bzr lookup-revision 33
2594
3149
takes_args = ['revno']
3150
takes_options = ['directory']
2596
3152
@display_command
2597
def run(self, revno):
3153
def run(self, revno, directory=u'.'):
2599
3155
revno = int(revno)
2600
3156
except ValueError:
2601
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2603
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3157
raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3159
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3160
self.outf.write("%s\n" % revid)
2606
3163
class cmd_export(Command):
2607
"""Export current or past revision to a destination directory or archive.
3164
__doc__ = """Export current or past revision to a destination directory or archive.
2609
3166
If no revision is specified this exports the last committed revision.
2644
3202
help="Name of the root directory inside the exported file."),
3203
Option('per-file-timestamps',
3204
help='Set modification time of files to that of the last '
3205
'revision in which it was changed.'),
3206
Option('uncommitted',
3207
help='Export the working tree contents rather than that of the '
2646
3210
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2647
root=None, filters=False):
3211
root=None, filters=False, per_file_timestamps=False, uncommitted=False,
2648
3213
from bzrlib.export import export
2650
3215
if branch_or_subdir is None:
2651
tree = WorkingTree.open_containing(u'.')[0]
3216
branch_or_subdir = directory
3218
(tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
3220
if tree is not None:
3221
self.add_cleanup(tree.lock_read().unlock)
3225
raise errors.BzrCommandError(
3226
gettext("--uncommitted requires a working tree"))
2655
b, subdir = Branch.open_containing(branch_or_subdir)
2658
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
3229
export_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2660
export(rev_tree, dest, format, root, subdir, filtered=filters)
3231
export(export_tree, dest, format, root, subdir, filtered=filters,
3232
per_file_timestamps=per_file_timestamps)
2661
3233
except errors.NoSuchExportFormat, e:
2662
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3234
raise errors.BzrCommandError(
3235
gettext('Unsupported export format: %s') % e.format)
2665
3238
class cmd_cat(Command):
2666
"""Write the contents of a file as of a given revision to standard output.
3239
__doc__ = """Write the contents of a file as of a given revision to standard output.
2668
3241
If no revision is nominated, the last revision is used.
2684
3257
@display_command
2685
3258
def run(self, filename, revision=None, name_from_revision=False,
3259
filters=False, directory=None):
2687
3260
if revision is not None and len(revision) != 1:
2688
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2689
" one revision specifier")
3261
raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3262
" one revision specifier"))
2690
3263
tree, branch, relpath = \
2691
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2694
return self._run(tree, branch, relpath, filename, revision,
2695
name_from_revision, filters)
3264
_open_directory_or_containing_tree_or_branch(filename, directory)
3265
self.add_cleanup(branch.lock_read().unlock)
3266
return self._run(tree, branch, relpath, filename, revision,
3267
name_from_revision, filters)
2699
3269
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2701
3271
if tree is None:
2702
3272
tree = b.basis_tree()
2703
3273
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3274
self.add_cleanup(rev_tree.lock_read().unlock)
2705
3276
old_file_id = rev_tree.path2id(relpath)
3278
# TODO: Split out this code to something that generically finds the
3279
# best id for a path across one or more trees; it's like
3280
# find_ids_across_trees but restricted to find just one. -- mbp
2707
3282
if name_from_revision:
2708
3283
# Try in revision if requested
2709
3284
if old_file_id is None:
2710
raise errors.BzrCommandError(
2711
"%r is not present in revision %s" % (
3285
raise errors.BzrCommandError(gettext(
3286
"{0!r} is not present in revision {1}").format(
2712
3287
filename, rev_tree.get_revision_id()))
2714
content = rev_tree.get_file_text(old_file_id)
3289
actual_file_id = old_file_id
2716
3291
cur_file_id = tree.path2id(relpath)
2718
if cur_file_id is not None:
2719
# Then try with the actual file id
2721
content = rev_tree.get_file_text(cur_file_id)
2723
except errors.NoSuchId:
2724
# The actual file id didn't exist at that time
2726
if not found and old_file_id is not None:
2727
# Finally try with the old file id
2728
content = rev_tree.get_file_text(old_file_id)
2731
# Can't be found anywhere
2732
raise errors.BzrCommandError(
2733
"%r is not present in revision %s" % (
3292
if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3293
actual_file_id = cur_file_id
3294
elif old_file_id is not None:
3295
actual_file_id = old_file_id
3297
raise errors.BzrCommandError(gettext(
3298
"{0!r} is not present in revision {1}").format(
2734
3299
filename, rev_tree.get_revision_id()))
2736
from bzrlib.filters import (
2737
ContentFilterContext,
2738
filtered_output_bytes,
2740
filters = rev_tree._content_filter_stack(relpath)
2741
chunks = content.splitlines(True)
2742
content = filtered_output_bytes(chunks, filters,
2743
ContentFilterContext(relpath, rev_tree))
2744
self.outf.writelines(content)
3301
from bzrlib.filter_tree import ContentFilterTree
3302
filter_tree = ContentFilterTree(rev_tree,
3303
rev_tree._content_filter_stack)
3304
content = filter_tree.get_file_text(actual_file_id)
2746
self.outf.write(content)
3306
content = rev_tree.get_file_text(actual_file_id)
3308
self.outf.write(content)
2749
3311
class cmd_local_time_offset(Command):
2750
"""Show the offset in seconds from GMT to local time."""
3312
__doc__ = """Show the offset in seconds from GMT to local time."""
2752
3314
@display_command
2754
print osutils.local_time_offset()
3316
self.outf.write("%s\n" % osutils.local_time_offset())
2758
3320
class cmd_commit(Command):
2759
"""Commit changes into a new revision.
3321
__doc__ = """Commit changes into a new revision.
2761
3323
An explanatory message needs to be given for each commit. This is
2762
3324
often done by using the --message option (getting the message from the
2867
3407
"the master branch until a normal commit "
2868
3408
"is performed."
2871
help='When no message is supplied, show the diff along'
2872
' with the status summary in the message editor.'),
3410
Option('show-diff', short_name='p',
3411
help='When no message is supplied, show the diff along'
3412
' with the status summary in the message editor.'),
3414
help='When committing to a foreign version control '
3415
'system do not push data that can not be natively '
2874
3418
aliases = ['ci', 'checkin']
2876
3420
def _iter_bug_fix_urls(self, fixes, branch):
3421
default_bugtracker = None
2877
3422
# Configure the properties for bug fixing attributes.
2878
3423
for fixed_bug in fixes:
2879
3424
tokens = fixed_bug.split(':')
2880
if len(tokens) != 2:
2881
raise errors.BzrCommandError(
3425
if len(tokens) == 1:
3426
if default_bugtracker is None:
3427
branch_config = branch.get_config()
3428
default_bugtracker = branch_config.get_user_option(
3430
if default_bugtracker is None:
3431
raise errors.BzrCommandError(gettext(
3432
"No tracker specified for bug %s. Use the form "
3433
"'tracker:id' or specify a default bug tracker "
3434
"using the `bugtracker` option.\nSee "
3435
"\"bzr help bugs\" for more information on this "
3436
"feature. Commit refused.") % fixed_bug)
3437
tag = default_bugtracker
3439
elif len(tokens) != 2:
3440
raise errors.BzrCommandError(gettext(
2882
3441
"Invalid bug %s. Must be in the form of 'tracker:id'. "
2883
3442
"See \"bzr help bugs\" for more information on this "
2884
"feature.\nCommit refused." % fixed_bug)
2885
tag, bug_id = tokens
3443
"feature.\nCommit refused.") % fixed_bug)
3445
tag, bug_id = tokens
2887
3447
yield bugtracker.get_bug_url(tag, branch, bug_id)
2888
3448
except errors.UnknownBugTrackerAbbreviation:
2889
raise errors.BzrCommandError(
2890
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3449
raise errors.BzrCommandError(gettext(
3450
'Unrecognized bug %s. Commit refused.') % fixed_bug)
2891
3451
except errors.MalformedBugIdentifier, e:
2892
raise errors.BzrCommandError(
2893
"%s\nCommit refused." % (str(e),))
3452
raise errors.BzrCommandError(gettext(
3453
"%s\nCommit refused.") % (str(e),))
2895
3455
def run(self, message=None, file=None, verbose=False, selected_list=None,
2896
3456
unchanged=False, strict=False, local=False, fixes=None,
2897
author=None, show_diff=False, exclude=None):
3457
author=None, show_diff=False, exclude=None, commit_time=None,
2898
3459
from bzrlib.errors import (
2899
3460
PointlessCommit,
2900
3461
ConflictsInTree,
2931
3495
if local and not tree.branch.get_bound_location():
2932
3496
raise errors.LocalRequiresBoundBranch()
3498
if message is not None:
3500
file_exists = osutils.lexists(message)
3501
except UnicodeError:
3502
# The commit message contains unicode characters that can't be
3503
# represented in the filesystem encoding, so that can't be a
3508
'The commit message is a file name: "%(f)s".\n'
3509
'(use --file "%(f)s" to take commit message from that file)'
3511
ui.ui_factory.show_warning(warning_msg)
3513
message = message.replace('\r\n', '\n')
3514
message = message.replace('\r', '\n')
3516
raise errors.BzrCommandError(gettext(
3517
"please specify either --message or --file"))
2934
3519
def get_message(commit_obj):
2935
3520
"""Callback to get commit message"""
2936
my_message = message
2937
if my_message is None and not file:
2938
t = make_commit_message_template_encoded(tree,
3524
my_message = f.read().decode(osutils.get_user_encoding())
3527
elif message is not None:
3528
my_message = message
3530
# No message supplied: make one up.
3531
# text is the status of the tree
3532
text = make_commit_message_template_encoded(tree,
2939
3533
selected_list, diff=show_diff,
2940
3534
output_encoding=osutils.get_user_encoding())
2941
start_message = generate_commit_message_template(commit_obj)
2942
my_message = edit_commit_message_encoded(t,
2943
start_message=start_message)
2944
if my_message is None:
2945
raise errors.BzrCommandError("please specify a commit"
2946
" message with either --message or --file")
2947
elif my_message and file:
2948
raise errors.BzrCommandError(
2949
"please specify either --message or --file")
2951
my_message = codecs.open(file, 'rt',
2952
osutils.get_user_encoding()).read()
2953
if my_message == "":
2954
raise errors.BzrCommandError("empty commit message specified")
3535
# start_message is the template generated from hooks
3536
# XXX: Warning - looks like hooks return unicode,
3537
# make_commit_message_template_encoded returns user encoding.
3538
# We probably want to be using edit_commit_message instead to
3540
my_message = set_commit_message(commit_obj)
3541
if my_message is None:
3542
start_message = generate_commit_message_template(commit_obj)
3543
my_message = edit_commit_message_encoded(text,
3544
start_message=start_message)
3545
if my_message is None:
3546
raise errors.BzrCommandError(gettext("please specify a commit"
3547
" message with either --message or --file"))
3548
if my_message == "":
3549
raise errors.BzrCommandError(gettext("Empty commit message specified."
3550
" Please specify a commit message with either"
3551
" --message or --file or leave a blank message"
3552
" with --message \"\"."))
2955
3553
return my_message
3555
# The API permits a commit with a filter of [] to mean 'select nothing'
3556
# but the command line should not do that.
3557
if not selected_list:
3558
selected_list = None
2958
3560
tree.commit(message_callback=get_message,
2959
3561
specific_files=selected_list,
2960
3562
allow_pointless=unchanged, strict=strict, local=local,
2961
3563
reporter=None, verbose=verbose, revprops=properties,
2963
exclude=safe_relpath_files(tree, exclude))
3564
authors=author, timestamp=commit_stamp,
3566
exclude=tree.safe_relpath_files(exclude),
2964
3568
except PointlessCommit:
2965
# FIXME: This should really happen before the file is read in;
2966
# perhaps prepare the commit; get the message; then actually commit
2967
raise errors.BzrCommandError("No changes to commit."
2968
" Use --unchanged to commit anyhow.")
3569
raise errors.BzrCommandError(gettext("No changes to commit."
3570
" Please 'bzr add' the files you want to commit, or use"
3571
" --unchanged to force an empty commit."))
2969
3572
except ConflictsInTree:
2970
raise errors.BzrCommandError('Conflicts detected in working '
3573
raise errors.BzrCommandError(gettext('Conflicts detected in working '
2971
3574
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2973
3576
except StrictCommitFailed:
2974
raise errors.BzrCommandError("Commit refused because there are"
2975
" unknown files in the working tree.")
3577
raise errors.BzrCommandError(gettext("Commit refused because there are"
3578
" unknown files in the working tree."))
2976
3579
except errors.BoundBranchOutOfDate, e:
2977
raise errors.BzrCommandError(str(e) + "\n"
2978
'To commit to master branch, run update and then commit.\n'
2979
'You can also pass --local to commit to continue working '
3580
e.extra_help = (gettext("\n"
3581
'To commit to master branch, run update and then commit.\n'
3582
'You can also pass --local to commit to continue working '
2983
3587
class cmd_check(Command):
2984
"""Validate working tree structure, branch consistency and repository history.
3588
__doc__ = """Validate working tree structure, branch consistency and repository history.
2986
3590
This command checks various invariants about branch and repository storage
2987
3591
to detect data corruption or bzr bugs.
3044
3657
class cmd_upgrade(Command):
3045
"""Upgrade branch storage to current format.
3047
The check command or bzr developers may sometimes advise you to run
3048
this command. When the default format has changed you may also be warned
3049
during other operations to upgrade.
3658
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3660
When the default format has changed after a major new release of
3661
Bazaar, you may be informed during certain operations that you
3662
should upgrade. Upgrading to a newer format may improve performance
3663
or make new features available. It may however limit interoperability
3664
with older repositories or with older versions of Bazaar.
3666
If you wish to upgrade to a particular format rather than the
3667
current default, that can be specified using the --format option.
3668
As a consequence, you can use the upgrade command this way to
3669
"downgrade" to an earlier format, though some conversions are
3670
a one way process (e.g. changing from the 1.x default to the
3671
2.x default) so downgrading is not always possible.
3673
A backup.bzr.~#~ directory is created at the start of the conversion
3674
process (where # is a number). By default, this is left there on
3675
completion. If the conversion fails, delete the new .bzr directory
3676
and rename this one back in its place. Use the --clean option to ask
3677
for the backup.bzr directory to be removed on successful conversion.
3678
Alternatively, you can delete it by hand if everything looks good
3681
If the location given is a shared repository, dependent branches
3682
are also converted provided the repository converts successfully.
3683
If the conversion of a branch fails, remaining branches are still
3686
For more information on upgrades, see the Bazaar Upgrade Guide,
3687
http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
3052
_see_also = ['check']
3690
_see_also = ['check', 'reconcile', 'formats']
3053
3691
takes_args = ['url?']
3054
3692
takes_options = [
3055
RegistryOption('format',
3056
help='Upgrade to a specific format. See "bzr help'
3057
' formats" for details.',
3058
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3059
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3060
value_switches=True, title='Branch format'),
3693
RegistryOption('format',
3694
help='Upgrade to a specific format. See "bzr help'
3695
' formats" for details.',
3696
lazy_registry=('bzrlib.controldir', 'format_registry'),
3697
converter=lambda name: controldir.format_registry.make_bzrdir(name),
3698
value_switches=True, title='Branch format'),
3700
help='Remove the backup.bzr directory if successful.'),
3702
help="Show what would be done, but don't actually do anything."),
3063
def run(self, url='.', format=None):
3705
def run(self, url='.', format=None, clean=False, dry_run=False):
3064
3706
from bzrlib.upgrade import upgrade
3065
upgrade(url, format)
3707
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3709
if len(exceptions) == 1:
3710
# Compatibility with historical behavior
3068
3716
class cmd_whoami(Command):
3069
"""Show or set bzr user id.
3717
__doc__ = """Show or set bzr user id.
3072
3720
Show the email of the current user::
3087
3736
encoding_type = 'replace'
3089
3738
@display_command
3090
def run(self, email=False, branch=False, name=None):
3739
def run(self, email=False, branch=False, name=None, directory=None):
3091
3740
if name is None:
3092
# use branch if we're inside one; otherwise global config
3094
c = Branch.open_containing('.')[0].get_config()
3095
except errors.NotBranchError:
3096
c = config.GlobalConfig()
3741
if directory is None:
3742
# use branch if we're inside one; otherwise global config
3744
c = Branch.open_containing(u'.')[0].get_config_stack()
3745
except errors.NotBranchError:
3746
c = _mod_config.GlobalStack()
3748
c = Branch.open(directory).get_config_stack()
3749
identity = c.get('email')
3098
self.outf.write(c.user_email() + '\n')
3751
self.outf.write(_mod_config.extract_email_address(identity)
3100
self.outf.write(c.username() + '\n')
3754
self.outf.write(identity + '\n')
3758
raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3103
3761
# display a warning if an email address isn't included in the given name.
3105
config.extract_email_address(name)
3763
_mod_config.extract_email_address(name)
3106
3764
except errors.NoEmailInUsername, e:
3107
3765
warning('"%s" does not seem to contain an email address. '
3108
3766
'This is allowed, but not recommended.', name)
3110
3768
# use global config unless --branch given
3112
c = Branch.open_containing('.')[0].get_config()
3770
if directory is None:
3771
c = Branch.open_containing(u'.')[0].get_config_stack()
3773
c = Branch.open(directory).get_config_stack()
3114
c = config.GlobalConfig()
3115
c.set_user_option('email', name)
3775
c = _mod_config.GlobalStack()
3776
c.set('email', name)
3118
3779
class cmd_nick(Command):
3119
"""Print or set the branch nickname.
3780
__doc__ = """Print or set the branch nickname.
3121
3782
If unset, the tree root directory name is used as the nickname.
3122
3783
To print the current nickname, execute with no argument.
3350
4024
from bzrlib.tests import SubUnitBzrRunner
3351
4025
except ImportError:
3352
raise errors.BzrCommandError("subunit not available. subunit "
3353
"needs to be installed to use --subunit.")
4026
raise errors.BzrCommandError(gettext("subunit not available. subunit "
4027
"needs to be installed to use --subunit."))
3354
4028
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
4029
# On Windows, disable automatic conversion of '\n' to '\r\n' in
4030
# stdout, which would corrupt the subunit stream.
4031
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
4032
# following code can be deleted when it's sufficiently deployed
4033
# -- vila/mgz 20100514
4034
if (sys.platform == "win32"
4035
and getattr(sys.stdout, 'fileno', None) is not None):
4037
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3356
4039
self.additional_selftest_args.setdefault(
3357
4040
'suite_decorators', []).append(parallel)
3359
test_suite_factory = benchmarks.test_suite
3360
# Unless user explicitly asks for quiet, be verbose in benchmarks
3361
verbose = not is_quiet()
3362
# TODO: should possibly lock the history file...
3363
benchfile = open(".perf_history", "at", buffering=1)
4042
raise errors.BzrCommandError(gettext(
4043
"--benchmark is no longer supported from bzr 2.2; "
4044
"use bzr-usertest instead"))
4045
test_suite_factory = None
4047
exclude_pattern = None
3365
test_suite_factory = None
4049
exclude_pattern = '(' + '|'.join(exclude) + ')'
4051
self._disable_fsync()
4052
selftest_kwargs = {"verbose": verbose,
4054
"stop_on_failure": one,
4055
"transport": transport,
4056
"test_suite_factory": test_suite_factory,
4057
"lsprof_timed": lsprof_timed,
4058
"lsprof_tests": lsprof_tests,
4059
"matching_tests_first": first,
4060
"list_only": list_only,
4061
"random_seed": randomize,
4062
"exclude_pattern": exclude_pattern,
4064
"load_list": load_list,
4065
"debug_flags": debugflag,
4066
"starting_with": starting_with
4068
selftest_kwargs.update(self.additional_selftest_args)
4070
# Make deprecation warnings visible, unless -Werror is set
4071
cleanup = symbol_versioning.activate_deprecation_warnings(
3368
selftest_kwargs = {"verbose": verbose,
3370
"stop_on_failure": one,
3371
"transport": transport,
3372
"test_suite_factory": test_suite_factory,
3373
"lsprof_timed": lsprof_timed,
3374
"bench_history": benchfile,
3375
"matching_tests_first": first,
3376
"list_only": list_only,
3377
"random_seed": randomize,
3378
"exclude_pattern": exclude,
3380
"load_list": load_list,
3381
"debug_flags": debugflag,
3382
"starting_with": starting_with
3384
selftest_kwargs.update(self.additional_selftest_args)
3385
result = selftest(**selftest_kwargs)
4074
result = tests.selftest(**selftest_kwargs)
3387
if benchfile is not None:
3389
4077
return int(not result)
4079
def _disable_fsync(self):
4080
"""Change the 'os' functionality to not synchronize."""
4081
self._orig_fsync = getattr(os, 'fsync', None)
4082
if self._orig_fsync is not None:
4083
os.fsync = lambda filedes: None
4084
self._orig_fdatasync = getattr(os, 'fdatasync', None)
4085
if self._orig_fdatasync is not None:
4086
os.fdatasync = lambda filedes: None
3392
4089
class cmd_version(Command):
3393
"""Show version of bzr."""
4090
__doc__ = """Show version of bzr."""
3395
4092
encoding_type = 'replace'
3396
4093
takes_options = [
3430
4127
branch1 = Branch.open_containing(branch)[0]
3431
4128
branch2 = Branch.open_containing(other)[0]
3436
last1 = ensure_null(branch1.last_revision())
3437
last2 = ensure_null(branch2.last_revision())
3439
graph = branch1.repository.get_graph(branch2.repository)
3440
base_rev_id = graph.find_unique_lca(last1, last2)
3442
print 'merge base is revision %s' % base_rev_id
4129
self.add_cleanup(branch1.lock_read().unlock)
4130
self.add_cleanup(branch2.lock_read().unlock)
4131
last1 = ensure_null(branch1.last_revision())
4132
last2 = ensure_null(branch2.last_revision())
4134
graph = branch1.repository.get_graph(branch2.repository)
4135
base_rev_id = graph.find_unique_lca(last1, last2)
4137
self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
3449
4140
class cmd_merge(Command):
3450
"""Perform a three-way merge.
4141
__doc__ = """Perform a three-way merge.
3452
4143
The source of the merge can be specified either in the form of a branch,
3453
4144
or in the form of a path to a file containing a merge directive generated
3454
4145
with bzr send. If neither is specified, the default is the upstream branch
3455
or the branch most recently merged using --remember.
3457
When merging a branch, by default the tip will be merged. To pick a different
3458
revision, pass --revision. If you specify two values, the first will be used as
3459
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3460
available revisions, like this is commonly referred to as "cherrypicking".
3462
Revision numbers are always relative to the branch being merged.
3464
By default, bzr will try to merge in all new work from the other
3465
branch, automatically determining an appropriate base. If this
3466
fails, you may need to give an explicit base.
4146
or the branch most recently merged using --remember. The source of the
4147
merge may also be specified in the form of a path to a file in another
4148
branch: in this case, only the modifications to that file are merged into
4149
the current working tree.
4151
When merging from a branch, by default bzr will try to merge in all new
4152
work from the other branch, automatically determining an appropriate base
4153
revision. If this fails, you may need to give an explicit base.
4155
To pick a different ending revision, pass "--revision OTHER". bzr will
4156
try to merge in all new work up to and including revision OTHER.
4158
If you specify two values, "--revision BASE..OTHER", only revisions BASE
4159
through OTHER, excluding BASE but including OTHER, will be merged. If this
4160
causes some revisions to be skipped, i.e. if the destination branch does
4161
not already contain revision BASE, such a merge is commonly referred to as
4162
a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4163
cherrypicks. The changes look like a normal commit, and the history of the
4164
changes from the other branch is not stored in the commit.
4166
Revision numbers are always relative to the source branch.
3468
4168
Merge will do its best to combine the changes in two branches, but there
3469
4169
are some kinds of problems only a human can fix. When it encounters those,
3470
4170
it will mark a conflict. A conflict means that you need to fix something,
3471
before you should commit.
4171
before you can commit.
3473
4173
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
3475
If there is no default branch set, the first merge will set it. After
3476
that, you can omit the branch to use the default. To change the
3477
default, use --remember. The value will only be saved if the remote
3478
location can be accessed.
4175
If there is no default branch set, the first merge will set it (use
4176
--no-remember to avoid setting it). After that, you can omit the branch
4177
to use the default. To change the default, use --remember. The value will
4178
only be saved if the remote location can be accessed.
3480
4180
The results of the merge are placed into the destination working
3481
4181
directory, where they can be reviewed (with bzr diff), tested, and then
3482
4182
committed to record the result of the merge.
3484
4184
merge refuses to run if there are any uncommitted changes, unless
4185
--force is given. If --force is given, then the changes from the source
4186
will be merged with the current working tree, including any uncommitted
4187
changes in the tree. The --force option can also be used to create a
4188
merge revision which has more than two parents.
4190
If one would like to merge changes from the working tree of the other
4191
branch without merging any committed revisions, the --uncommitted option
4194
To select only some changes to merge, use "merge -i", which will prompt
4195
you to apply each diff hunk and file change, similar to "shelve".
3488
To merge the latest revision from bzr.dev::
4198
To merge all new revisions from bzr.dev::
3490
4200
bzr merge ../bzr.dev
3545
4263
allow_pending = True
3546
4264
verified = 'inapplicable'
3547
4266
tree = WorkingTree.open_containing(directory)[0]
4267
if tree.branch.revno() == 0:
4268
raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4269
'https://bugs.launchpad.net/bzr/+bug/308562'))
3549
# die as quickly as possible if there are uncommitted changes
3551
4272
basis_tree = tree.revision_tree(tree.last_revision())
3552
4273
except errors.NoSuchRevision:
3553
4274
basis_tree = tree.basis_tree()
4276
# die as quickly as possible if there are uncommitted changes
3555
changes = tree.changes_from(basis_tree)
3556
if changes.has_changed():
4278
if tree.has_changes():
3557
4279
raise errors.UncommittedChanges(tree)
3559
4281
view_info = _get_view_info_for_change_reporter(tree)
3560
4282
change_reporter = delta._ChangeReporter(
3561
4283
unversioned_filter=tree.is_ignored, view_info=view_info)
3564
pb = ui.ui_factory.nested_progress_bar()
3565
cleanups.append(pb.finished)
3567
cleanups.append(tree.unlock)
3568
if location is not None:
3570
mergeable = bundle.read_mergeable_from_url(location,
3571
possible_transports=possible_transports)
3572
except errors.NotABundle:
3576
raise errors.BzrCommandError('Cannot use --uncommitted'
3577
' with bundles or merge directives.')
3579
if revision is not None:
3580
raise errors.BzrCommandError(
3581
'Cannot use -r with merge directives or bundles')
3582
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3585
if merger is None and uncommitted:
3586
if revision is not None and len(revision) > 0:
3587
raise errors.BzrCommandError('Cannot use --uncommitted and'
3588
' --revision at the same time.')
3589
location = self._select_branch_location(tree, location)[0]
3590
other_tree, other_path = WorkingTree.open_containing(location)
3591
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3593
allow_pending = False
3594
if other_path != '':
3595
merger.interesting_files = [other_path]
3598
merger, allow_pending = self._get_merger_from_branch(tree,
3599
location, revision, remember, possible_transports, pb)
3601
merger.merge_type = merge_type
3602
merger.reprocess = reprocess
3603
merger.show_base = show_base
3604
self.sanity_check_merger(merger)
3605
if (merger.base_rev_id == merger.other_rev_id and
3606
merger.other_rev_id is not None):
3607
note('Nothing to do.')
4284
pb = ui.ui_factory.nested_progress_bar()
4285
self.add_cleanup(pb.finished)
4286
self.add_cleanup(tree.lock_write().unlock)
4287
if location is not None:
4289
mergeable = bundle.read_mergeable_from_url(location,
4290
possible_transports=possible_transports)
4291
except errors.NotABundle:
4295
raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4296
' with bundles or merge directives.'))
4298
if revision is not None:
4299
raise errors.BzrCommandError(gettext(
4300
'Cannot use -r with merge directives or bundles'))
4301
merger, verified = _mod_merge.Merger.from_mergeable(tree,
4304
if merger is None and uncommitted:
4305
if revision is not None and len(revision) > 0:
4306
raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4307
' --revision at the same time.'))
4308
merger = self.get_merger_from_uncommitted(tree, location, None)
4309
allow_pending = False
4312
merger, allow_pending = self._get_merger_from_branch(tree,
4313
location, revision, remember, possible_transports, None)
4315
merger.merge_type = merge_type
4316
merger.reprocess = reprocess
4317
merger.show_base = show_base
4318
self.sanity_check_merger(merger)
4319
if (merger.base_rev_id == merger.other_rev_id and
4320
merger.other_rev_id is not None):
4321
# check if location is a nonexistent file (and not a branch) to
4322
# disambiguate the 'Nothing to do'
4323
if merger.interesting_files:
4324
if not merger.other_tree.has_filename(
4325
merger.interesting_files[0]):
4326
note(gettext("merger: ") + str(merger))
4327
raise errors.PathsDoNotExist([location])
4328
note(gettext('Nothing to do.'))
4330
if pull and not preview:
4331
if merger.interesting_files is not None:
4332
raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4333
if (merger.base_rev_id == tree.last_revision()):
4334
result = tree.pull(merger.other_branch, False,
4335
merger.other_rev_id)
4336
result.report(self.outf)
3610
if merger.interesting_files is not None:
3611
raise errors.BzrCommandError('Cannot pull individual files')
3612
if (merger.base_rev_id == tree.last_revision()):
3613
result = tree.pull(merger.other_branch, False,
3614
merger.other_rev_id)
3615
result.report(self.outf)
3617
merger.check_basis(False)
3619
return self._do_preview(merger)
3621
return self._do_merge(merger, change_reporter, allow_pending,
3624
for cleanup in reversed(cleanups):
4338
if merger.this_basis is None:
4339
raise errors.BzrCommandError(gettext(
4340
"This branch has no commits."
4341
" (perhaps you would prefer 'bzr pull')"))
4343
return self._do_preview(merger)
4345
return self._do_interactive(merger)
4347
return self._do_merge(merger, change_reporter, allow_pending,
4350
def _get_preview(self, merger):
4351
tree_merger = merger.make_merger()
4352
tt = tree_merger.make_preview_transform()
4353
self.add_cleanup(tt.finalize)
4354
result_tree = tt.get_preview_tree()
3627
4357
def _do_preview(self, merger):
3628
4358
from bzrlib.diff import show_diff_trees
3629
tree_merger = merger.make_merger()
3630
tt = tree_merger.make_preview_transform()
3632
result_tree = tt.get_preview_tree()
3633
show_diff_trees(merger.this_tree, result_tree, self.outf,
3634
old_label='', new_label='')
4359
result_tree = self._get_preview(merger)
4360
path_encoding = osutils.get_diff_header_encoding()
4361
show_diff_trees(merger.this_tree, result_tree, self.outf,
4362
old_label='', new_label='',
4363
path_encoding=path_encoding)
3638
4365
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3639
4366
merger.change_reporter = change_reporter
3792
4559
def run(self, file_list=None, merge_type=None, show_base=False,
3793
4560
reprocess=False):
4561
from bzrlib.conflicts import restore
3794
4562
if merge_type is None:
3795
4563
merge_type = _mod_merge.Merge3Merger
3796
tree, file_list = tree_files(file_list)
3799
parents = tree.get_parent_ids()
3800
if len(parents) != 2:
3801
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3802
" merges. Not cherrypicking or"
3804
repository = tree.branch.repository
3805
interesting_ids = None
3807
conflicts = tree.conflicts()
3808
if file_list is not None:
3809
interesting_ids = set()
3810
for filename in file_list:
3811
file_id = tree.path2id(filename)
3813
raise errors.NotVersionedError(filename)
3814
interesting_ids.add(file_id)
3815
if tree.kind(file_id) != "directory":
4564
tree, file_list = WorkingTree.open_containing_paths(file_list)
4565
self.add_cleanup(tree.lock_write().unlock)
4566
parents = tree.get_parent_ids()
4567
if len(parents) != 2:
4568
raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
4569
" merges. Not cherrypicking or"
4571
repository = tree.branch.repository
4572
interesting_ids = None
4574
conflicts = tree.conflicts()
4575
if file_list is not None:
4576
interesting_ids = set()
4577
for filename in file_list:
4578
file_id = tree.path2id(filename)
4580
raise errors.NotVersionedError(filename)
4581
interesting_ids.add(file_id)
4582
if tree.kind(file_id) != "directory":
3818
for name, ie in tree.inventory.iter_entries(file_id):
3819
interesting_ids.add(ie.file_id)
3820
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3822
# Remerge only supports resolving contents conflicts
3823
allowed_conflicts = ('text conflict', 'contents conflict')
3824
restore_files = [c.path for c in conflicts
3825
if c.typestring in allowed_conflicts]
3826
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3827
tree.set_conflicts(ConflictList(new_conflicts))
3828
if file_list is not None:
3829
restore_files = file_list
3830
for filename in restore_files:
3832
restore(tree.abspath(filename))
3833
except errors.NotConflicted:
3835
# Disable pending merges, because the file texts we are remerging
3836
# have not had those merges performed. If we use the wrong parents
3837
# list, we imply that the working tree text has seen and rejected
3838
# all the changes from the other tree, when in fact those changes
3839
# have not yet been seen.
3840
pb = ui.ui_factory.nested_progress_bar()
3841
tree.set_parent_ids(parents[:1])
4585
for name, ie in tree.inventory.iter_entries(file_id):
4586
interesting_ids.add(ie.file_id)
4587
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4589
# Remerge only supports resolving contents conflicts
4590
allowed_conflicts = ('text conflict', 'contents conflict')
4591
restore_files = [c.path for c in conflicts
4592
if c.typestring in allowed_conflicts]
4593
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4594
tree.set_conflicts(ConflictList(new_conflicts))
4595
if file_list is not None:
4596
restore_files = file_list
4597
for filename in restore_files:
3843
merger = _mod_merge.Merger.from_revision_ids(pb,
3845
merger.interesting_ids = interesting_ids
3846
merger.merge_type = merge_type
3847
merger.show_base = show_base
3848
merger.reprocess = reprocess
3849
conflicts = merger.do_merge()
3851
tree.set_parent_ids(parents)
4599
restore(tree.abspath(filename))
4600
except errors.NotConflicted:
4602
# Disable pending merges, because the file texts we are remerging
4603
# have not had those merges performed. If we use the wrong parents
4604
# list, we imply that the working tree text has seen and rejected
4605
# all the changes from the other tree, when in fact those changes
4606
# have not yet been seen.
4607
tree.set_parent_ids(parents[:1])
4609
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4610
merger.interesting_ids = interesting_ids
4611
merger.merge_type = merge_type
4612
merger.show_base = show_base
4613
merger.reprocess = reprocess
4614
conflicts = merger.do_merge()
4616
tree.set_parent_ids(parents)
3855
4617
if conflicts > 0:
3879
4642
name. If you name a directory, all the contents of that directory will be
3882
Any files that have been newly added since that revision will be deleted,
3883
with a backup kept if appropriate. Directories containing unknown files
3884
will not be deleted.
4645
If you have newly added files since the target revision, they will be
4646
removed. If the files to be removed have been changed, backups will be
4647
created as above. Directories containing unknown files will not be
3886
The working tree contains a list of pending merged revisions, which will
3887
be included as parents in the next commit. Normally, revert clears that
3888
list as well as reverting the files. If any files are specified, revert
3889
leaves the pending merge list alone and reverts only the files. Use "bzr
3890
revert ." in the tree root to revert all files but keep the merge record,
3891
and "bzr revert --forget-merges" to clear the pending merge list without
4650
The working tree contains a list of revisions that have been merged but
4651
not yet committed. These revisions will be included as additional parents
4652
of the next commit. Normally, using revert clears that list as well as
4653
reverting the files. If any files are specified, revert leaves the list
4654
of uncommitted merges alone and reverts only the files. Use ``bzr revert
4655
.`` in the tree root to revert all files but keep the recorded merges,
4656
and ``bzr revert --forget-merges`` to clear the pending merge list without
3892
4657
reverting any files.
4659
Using "bzr revert --forget-merges", it is possible to apply all of the
4660
changes from a branch in a single revision. To do this, perform the merge
4661
as desired. Then doing revert with the "--forget-merges" option will keep
4662
the content of the tree as it was, but it will clear the list of pending
4663
merges. The next commit will then contain all of the changes that are
4664
present in the other branch, but without any other parent revisions.
4665
Because this technique forgets where these changes originated, it may
4666
cause additional conflicts on later merges involving the same source and
3895
_see_also = ['cat', 'export']
4670
_see_also = ['cat', 'export', 'merge', 'shelve']
3896
4671
takes_options = [
3898
4673
Option('no-backup', "Do not save backups of reverted files."),
4072
4868
_get_revision_range(revision,
4073
4869
remote_branch, self.name()))
4075
local_branch.lock_read()
4077
remote_branch.lock_read()
4079
local_extra, remote_extra = find_unmerged(
4080
local_branch, remote_branch, restrict,
4081
backward=not reverse,
4082
include_merges=include_merges,
4083
local_revid_range=local_revid_range,
4084
remote_revid_range=remote_revid_range)
4086
if log_format is None:
4087
registry = log.log_formatter_registry
4088
log_format = registry.get_default(local_branch)
4089
lf = log_format(to_file=self.outf,
4091
show_timezone='original')
4094
if local_extra and not theirs_only:
4095
message("You have %d extra revision(s):\n" %
4097
for revision in iter_log_revisions(local_extra,
4098
local_branch.repository,
4100
lf.log_revision(revision)
4101
printed_local = True
4104
printed_local = False
4106
if remote_extra and not mine_only:
4107
if printed_local is True:
4109
message("You are missing %d revision(s):\n" %
4111
for revision in iter_log_revisions(remote_extra,
4112
remote_branch.repository,
4114
lf.log_revision(revision)
4117
if mine_only and not local_extra:
4118
# We checked local, and found nothing extra
4119
message('This branch is up to date.\n')
4120
elif theirs_only and not remote_extra:
4121
# We checked remote, and found nothing extra
4122
message('Other branch is up to date.\n')
4123
elif not (mine_only or theirs_only or local_extra or
4125
# We checked both branches, and neither one had extra
4127
message("Branches are up to date.\n")
4129
remote_branch.unlock()
4131
local_branch.unlock()
4871
local_extra, remote_extra = find_unmerged(
4872
local_branch, remote_branch, restrict,
4873
backward=not reverse,
4874
include_merged=include_merged,
4875
local_revid_range=local_revid_range,
4876
remote_revid_range=remote_revid_range)
4878
if log_format is None:
4879
registry = log.log_formatter_registry
4880
log_format = registry.get_default(local_branch)
4881
lf = log_format(to_file=self.outf,
4883
show_timezone='original')
4886
if local_extra and not theirs_only:
4887
message(ngettext("You have %d extra revision:\n",
4888
"You have %d extra revisions:\n",
4891
for revision in iter_log_revisions(local_extra,
4892
local_branch.repository,
4894
lf.log_revision(revision)
4895
printed_local = True
4898
printed_local = False
4900
if remote_extra and not mine_only:
4901
if printed_local is True:
4903
message(ngettext("You are missing %d revision:\n",
4904
"You are missing %d revisions:\n",
4905
len(remote_extra)) %
4907
for revision in iter_log_revisions(remote_extra,
4908
remote_branch.repository,
4910
lf.log_revision(revision)
4913
if mine_only and not local_extra:
4914
# We checked local, and found nothing extra
4915
message(gettext('This branch has no new revisions.\n'))
4916
elif theirs_only and not remote_extra:
4917
# We checked remote, and found nothing extra
4918
message(gettext('Other branch has no new revisions.\n'))
4919
elif not (mine_only or theirs_only or local_extra or
4921
# We checked both branches, and neither one had extra
4923
message(gettext("Branches are up to date.\n"))
4132
4925
if not status_code and parent is None and other_branch is not None:
4133
local_branch.lock_write()
4135
# handle race conditions - a parent might be set while we run.
4136
if local_branch.get_parent() is None:
4137
local_branch.set_parent(remote_branch.base)
4139
local_branch.unlock()
4926
self.add_cleanup(local_branch.lock_write().unlock)
4927
# handle race conditions - a parent might be set while we run.
4928
if local_branch.get_parent() is None:
4929
local_branch.set_parent(remote_branch.base)
4140
4930
return status_code
4143
4933
class cmd_pack(Command):
4144
"""Compress the data within a repository."""
4934
__doc__ = """Compress the data within a repository.
4936
This operation compresses the data within a bazaar repository. As
4937
bazaar supports automatic packing of repository, this operation is
4938
normally not required to be done manually.
4940
During the pack operation, bazaar takes a backup of existing repository
4941
data, i.e. pack files. This backup is eventually removed by bazaar
4942
automatically when it is safe to do so. To save disk space by removing
4943
the backed up pack files, the --clean-obsolete-packs option may be
4946
Warning: If you use --clean-obsolete-packs and your machine crashes
4947
during or immediately after repacking, you may be left with a state
4948
where the deletion has been written to disk but the new packs have not
4949
been. In this case the repository may be unusable.
4146
4952
_see_also = ['repositories']
4147
4953
takes_args = ['branch_or_repo?']
4955
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4149
def run(self, branch_or_repo='.'):
4150
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4958
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4959
dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
4152
4961
branch = dir.open_branch()
4153
4962
repository = branch.repository
4154
4963
except errors.NotBranchError:
4155
4964
repository = dir.open_repository()
4965
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4159
4968
class cmd_plugins(Command):
4160
"""List the installed plugins.
4969
__doc__ = """List the installed plugins.
4162
4971
This command displays the list of installed plugins including
4163
4972
version of plugin and a short description of each.
4253
5043
Option('long', help='Show commit date in annotations.'),
4257
5048
encoding_type = 'exact'
4259
5050
@display_command
4260
5051
def run(self, filename, all=False, long=False, revision=None,
4262
from bzrlib.annotate import annotate_file, annotate_file_tree
5052
show_ids=False, directory=None):
5053
from bzrlib.annotate import (
4263
5056
wt, branch, relpath = \
4264
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
5057
_open_directory_or_containing_tree_or_branch(filename, directory)
4265
5058
if wt is not None:
4270
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4272
file_id = wt.path2id(relpath)
4274
file_id = tree.path2id(relpath)
4276
raise errors.NotVersionedError(filename)
4277
file_version = tree.inventory[file_id].revision
4278
if wt is not None and revision is None:
4279
# If there is a tree and we're not annotating historical
4280
# versions, annotate the working tree's content.
4281
annotate_file_tree(wt, file_id, self.outf, long, all,
4284
annotate_file(branch, file_version, file_id, long, all, self.outf,
5059
self.add_cleanup(wt.lock_read().unlock)
5061
self.add_cleanup(branch.lock_read().unlock)
5062
tree = _get_one_revision_tree('annotate', revision, branch=branch)
5063
self.add_cleanup(tree.lock_read().unlock)
5064
if wt is not None and revision is None:
5065
file_id = wt.path2id(relpath)
5067
file_id = tree.path2id(relpath)
5069
raise errors.NotVersionedError(filename)
5070
if wt is not None and revision is None:
5071
# If there is a tree and we're not annotating historical
5072
# versions, annotate the working tree's content.
5073
annotate_file_tree(wt, file_id, self.outf, long, all,
5076
annotate_file_tree(tree, file_id, self.outf, long, all,
5077
show_ids=show_ids, branch=branch)
4293
5080
class cmd_re_sign(Command):
4294
"""Create a digital signature for an existing revision."""
5081
__doc__ = """Create a digital signature for an existing revision."""
4295
5082
# TODO be able to replace existing ones.
4297
5084
hidden = True # is this right ?
4298
5085
takes_args = ['revision_id*']
4299
takes_options = ['revision']
5086
takes_options = ['directory', 'revision']
4301
def run(self, revision_id_list=None, revision=None):
5088
def run(self, revision_id_list=None, revision=None, directory=u'.'):
4302
5089
if revision_id_list is not None and revision is not None:
4303
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
5090
raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
4304
5091
if revision_id_list is None and revision is None:
4305
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4306
b = WorkingTree.open_containing(u'.')[0].branch
4309
return self._run(b, revision_id_list, revision)
5092
raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
5093
b = WorkingTree.open_containing(directory)[0].branch
5094
self.add_cleanup(b.lock_write().unlock)
5095
return self._run(b, revision_id_list, revision)
4313
5097
def _run(self, b, revision_id_list, revision):
4314
5098
import bzrlib.gpg as gpg
4315
gpg_strategy = gpg.GPGStrategy(b.get_config())
5099
gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
4316
5100
if revision_id_list is not None:
4317
5101
b.repository.start_write_group()
4356
5140
b.repository.commit_write_group()
4358
raise errors.BzrCommandError('Please supply either one revision, or a range.')
5142
raise errors.BzrCommandError(gettext('Please supply either one revision, or a range.'))
4361
5145
class cmd_bind(Command):
4362
"""Convert the current branch into a checkout of the supplied branch.
5146
__doc__ = """Convert the current branch into a checkout of the supplied branch.
5147
If no branch is supplied, rebind to the last bound location.
4364
5149
Once converted into a checkout, commits must succeed on the master branch
4365
5150
before they will be applied to the local branch.
4367
5152
Bound branches use the nickname of its master branch unless it is set
4368
locally, in which case binding will update the the local nickname to be
5153
locally, in which case binding will update the local nickname to be
4369
5154
that of the master.
4372
5157
_see_also = ['checkouts', 'unbind']
4373
5158
takes_args = ['location?']
5159
takes_options = ['directory']
4376
def run(self, location=None):
4377
b, relpath = Branch.open_containing(u'.')
5161
def run(self, location=None, directory=u'.'):
5162
b, relpath = Branch.open_containing(directory)
4378
5163
if location is None:
4380
5165
location = b.get_old_bound_location()
4381
5166
except errors.UpgradeRequired:
4382
raise errors.BzrCommandError('No location supplied. '
4383
'This format does not remember old locations.')
5167
raise errors.BzrCommandError(gettext('No location supplied. '
5168
'This format does not remember old locations.'))
4385
5170
if location is None:
4386
raise errors.BzrCommandError('No location supplied and no '
4387
'previous location known')
5171
if b.get_bound_location() is not None:
5172
raise errors.BzrCommandError(gettext('Branch is already bound'))
5174
raise errors.BzrCommandError(gettext('No location supplied '
5175
'and no previous location known'))
4388
5176
b_other = Branch.open(location)
4390
5178
b.bind(b_other)
4391
5179
except errors.DivergedBranches:
4392
raise errors.BzrCommandError('These branches have diverged.'
4393
' Try merging, and then bind again.')
5180
raise errors.BzrCommandError(gettext('These branches have diverged.'
5181
' Try merging, and then bind again.'))
4394
5182
if b.get_config().has_explicit_nickname():
4395
5183
b.nick = b_other.nick
4398
5186
class cmd_unbind(Command):
4399
"""Convert the current checkout into a regular branch.
5187
__doc__ = """Convert the current checkout into a regular branch.
4401
5189
After unbinding, the local branch is considered independent and subsequent
4402
5190
commits will be local only.
4507
5291
end_revision=last_revno)
4510
print 'Dry-run, pretending to remove the above revisions.'
4512
val = raw_input('Press <enter> to continue')
5294
self.outf.write(gettext('Dry-run, pretending to remove'
5295
' the above revisions.\n'))
4514
print 'The above revision(s) will be removed.'
4516
val = raw_input('Are you sure [y/N]? ')
4517
if val.lower() not in ('y', 'yes'):
5297
self.outf.write(gettext('The above revision(s) will be removed.\n'))
5300
if not ui.ui_factory.confirm_action(
5301
gettext(u'Uncommit these revisions'),
5302
'bzrlib.builtins.uncommit',
5304
self.outf.write(gettext('Canceled\n'))
4521
5307
mutter('Uncommitting from {%s} to {%s}',
4522
5308
last_rev_id, rev_id)
4523
5309
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4524
revno=revno, local=local)
4525
note('You can restore the old tip by running:\n'
4526
' bzr pull . -r revid:%s', last_rev_id)
5310
revno=revno, local=local, keep_tags=keep_tags)
5311
self.outf.write(gettext('You can restore the old tip by running:\n'
5312
' bzr pull . -r revid:%s\n') % last_rev_id)
4529
5315
class cmd_break_lock(Command):
4530
"""Break a dead lock on a repository, branch or working directory.
5316
__doc__ = """Break a dead lock.
5318
This command breaks a lock on a repository, branch, working directory or
4532
5321
CAUTION: Locks should only be broken when you are sure that the process
4533
5322
holding the lock has been stopped.
4535
You can get information on what locks are open via the 'bzr info' command.
5324
You can get information on what locks are open via the 'bzr info
5325
[location]' command.
5329
bzr break-lock bzr+ssh://example.com/bzr/foo
5330
bzr break-lock --conf ~/.bazaar
4540
5333
takes_args = ['location?']
5336
help='LOCATION is the directory where the config lock is.'),
5338
help='Do not ask for confirmation before breaking the lock.'),
4542
def run(self, location=None, show=False):
5341
def run(self, location=None, config=False, force=False):
4543
5342
if location is None:
4544
5343
location = u'.'
4545
control, relpath = bzrdir.BzrDir.open_containing(location)
4547
control.break_lock()
4548
except NotImplementedError:
5345
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5347
{'bzrlib.lockdir.break': True})
5349
conf = _mod_config.LockableConfig(file_name=location)
5352
control, relpath = controldir.ControlDir.open_containing(location)
5354
control.break_lock()
5355
except NotImplementedError:
4552
5359
class cmd_wait_until_signalled(Command):
4553
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5360
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4555
5362
This just prints a line to signal when it is ready, then blocks on stdin.
4809
5635
directly from the merge directive, without retrieving data from a
4812
If --no-bundle is specified, then public_branch is needed (and must be
4813
up-to-date), so that the receiver can perform the merge using the
4814
public_branch. The public_branch is always included if known, so that
4815
people can check it later.
4817
The submit branch defaults to the parent, but can be overridden. Both
4818
submit branch and public branch will be remembered if supplied.
4820
If a public_branch is known for the submit_branch, that public submit
4821
branch is used in the merge instructions. This means that a local mirror
4822
can be used as your actual submit branch, once you have set public_branch
5638
`bzr send` creates a compact data set that, when applied using bzr
5639
merge, has the same effect as merging from the source branch.
5641
By default the merge directive is self-contained and can be applied to any
5642
branch containing submit_branch in its ancestory without needing access to
5645
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5646
revisions, but only a structured request to merge from the
5647
public_location. In that case the public_branch is needed and it must be
5648
up-to-date and accessible to the recipient. The public_branch is always
5649
included if known, so that people can check it later.
5651
The submit branch defaults to the parent of the source branch, but can be
5652
overridden. Both submit branch and public branch will be remembered in
5653
branch.conf the first time they are used for a particular branch. The
5654
source branch defaults to that containing the working directory, but can
5655
be changed using --from.
5657
Both the submit branch and the public branch follow the usual behavior with
5658
respect to --remember: If there is no default location set, the first send
5659
will set it (use --no-remember to avoid setting it). After that, you can
5660
omit the location to use the default. To change the default, use
5661
--remember. The value will only be saved if the location can be accessed.
5663
In order to calculate those changes, bzr must analyse the submit branch.
5664
Therefore it is most efficient for the submit branch to be a local mirror.
5665
If a public location is known for the submit_branch, that location is used
5666
in the merge directive.
5668
The default behaviour is to send the merge directive by mail, unless -o is
5669
given, in which case it is sent to a file.
4825
5671
Mail is sent using your preferred mail program. This should be transparent
4826
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
5672
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
4827
5673
If the preferred client can't be found (or used), your editor will be used.
4829
5675
To use a specific mail program, set the mail_client configuration option.
4830
5676
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4831
specific clients are "claws", "evolution", "kmail", "mutt", and
4832
"thunderbird"; generic options are "default", "editor", "emacsclient",
4833
"mapi", and "xdg-email". Plugins may also add supported clients.
5677
specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5678
Mail.app), "mutt", and "thunderbird"; generic options are "default",
5679
"editor", "emacsclient", "mapi", and "xdg-email". Plugins may also add
4835
5682
If mail is being sent, a to address is required. This can be supplied
4836
5683
either on the commandline, by setting the submit_to configuration
4866
5717
short_name='f',
4868
5719
Option('output', short_name='o',
4869
help='Write merge directive to this file; '
5720
help='Write merge directive to this file or directory; '
4870
5721
'use - for stdout.',
5724
help='Refuse to send if there are uncommitted changes in'
5725
' the working tree, --no-strict disables the check.'),
4872
5726
Option('mail-to', help='Mail the request to this address.',
4876
5730
Option('body', help='Body for the email.', type=unicode),
4877
5731
RegistryOption('format',
4878
help='Use the specified output format.',
4879
lazy_registry=('bzrlib.send', 'format_registry'))
5732
help='Use the specified output format.',
5733
lazy_registry=('bzrlib.send', 'format_registry')),
4882
5736
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4883
no_patch=False, revision=None, remember=False, output=None,
4884
format=None, mail_to=None, message=None, body=None, **kwargs):
5737
no_patch=False, revision=None, remember=None, output=None,
5738
format=None, mail_to=None, message=None, body=None,
5739
strict=None, **kwargs):
4885
5740
from bzrlib.send import send
4886
5741
return send(submit_branch, revision, public_branch, remember,
4887
format, no_bundle, no_patch, output,
4888
kwargs.get('from', '.'), mail_to, message, body,
5742
format, no_bundle, no_patch, output,
5743
kwargs.get('from', '.'), mail_to, message, body,
4892
5748
class cmd_bundle_revisions(cmd_send):
4893
"""Create a merge-directive for submitting changes.
5749
__doc__ = """Create a merge-directive for submitting changes.
4895
5751
A merge directive provides many things needed for requesting merges:
4975
5834
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4976
5835
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5837
If no tag name is specified it will be determined through the
5838
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5839
upstream releases by reading configure.ac. See ``bzr help hooks`` for
4979
5843
_see_also = ['commit', 'tags']
4980
takes_args = ['tag_name']
5844
takes_args = ['tag_name?']
4981
5845
takes_options = [
4982
5846
Option('delete',
4983
5847
help='Delete this tag rather than placing it.',
4986
help='Branch in which to place the tag.',
5849
custom_help('directory',
5850
help='Branch in which to place the tag.'),
4990
5851
Option('force',
4991
5852
help='Replace existing tags.',
4996
def run(self, tag_name,
5857
def run(self, tag_name=None,
5002
5863
branch, relpath = Branch.open_containing(directory)
5006
branch.tags.delete_tag(tag_name)
5007
self.outf.write('Deleted tag %s.\n' % tag_name)
5010
if len(revision) != 1:
5011
raise errors.BzrCommandError(
5012
"Tags can only be placed on a single revision, "
5014
revision_id = revision[0].as_revision_id(branch)
5016
revision_id = branch.last_revision()
5017
if (not force) and branch.tags.has_tag(tag_name):
5018
raise errors.TagAlreadyExists(tag_name)
5864
self.add_cleanup(branch.lock_write().unlock)
5866
if tag_name is None:
5867
raise errors.BzrCommandError(gettext("No tag specified to delete."))
5868
branch.tags.delete_tag(tag_name)
5869
note(gettext('Deleted tag %s.') % tag_name)
5872
if len(revision) != 1:
5873
raise errors.BzrCommandError(gettext(
5874
"Tags can only be placed on a single revision, "
5876
revision_id = revision[0].as_revision_id(branch)
5878
revision_id = branch.last_revision()
5879
if tag_name is None:
5880
tag_name = branch.automatic_tag_name(revision_id)
5881
if tag_name is None:
5882
raise errors.BzrCommandError(gettext(
5883
"Please specify a tag name."))
5885
existing_target = branch.tags.lookup_tag(tag_name)
5886
except errors.NoSuchTag:
5887
existing_target = None
5888
if not force and existing_target not in (None, revision_id):
5889
raise errors.TagAlreadyExists(tag_name)
5890
if existing_target == revision_id:
5891
note(gettext('Tag %s already exists for that revision.') % tag_name)
5019
5893
branch.tags.set_tag(tag_name, revision_id)
5020
self.outf.write('Created tag %s.\n' % tag_name)
5894
if existing_target is None:
5895
note(gettext('Created tag %s.') % tag_name)
5897
note(gettext('Updated tag %s.') % tag_name)
5025
5900
class cmd_tags(Command):
5901
__doc__ = """List tags.
5028
5903
This command shows a table of tag names and the revisions they reference.
5031
5906
_see_also = ['tag']
5032
5907
takes_options = [
5034
help='Branch whose tags should be displayed.',
5038
RegistryOption.from_kwargs('sort',
5908
custom_help('directory',
5909
help='Branch whose tags should be displayed.'),
5910
RegistryOption('sort',
5039
5911
'Sort tags by different criteria.', title='Sorting',
5040
alpha='Sort tags lexicographically (default).',
5041
time='Sort tags chronologically.',
5912
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
5047
5918
@display_command
5919
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5920
from bzrlib.tag import tag_sort_methods
5054
5921
branch, relpath = Branch.open_containing(directory)
5056
5923
tags = branch.tags.get_tag_dict().items()
5063
graph = branch.repository.get_graph()
5064
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5065
revid1, revid2 = rev1.rev_id, rev2.rev_id
5066
# only show revisions between revid1 and revid2 (inclusive)
5067
tags = [(tag, revid) for tag, revid in tags if
5068
graph.is_between(revid, revid1, revid2)]
5071
elif sort == 'time':
5073
for tag, revid in tags:
5075
revobj = branch.repository.get_revision(revid)
5076
except errors.NoSuchRevision:
5077
timestamp = sys.maxint # place them at the end
5079
timestamp = revobj.timestamp
5080
timestamps[revid] = timestamp
5081
tags.sort(key=lambda x: timestamps[x[1]])
5083
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5084
for index, (tag, revid) in enumerate(tags):
5086
revno = branch.revision_id_to_dotted_revno(revid)
5087
if isinstance(revno, tuple):
5088
revno = '.'.join(map(str, revno))
5089
except errors.NoSuchRevision:
5090
# Bad tag data/merges can lead to tagged revisions
5091
# which are not in this branch. Fail gracefully ...
5093
tags[index] = (tag, revno)
5927
self.add_cleanup(branch.lock_read().unlock)
5929
# Restrict to the specified range
5930
tags = self._tags_for_range(branch, revision)
5932
sort = tag_sort_methods.get()
5935
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5936
for index, (tag, revid) in enumerate(tags):
5938
revno = branch.revision_id_to_dotted_revno(revid)
5939
if isinstance(revno, tuple):
5940
revno = '.'.join(map(str, revno))
5941
except (errors.NoSuchRevision,
5942
errors.GhostRevisionsHaveNoRevno,
5943
errors.UnsupportedOperation):
5944
# Bad tag data/merges can lead to tagged revisions
5945
# which are not in this branch. Fail gracefully ...
5947
tags[index] = (tag, revno)
5096
5949
for tag, revspec in tags:
5097
5950
self.outf.write('%-20s %s\n' % (tag, revspec))
5952
def _tags_for_range(self, branch, revision):
5954
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5955
revid1, revid2 = rev1.rev_id, rev2.rev_id
5956
# _get_revision_range will always set revid2 if it's not specified.
5957
# If revid1 is None, it means we want to start from the branch
5958
# origin which is always a valid ancestor. If revid1 == revid2, the
5959
# ancestry check is useless.
5960
if revid1 and revid1 != revid2:
5961
# FIXME: We really want to use the same graph than
5962
# branch.iter_merge_sorted_revisions below, but this is not
5963
# easily available -- vila 2011-09-23
5964
if branch.repository.get_graph().is_ancestor(revid2, revid1):
5965
# We don't want to output anything in this case...
5967
# only show revisions between revid1 and revid2 (inclusive)
5968
tagged_revids = branch.tags.get_reverse_tag_dict()
5970
for r in branch.iter_merge_sorted_revisions(
5971
start_revision_id=revid2, stop_revision_id=revid1,
5972
stop_rule='include'):
5973
revid_tags = tagged_revids.get(r[0], None)
5975
found.extend([(tag, r[0]) for tag in revid_tags])
5100
5979
class cmd_reconfigure(Command):
5101
"""Reconfigure the type of a bzr directory.
5980
__doc__ = """Reconfigure the type of a bzr directory.
5103
5982
A target configuration must be specified.
5135
6026
Option('bind-to', help='Branch to bind checkout to.', type=str),
5136
6027
Option('force',
5137
help='Perform reconfiguration even if local changes'
6028
help='Perform reconfiguration even if local changes'
6030
Option('stacked-on',
6031
help='Reconfigure a branch to be stacked on another branch.',
6035
help='Reconfigure a branch to be unstacked. This '
6036
'may require copying substantial data into it.',
5141
def run(self, location=None, target_type=None, bind_to=None, force=False):
5142
directory = bzrdir.BzrDir.open(location)
5143
if target_type is None:
5144
raise errors.BzrCommandError('No target configuration specified')
5145
elif target_type == 'branch':
6040
def run(self, location=None, bind_to=None, force=False,
6041
tree_type=None, repository_type=None, repository_trees=None,
6042
stacked_on=None, unstacked=None):
6043
directory = controldir.ControlDir.open(location)
6044
if stacked_on and unstacked:
6045
raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
6046
elif stacked_on is not None:
6047
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
6049
reconfigure.ReconfigureUnstacked().apply(directory)
6050
# At the moment you can use --stacked-on and a different
6051
# reconfiguration shape at the same time; there seems no good reason
6053
if (tree_type is None and
6054
repository_type is None and
6055
repository_trees is None):
6056
if stacked_on or unstacked:
6059
raise errors.BzrCommandError(gettext('No target configuration '
6061
reconfiguration = None
6062
if tree_type == 'branch':
5146
6063
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5147
elif target_type == 'tree':
6064
elif tree_type == 'tree':
5148
6065
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5149
elif target_type == 'checkout':
6066
elif tree_type == 'checkout':
5150
6067
reconfiguration = reconfigure.Reconfigure.to_checkout(
5151
6068
directory, bind_to)
5152
elif target_type == 'lightweight-checkout':
6069
elif tree_type == 'lightweight-checkout':
5153
6070
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5154
6071
directory, bind_to)
5155
elif target_type == 'use-shared':
6073
reconfiguration.apply(force)
6074
reconfiguration = None
6075
if repository_type == 'use-shared':
5156
6076
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5157
elif target_type == 'standalone':
6077
elif repository_type == 'standalone':
5158
6078
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5159
elif target_type == 'with-trees':
6080
reconfiguration.apply(force)
6081
reconfiguration = None
6082
if repository_trees == 'with-trees':
5160
6083
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5161
6084
directory, True)
5162
elif target_type == 'with-no-trees':
6085
elif repository_trees == 'with-no-trees':
5163
6086
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5164
6087
directory, False)
5165
reconfiguration.apply(force)
6089
reconfiguration.apply(force)
6090
reconfiguration = None
5168
6093
class cmd_switch(Command):
5169
"""Set the branch of a checkout and update.
6094
__doc__ = """Set the branch of a checkout and update.
5171
6096
For lightweight checkouts, this changes the branch being referenced.
5172
6097
For heavyweight checkouts, this checks that there are no local commits
5184
6109
/path/to/newbranch.
5186
6111
Bound branches use the nickname of its master branch unless it is set
5187
locally, in which case switching will update the the local nickname to be
6112
locally, in which case switching will update the local nickname to be
5188
6113
that of the master.
5191
takes_args = ['to_location']
5192
takes_options = [Option('force',
5193
help='Switch even if local commits will be lost.')
6116
takes_args = ['to_location?']
6117
takes_options = ['directory',
6119
help='Switch even if local commits will be lost.'),
6121
Option('create-branch', short_name='b',
6122
help='Create the target branch from this one before'
6123
' switching to it.'),
5196
def run(self, to_location, force=False):
6126
def run(self, to_location=None, force=False, create_branch=False,
6127
revision=None, directory=u'.'):
5197
6128
from bzrlib import switch
5199
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
6129
tree_location = directory
6130
revision = _get_one_revision('switch', revision)
6131
control_dir = controldir.ControlDir.open_containing(tree_location)[0]
6132
if to_location is None:
6133
if revision is None:
6134
raise errors.BzrCommandError(gettext('You must supply either a'
6135
' revision or a location'))
6136
to_location = tree_location
5201
6138
branch = control_dir.open_branch()
5202
6139
had_explicit_nick = branch.get_config().has_explicit_nickname()
5203
6140
except errors.NotBranchError:
5204
6142
had_explicit_nick = False
5206
to_branch = Branch.open(to_location)
5207
except errors.NotBranchError:
5208
this_url = self._get_branch_location(control_dir)
5209
to_branch = Branch.open(
5210
urlutils.join(this_url, '..', to_location))
5211
switch.switch(control_dir, to_branch, force)
6145
raise errors.BzrCommandError(gettext('cannot create branch without'
6147
to_location = directory_service.directories.dereference(
6149
if '/' not in to_location and '\\' not in to_location:
6150
# This path is meant to be relative to the existing branch
6151
this_url = self._get_branch_location(control_dir)
6152
# Perhaps the target control dir supports colocated branches?
6154
root = controldir.ControlDir.open(this_url,
6155
possible_transports=[control_dir.user_transport])
6156
except errors.NotBranchError:
6159
colocated = root._format.colocated_branches
6161
to_location = urlutils.join_segment_parameters(this_url,
6162
{"branch": urlutils.escape(to_location)})
6164
to_location = urlutils.join(
6165
this_url, '..', urlutils.escape(to_location))
6166
to_branch = branch.bzrdir.sprout(to_location,
6167
possible_transports=[branch.bzrdir.root_transport],
6168
source_branch=branch).open_branch()
6170
# Perhaps it's a colocated branch?
6172
to_branch = control_dir.open_branch(to_location)
6173
except (errors.NotBranchError, errors.NoColocatedBranchSupport):
6175
to_branch = Branch.open(to_location)
6176
except errors.NotBranchError:
6177
this_url = self._get_branch_location(control_dir)
6178
to_branch = Branch.open(
6180
this_url, '..', urlutils.escape(to_location)))
6181
if revision is not None:
6182
revision = revision.as_revision_id(to_branch)
6183
switch.switch(control_dir, to_branch, force, revision_id=revision)
5212
6184
if had_explicit_nick:
5213
6185
branch = control_dir.open_branch() #get the new branch!
5214
6186
branch.nick = to_branch.nick
5215
note('Switched to branch: %s',
6187
note(gettext('Switched to branch: %s'),
5216
6188
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5218
6190
def _get_branch_location(self, control_dir):
5323
tree, file_list = tree_files(file_list, apply_view=False)
6295
tree, file_list = WorkingTree.open_containing_paths(file_list,
5324
6297
current_view, view_dict = tree.views.get_view_info()
5325
6298
if name is None:
5326
6299
name = current_view
5329
raise errors.BzrCommandError(
5330
"Both --delete and a file list specified")
6302
raise errors.BzrCommandError(gettext(
6303
"Both --delete and a file list specified"))
5332
raise errors.BzrCommandError(
5333
"Both --delete and --switch specified")
6305
raise errors.BzrCommandError(gettext(
6306
"Both --delete and --switch specified"))
5335
6308
tree.views.set_view_info(None, {})
5336
self.outf.write("Deleted all views.\n")
6309
self.outf.write(gettext("Deleted all views.\n"))
5337
6310
elif name is None:
5338
raise errors.BzrCommandError("No current view to delete")
6311
raise errors.BzrCommandError(gettext("No current view to delete"))
5340
6313
tree.views.delete_view(name)
5341
self.outf.write("Deleted '%s' view.\n" % name)
6314
self.outf.write(gettext("Deleted '%s' view.\n") % name)
5344
raise errors.BzrCommandError(
5345
"Both --switch and a file list specified")
6317
raise errors.BzrCommandError(gettext(
6318
"Both --switch and a file list specified"))
5347
raise errors.BzrCommandError(
5348
"Both --switch and --all specified")
6320
raise errors.BzrCommandError(gettext(
6321
"Both --switch and --all specified"))
5349
6322
elif switch == 'off':
5350
6323
if current_view is None:
5351
raise errors.BzrCommandError("No current view to disable")
6324
raise errors.BzrCommandError(gettext("No current view to disable"))
5352
6325
tree.views.set_view_info(None, view_dict)
5353
self.outf.write("Disabled '%s' view.\n" % (current_view))
6326
self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
5355
6328
tree.views.set_view_info(switch, view_dict)
5356
6329
view_str = views.view_display_str(tree.views.lookup_view())
5357
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
6330
self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
5360
self.outf.write('Views defined:\n')
6333
self.outf.write(gettext('Views defined:\n'))
5361
6334
for view in sorted(view_dict):
5362
6335
if view == current_view:
5446
6457
Option('destroy',
5447
6458
help='Destroy removed changes instead of shelving them.'),
5449
_see_also = ['unshelve']
6460
_see_also = ['unshelve', 'configuration']
5451
6462
def run(self, revision=None, all=False, file_list=None, message=None,
5452
writer=None, list=False, destroy=False):
6463
writer=None, list=False, destroy=False, directory=None):
5454
return self.run_for_list()
6465
return self.run_for_list(directory=directory)
5455
6466
from bzrlib.shelf_ui import Shelver
5456
6467
if writer is None:
5457
6468
writer = bzrlib.option.diff_writer_registry.get()
5459
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
5460
message, destroy=destroy).run()
6470
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6471
file_list, message, destroy=destroy, directory=directory)
5461
6476
except errors.UserAbort:
5464
def run_for_list(self):
5465
tree = WorkingTree.open_containing('.')[0]
5468
manager = tree.get_shelf_manager()
5469
shelves = manager.active_shelves()
5470
if len(shelves) == 0:
5471
note('No shelved changes.')
5473
for shelf_id in reversed(shelves):
5474
message = manager.get_metadata(shelf_id).get('message')
5476
message = '<no message>'
5477
self.outf.write('%3d: %s\n' % (shelf_id, message))
6479
def run_for_list(self, directory=None):
6480
if directory is None:
6482
tree = WorkingTree.open_containing(directory)[0]
6483
self.add_cleanup(tree.lock_read().unlock)
6484
manager = tree.get_shelf_manager()
6485
shelves = manager.active_shelves()
6486
if len(shelves) == 0:
6487
note(gettext('No shelved changes.'))
6489
for shelf_id in reversed(shelves):
6490
message = manager.get_metadata(shelf_id).get('message')
6492
message = '<no message>'
6493
self.outf.write('%3d: %s\n' % (shelf_id, message))
5483
6497
class cmd_unshelve(Command):
5484
"""Restore shelved changes.
6498
__doc__ = """Restore shelved changes.
5486
6500
By default, the most recently shelved changes are restored. However if you
5487
6501
specify a shelf by id those changes will be restored instead. This works
5586
6609
self.outf.write('%s %s\n' % (path, location))
5589
# these get imported and then picked up by the scan for cmd_*
5590
# TODO: Some more consistent way to split command definitions across files;
5591
# we do need to load at least some information about them to know of
5592
# aliases. ideally we would avoid loading the implementation until the
5593
# details were needed.
5594
from bzrlib.cmd_version_info import cmd_version_info
5595
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
5596
from bzrlib.bundle.commands import (
5599
from bzrlib.foreign import cmd_dpush
5600
from bzrlib.sign_my_commits import cmd_sign_my_commits
5601
from bzrlib.weave_commands import cmd_versionedfile_list, \
5602
cmd_weave_plan_merge, cmd_weave_merge_text
6612
class cmd_export_pot(Command):
6613
__doc__ = """Export command helps and error messages in po format."""
6616
takes_options = [Option('plugin',
6617
help='Export help text from named command '\
6618
'(defaults to all built in commands).',
6620
Option('include-duplicates',
6621
help='Output multiple copies of the same msgid '
6622
'string if it appears more than once.'),
6625
def run(self, plugin=None, include_duplicates=False):
6626
from bzrlib.export_pot import export_pot
6627
export_pot(self.outf, plugin, include_duplicates)
6630
def _register_lazy_builtins():
6631
# register lazy builtins from other modules; called at startup and should
6632
# be only called once.
6633
for (name, aliases, module_name) in [
6634
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6635
('cmd_config', [], 'bzrlib.config'),
6636
('cmd_dpush', [], 'bzrlib.foreign'),
6637
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6638
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6639
('cmd_conflicts', [], 'bzrlib.conflicts'),
6640
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6641
('cmd_verify_signatures', [],
6642
'bzrlib.commit_signature_commands'),
6643
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6645
builtin_command_registry.register_lazy(name, aliases, module_name)