14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""builtin bzr commands"""
22
from shutil import rmtree
27
from bzrlib.branch import Branch
28
import bzrlib.bzrdir as bzrdir
29
from bzrlib.commands import Command, display_command
30
from bzrlib.revision import common_ancestor
31
import bzrlib.errors as errors
32
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError,
33
NotBranchError, DivergedBranches, NotConflicted,
34
NoSuchFile, NoWorkingTree, FileInWrongBranch,
36
from bzrlib.log import show_one_log
37
from bzrlib.merge import Merge3Merger
38
from bzrlib.option import Option
39
from bzrlib.progress import DummyProgress, ProgressPhase
40
from bzrlib.revisionspec import RevisionSpec
22
41
import bzrlib.trace
23
from bzrlib.trace import mutter, note, log_error, warning
24
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
25
from bzrlib.branch import Branch
26
from bzrlib import BZRDIR
27
from bzrlib.commands import Command
42
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
43
from bzrlib.transport.local import LocalTransport
45
from bzrlib.workingtree import WorkingTree
48
def tree_files(file_list, default_branch=u'.'):
50
return internal_tree_files(file_list, default_branch)
51
except FileInWrongBranch, e:
52
raise BzrCommandError("%s is not in the same branch as %s" %
53
(e.path, file_list[0]))
55
def internal_tree_files(file_list, default_branch=u'.'):
57
Return a branch and list of branch-relative paths.
58
If supplied file_list is empty or None, the branch default will be used,
59
and returned file_list will match the original.
61
if file_list is None or len(file_list) == 0:
62
return WorkingTree.open_containing(default_branch)[0], file_list
63
tree = WorkingTree.open_containing(file_list[0])[0]
65
for filename in file_list:
67
new_list.append(tree.relpath(filename))
68
except errors.PathNotChild:
69
raise FileInWrongBranch(tree.branch, filename)
73
def get_format_type(typestring):
74
"""Parse and return a format specifier."""
75
if typestring == "metadir":
76
return bzrdir.BzrDirMetaFormat1()
77
if typestring == "knit":
78
format = bzrdir.BzrDirMetaFormat1()
79
format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
81
msg = "No known bzr-dir format %s. Supported types are: metadir\n" %\
83
raise BzrCommandError(msg)
86
# TODO: Make sure no commands unconditionally use the working directory as a
87
# branch. If a filename argument is used, the first of them should be used to
88
# specify the branch. (Perhaps this can be factored out into some kind of
89
# Argument class, representing a file in a branch, where the first occurrence
30
92
class cmd_status(Command):
31
93
"""Display status summary.
291
379
def run(self, names_list):
292
380
if len(names_list) < 2:
293
381
raise BzrCommandError("missing file argument")
294
b = Branch.open_containing(names_list[0])
296
rel_names = [b.relpath(x) for x in names_list]
382
tree, rel_names = tree_files(names_list)
298
384
if os.path.isdir(names_list[-1]):
299
385
# move into existing directory
300
for pair in b.move(rel_names[:-1], rel_names[-1]):
386
for pair in tree.move(rel_names[:-1], rel_names[-1]):
301
387
print "%s => %s" % pair
303
389
if len(names_list) != 2:
304
390
raise BzrCommandError('to mv multiple files the destination '
305
391
'must be a versioned directory')
306
b.rename_one(rel_names[0], rel_names[1])
392
tree.rename_one(rel_names[0], rel_names[1])
307
393
print "%s => %s" % (rel_names[0], rel_names[1])
312
396
class cmd_pull(Command):
313
397
"""Pull any changes from another branch into the current one.
315
If the location is omitted, the last-used location will be used.
316
Both the revision history and the working directory will be
399
If there is no default location set, the first pull will set it. After
400
that, you can omit the location to use the default. To change the
401
default, use --remember.
319
403
This command only works on branches that have not diverged. Branches are
320
404
considered diverged if both branches have had commits without first
321
405
pulling from the other.
323
407
If branches have diverged, you can use 'bzr merge' to pull the text changes
324
from one into the other.
408
from one into the other. Once one branch has merged, the other should
409
be able to pull it again.
411
If you want to forget your local changes and just update your branch to
412
match the remote one, use --overwrite.
414
takes_options = ['remember', 'overwrite', 'revision', 'verbose']
326
415
takes_args = ['location?']
328
def run(self, location=None):
329
from bzrlib.merge import merge
331
from shutil import rmtree
334
br_to = Branch.open_containing('.')
335
stored_loc = br_to.get_parent()
417
def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
418
# FIXME: too much stuff is in the command class
419
tree_to = WorkingTree.open_containing(u'.')[0]
420
stored_loc = tree_to.branch.get_parent()
336
421
if location is None:
337
422
if stored_loc is None:
338
423
raise BzrCommandError("No pull location known or specified.")
340
print "Using last location: %s" % stored_loc
341
location = stored_loc
342
cache_root = tempfile.mkdtemp()
343
from bzrlib.errors import DivergedBranches
344
br_from = Branch.open_containing(location)
345
location = br_from.base
346
old_revno = br_to.revno()
348
from bzrlib.errors import DivergedBranches
349
br_from = Branch.open(location)
350
br_from.setup_caching(cache_root)
351
location = br_from.base
352
old_revno = br_to.revno()
425
print "Using saved location: %s" % stored_loc
426
location = stored_loc
428
br_from = Branch.open(location)
429
br_to = tree_to.branch
433
elif len(revision) == 1:
434
rev_id = revision[0].in_history(br_from).rev_id
436
raise BzrCommandError('bzr pull --revision takes one value.')
438
old_rh = br_to.revision_history()
439
count = tree_to.pull(br_from, overwrite, rev_id)
441
if br_to.get_parent() is None or remember:
442
br_to.set_parent(location)
443
note('%d revision(s) pulled.' % (count,))
446
new_rh = tree_to.branch.revision_history()
449
from bzrlib.log import show_changed_revisions
450
show_changed_revisions(tree_to.branch, old_rh, new_rh)
453
class cmd_push(Command):
454
"""Push this branch into another branch.
456
The remote branch will not have its working tree populated because this
457
is both expensive, and may not be supported on the remote file system.
459
Some smart servers or protocols *may* put the working tree in place.
461
If there is no default push location set, the first push will set it.
462
After that, you can omit the location to use the default. To change the
463
default, use --remember.
465
This command only works on branches that have not diverged. Branches are
466
considered diverged if the branch being pushed to is not an older version
469
If branches have diverged, you can use 'bzr push --overwrite' to replace
470
the other branch completely.
472
If you want to ensure you have the different changes in the other branch,
473
do a merge (see bzr help merge) from the other branch, and commit that
474
before doing a 'push --overwrite'.
476
takes_options = ['remember', 'overwrite',
477
Option('create-prefix',
478
help='Create the path leading up to the branch '
479
'if it does not already exist')]
480
takes_args = ['location?']
482
def run(self, location=None, remember=False, overwrite=False,
483
create_prefix=False, verbose=False):
484
# FIXME: Way too big! Put this into a function called from the
486
from bzrlib.transport import get_transport
488
tree_from = WorkingTree.open_containing(u'.')[0]
489
br_from = tree_from.branch
490
stored_loc = tree_from.branch.get_push_location()
492
if stored_loc is None:
493
raise BzrCommandError("No push location known or specified.")
495
print "Using saved location: %s" % stored_loc
496
location = stored_loc
498
dir_to = bzrlib.bzrdir.BzrDir.open(location)
499
br_to = dir_to.open_branch()
500
except NotBranchError:
502
transport = get_transport(location).clone('..')
503
if not create_prefix:
505
transport.mkdir(transport.relpath(location))
507
raise BzrCommandError("Parent directory of %s "
508
"does not exist." % location)
510
current = transport.base
511
needed = [(transport, transport.relpath(location))]
514
transport, relpath = needed[-1]
515
transport.mkdir(relpath)
518
new_transport = transport.clone('..')
519
needed.append((new_transport,
520
new_transport.relpath(transport.base)))
521
if new_transport.base == transport.base:
522
raise BzrCommandError("Could not creeate "
524
dir_to = br_from.bzrdir.clone(location)
525
br_to = dir_to.open_branch()
526
old_rh = br_to.revision_history()
354
br_to.update_revisions(br_from)
355
except DivergedBranches:
356
raise BzrCommandError("These branches have diverged."
359
merge(('.', -1), ('.', old_revno), check_clean=False)
360
if location != stored_loc:
361
br_to.set_parent(location)
529
tree_to = dir_to.open_workingtree()
530
except errors.NotLocalUrl:
531
# TODO: This should be updated for branches which don't have a
532
# working tree, as opposed to ones where we just couldn't
534
warning('Unable to update the working tree of: %s' % (br_to.base,))
535
count = br_to.pull(br_from, overwrite)
536
except NoWorkingTree:
537
count = br_to.pull(br_from, overwrite)
539
count = tree_to.pull(br_from, overwrite)
540
except DivergedBranches:
541
raise BzrCommandError("These branches have diverged."
542
" Try a merge then push with overwrite.")
543
if br_from.get_push_location() is None or remember:
544
br_from.set_push_location(location)
545
note('%d revision(s) pushed.' % (count,))
548
new_rh = br_to.revision_history()
551
from bzrlib.log import show_changed_revisions
552
show_changed_revisions(br_to, old_rh, new_rh)
367
555
class cmd_branch(Command):
427
copy_branch(br_from, to_location, revision_id, basis_branch)
616
# preserve whatever source format we have.
617
dir = br_from.bzrdir.sprout(to_location, revision_id, basis_dir)
618
branch = dir.open_branch()
428
619
except bzrlib.errors.NoSuchRevision:
429
620
rmtree(to_location)
430
msg = "The branch %s has no revision %d." % (from_location, revision[0])
621
msg = "The branch %s has no revision %s." % (from_location, revision[0])
431
622
raise BzrCommandError(msg)
432
623
except bzrlib.errors.UnlistableBranch:
433
msg = "The branch %s cannot be used as a --basis"
625
msg = "The branch %s cannot be used as a --basis" % (basis,)
626
raise BzrCommandError(msg)
628
branch.control_files.put_utf8('branch-name', name)
630
note('Branched %d revision(s).' % branch.revno())
635
class cmd_checkout(Command):
636
"""Create a new checkout of an existing branch.
638
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
639
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
641
To retrieve the branch as of a particular revision, supply the --revision
642
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
643
out of date [so you cannot commit] but it may be useful (i.e. to examine old
646
--basis is to speed up checking out from remote branches. When specified, it
647
uses the inventory and file contents from the basis branch in preference to the
648
branch being checked out. [Not implemented yet.]
650
takes_args = ['branch_location', 'to_location?']
651
takes_options = ['revision', # , 'basis']
652
Option('lightweight',
653
help="perform a lightweight checkout. Lightweight "
654
"checkouts depend on access to the branch for "
655
"every operation. Normal checkouts can perform "
656
"common operations like diff and status without "
657
"such access, and also support local commits."
661
def run(self, branch_location, to_location=None, revision=None, basis=None,
665
elif len(revision) > 1:
666
raise BzrCommandError(
667
'bzr checkout --revision takes exactly 1 revision value')
668
source = Branch.open(branch_location)
669
if len(revision) == 1 and revision[0] is not None:
670
revision_id = revision[0].in_history(source)[1]
673
if to_location is None:
674
to_location = os.path.basename(branch_location.rstrip("/\\"))
676
os.mkdir(to_location)
678
if e.errno == errno.EEXIST:
679
raise BzrCommandError('Target directory "%s" already'
680
' exists.' % to_location)
681
if e.errno == errno.ENOENT:
682
raise BzrCommandError('Parent of "%s" does not exist.' %
686
old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
687
bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
690
checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
691
bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
693
checkout_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience(
694
to_location, force_new_tree=False)
695
checkout = checkout_branch.bzrdir
696
checkout_branch.bind(source)
697
if revision_id is not None:
698
rh = checkout_branch.revision_history()
699
checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
700
checkout.create_workingtree(revision_id)
702
bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
438
705
class cmd_renames(Command):
439
706
"""Show list of renamed files.
441
TODO: Option to show renames between two historical versions.
443
TODO: Only show renames under dir, rather than in the whole branch.
708
# TODO: Option to show renames between two historical versions.
710
# TODO: Only show renames under dir, rather than in the whole branch.
445
711
takes_args = ['dir?']
447
def run(self, dir='.'):
448
b = Branch.open_containing(dir)
449
old_inv = b.basis_tree().inventory
450
new_inv = b.read_working_inventory()
714
def run(self, dir=u'.'):
715
tree = WorkingTree.open_containing(dir)[0]
716
old_inv = tree.basis_tree().inventory
717
new_inv = tree.read_working_inventory()
452
719
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
505
806
starting at the branch root."""
507
808
takes_args = ['filename']
508
810
def run(self, filename):
509
b = Branch.open_containing(filename)
511
fid = inv.path2id(b.relpath(filename))
811
tree, relpath = WorkingTree.open_containing(filename)
813
fid = inv.path2id(relpath)
513
815
raise BzrError("%r is not a versioned file" % filename)
514
816
for fip in inv.get_idpath(fid):
820
class cmd_reconcile(Command):
821
"""Reconcile bzr metadata in a branch.
823
This can correct data mismatches that may have been caused by
824
previous ghost operations or bzr upgrades. You should only
825
need to run this command if 'bzr check' or a bzr developer
826
advises you to run it.
828
If a second branch is provided, cross-branch reconciliation is
829
also attempted, which will check that data like the tree root
830
id which was not present in very early bzr versions is represented
831
correctly in both branches.
833
At the same time it is run it may recompress data resulting in
834
a potential saving in disk space or performance gain.
836
The branch *MUST* be on a listable system such as local disk or sftp.
838
takes_args = ['branch?']
840
def run(self, branch="."):
841
from bzrlib.reconcile import reconcile
842
dir = bzrlib.bzrdir.BzrDir.open(branch)
518
846
class cmd_revision_history(Command):
519
847
"""Display list of revision ids on this branch."""
522
for patchid in Branch.open_containing('.').revision_history():
851
branch = WorkingTree.open_containing(u'.')[0].branch
852
for patchid in branch.revision_history():
526
856
class cmd_ancestry(Command):
527
857
"""List all revisions merged into this branch."""
531
for revision_id in b.get_ancestry(b.last_revision()):
861
tree = WorkingTree.open_containing(u'.')[0]
863
# FIXME. should be tree.last_revision
864
for revision_id in b.repository.get_ancestry(b.last_revision()):
532
865
print revision_id
535
class cmd_directories(Command):
536
"""Display list of versioned directories in this branch."""
538
for name, ie in Branch.open_containing('.').read_working_inventory().directories():
545
868
class cmd_init(Command):
546
869
"""Make a directory into a versioned branch.
565
916
If files are listed, only the changes in those files are listed.
566
917
Otherwise, all changes for the tree are listed.
568
TODO: Allow diff across branches.
570
TODO: Option to use external diff command; could be GNU diff, wdiff,
573
TODO: Python difflib is not exactly the same as unidiff; should
574
either fix it up or prefer to use an external diff.
576
TODO: If a directory is given, diff everything under that.
578
TODO: Selected-file diff is inefficient and doesn't show you
581
TODO: This probably handles non-Unix newlines poorly.
924
# TODO: Allow diff across branches.
925
# TODO: Option to use external diff command; could be GNU diff, wdiff,
926
# or a graphical diff.
928
# TODO: Python difflib is not exactly the same as unidiff; should
929
# either fix it up or prefer to use an external diff.
931
# TODO: If a directory is given, diff everything under that.
933
# TODO: Selected-file diff is inefficient and doesn't show you
936
# TODO: This probably handles non-Unix newlines poorly.
589
938
takes_args = ['file*']
590
939
takes_options = ['revision', 'diff-options']
591
940
aliases = ['di', 'dif']
593
943
def run(self, revision=None, file_list=None, diff_options=None):
594
from bzrlib.diff import show_diff
597
b = Branch.open_containing(file_list[0])
598
file_list = [b.relpath(f) for f in file_list]
599
if file_list == ['']:
600
# just pointing to top-of-tree
603
b = Branch.open_containing('.')
944
from bzrlib.diff import diff_cmd_helper, show_diff_trees
946
tree1, file_list = internal_tree_files(file_list)
950
except FileInWrongBranch:
951
if len(file_list) != 2:
952
raise BzrCommandError("Files are in different branches")
954
tree1, file1 = WorkingTree.open_containing(file_list[0])
955
tree2, file2 = WorkingTree.open_containing(file_list[1])
956
if file1 != "" or file2 != "":
957
# FIXME diff those two files. rbc 20051123
958
raise BzrCommandError("Files are in different branches")
605
960
if revision is not None:
606
if len(revision) == 1:
607
show_diff(b, revision[0], specific_files=file_list,
608
external_diff_options=diff_options)
961
if tree2 is not None:
962
raise BzrCommandError("Can't specify -r with two branches")
963
if (len(revision) == 1) or (revision[1].spec is None):
964
return diff_cmd_helper(tree1, file_list, diff_options,
609
966
elif len(revision) == 2:
610
show_diff(b, revision[0], specific_files=file_list,
611
external_diff_options=diff_options,
612
revision2=revision[1])
967
return diff_cmd_helper(tree1, file_list, diff_options,
968
revision[0], revision[1])
614
970
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
616
show_diff(b, None, specific_files=file_list,
617
external_diff_options=diff_options)
972
if tree2 is not None:
973
return show_diff_trees(tree1, tree2, sys.stdout,
974
specific_files=file_list,
975
external_diff_options=diff_options)
977
return diff_cmd_helper(tree1, file_list, diff_options)
622
980
class cmd_deleted(Command):
623
981
"""List files deleted in the working tree.
625
TODO: Show files deleted since a previous revision, or between two revisions.
983
# TODO: Show files deleted since a previous revision, or
984
# between two revisions.
985
# TODO: Much more efficient way to do this: read in new
986
# directories with readdir, rather than stating each one. Same
987
# level of effort but possibly much less IO. (Or possibly not,
988
# if the directories are very large...)
627
990
def run(self, show_ids=False):
628
b = Branch.open_containing('.')
630
new = b.working_tree()
632
## TODO: Much more efficient way to do this: read in new
633
## directories with readdir, rather than stating each one. Same
634
## level of effort but possibly much less IO. (Or possibly not,
635
## if the directories are very large...)
991
tree = WorkingTree.open_containing(u'.')[0]
992
old = tree.basis_tree()
637
993
for path, ie in old.inventory.iter_entries():
638
if not new.has_id(ie.file_id):
994
if not tree.has_id(ie.file_id):
640
996
print '%-50s %s' % (path, ie.file_id)
680
1037
The root is the nearest enclosing directory with a .bzr control
682
1039
takes_args = ['filename?']
683
1041
def run(self, filename=None):
684
1042
"""Print the branch root."""
685
b = Branch.open_containing(filename)
1043
tree = WorkingTree.open_containing(filename)[0]
689
1047
class cmd_log(Command):
690
1048
"""Show log of this branch.
692
To request a range of logs, you can use the command -r begin:end
693
-r revision requests a specific revision, -r :end or -r begin: are
1050
To request a range of logs, you can use the command -r begin..end
1051
-r revision requests a specific revision, -r ..end or -r begin.. are
696
--message allows you to give a regular expression, which will be evaluated
697
so that only matching entries will be displayed.
699
TODO: Make --revision support uuid: and hash: [future tag:] notation.
1055
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
703
1057
takes_args = ['filename?']
704
takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
705
'long', 'message', 'short',]
1058
takes_options = [Option('forward',
1059
help='show from oldest to newest'),
1060
'timezone', 'verbose',
1061
'show-ids', 'revision',
1065
help='show revisions whose message matches this regexp',
707
1070
def run(self, filename=None, timezone='original',
715
1080
from bzrlib.log import log_formatter, show_log
1082
assert message is None or isinstance(message, basestring), \
1083
"invalid message argument %r" % message
718
1084
direction = (forward and 'forward') or 'reverse'
721
b = Branch.open_containing(filename)
722
fp = b.relpath(filename)
724
file_id = b.read_working_inventory().path2id(fp)
726
file_id = None # points to branch root
1089
# find the file id to log:
1091
dir, fp = bzrdir.BzrDir.open_containing(filename)
1092
b = dir.open_branch()
1096
inv = dir.open_workingtree().inventory
1097
except (errors.NotBranchError, errors.NotLocalUrl):
1098
# either no tree, or is remote.
1099
inv = b.basis_tree().inventory
1100
file_id = inv.path2id(fp)
728
b = Branch.open_containing('.')
1103
# FIXME ? log the current subdir only RBC 20060203
1104
dir, relpath = bzrdir.BzrDir.open_containing('.')
1105
b = dir.open_branch()
731
1107
if revision is None:
776
1172
A more user-friendly interface is "bzr log FILE"."""
778
1174
takes_args = ["filename"]
779
1176
def run(self, filename):
780
b = Branch.open_containing(filename)
781
inv = b.read_working_inventory()
782
file_id = inv.path2id(b.relpath(filename))
1177
tree, relpath = WorkingTree.open_containing(filename)
1179
inv = tree.read_working_inventory()
1180
file_id = inv.path2id(relpath)
783
1181
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
784
1182
print "%6d %s" % (revno, what)
787
1185
class cmd_ls(Command):
788
1186
"""List files in a tree.
790
TODO: Take a revision or remote path and list that tree instead.
1188
# TODO: Take a revision or remote path and list that tree instead.
793
def run(self, revision=None, verbose=False):
794
b = Branch.open_containing('.')
796
tree = b.working_tree()
798
tree = b.revision_tree(revision.in_history(b).rev_id)
1190
takes_options = ['verbose', 'revision',
1191
Option('non-recursive',
1192
help='don\'t recurse into sub-directories'),
1194
help='Print all paths from the root of the branch.'),
1195
Option('unknown', help='Print unknown files'),
1196
Option('versioned', help='Print versioned files'),
1197
Option('ignored', help='Print ignored files'),
1199
Option('null', help='Null separate the files'),
1202
def run(self, revision=None, verbose=False,
1203
non_recursive=False, from_root=False,
1204
unknown=False, versioned=False, ignored=False,
1207
if verbose and null:
1208
raise BzrCommandError('Cannot set both --verbose and --null')
1209
all = not (unknown or versioned or ignored)
1211
selection = {'I':ignored, '?':unknown, 'V':versioned}
1213
tree, relpath = WorkingTree.open_containing(u'.')
1218
if revision is not None:
1219
tree = tree.branch.repository.revision_tree(
1220
revision[0].in_history(tree.branch).rev_id)
799
1221
for fp, fc, kind, fid, entry in tree.list_files():
801
kindch = entry.kind_character()
802
print '%-8s %s%s' % (fc, fp, kindch)
1222
if fp.startswith(relpath):
1223
fp = fp[len(relpath):]
1224
if non_recursive and '/' in fp:
1226
if not all and not selection[fc]:
1229
kindch = entry.kind_character()
1230
print '%-8s %s%s' % (fc, fp, kindch)
1232
sys.stdout.write(fp)
1233
sys.stdout.write('\0')
808
1239
class cmd_unknowns(Command):
809
1240
"""List unknown files."""
811
1243
from bzrlib.osutils import quotefn
812
for f in Branch.open_containing('.').unknowns():
1244
for f in WorkingTree.open_containing(u'.')[0].unknowns():
813
1245
print quotefn(f)
817
1248
class cmd_ignore(Command):
818
1249
"""Ignore a command or pattern.
820
1251
To remove patterns from the ignore list, edit the .bzrignore file.
822
1253
If the pattern contains a slash, it is compared to the whole path
823
from the branch root. Otherwise, it is comapred to only the last
824
component of the path.
1254
from the branch root. Otherwise, it is compared to only the last
1255
component of the path. To match a file only in the root directory,
826
1258
Ignore patterns are case-insensitive on case-insensitive systems.
983
1428
A selected-file commit may fail in some cases where the committed
984
1429
tree would be invalid, such as trying to commit a file in a
985
1430
newly-added directory that is not itself committed.
987
TODO: Run hooks on tree to-be-committed, and after commit.
989
TODO: Strict commit that fails if there are unknown or deleted files.
1432
# TODO: Run hooks on tree to-be-committed, and after commit.
1434
# TODO: Strict commit that fails if there are deleted files.
1435
# (what does "deleted files" mean ??)
1437
# TODO: Give better message for -s, --summary, used by tla people
1439
# XXX: verbose currently does nothing
991
1441
takes_args = ['selected*']
992
takes_options = ['message', 'file', 'verbose', 'unchanged']
1442
takes_options = ['message', 'verbose',
1444
help='commit even if nothing has changed'),
1445
Option('file', type=str,
1447
help='file containing commit message'),
1449
help="refuse to commit if there are unknown "
1450
"files in the working tree."),
1452
help="perform a local only commit in a bound "
1453
"branch. Such commits are not pushed to "
1454
"the master branch until a normal commit "
993
1458
aliases = ['ci', 'checkin']
995
# TODO: Give better message for -s, --summary, used by tla people
997
# XXX: verbose currently does nothing
999
1460
def run(self, message=None, file=None, verbose=True, selected_list=None,
1001
from bzrlib.errors import PointlessCommit
1002
from bzrlib.msgeditor import edit_commit_message
1003
from bzrlib.status import show_status
1004
from cStringIO import StringIO
1006
b = Branch.open_containing('.')
1008
selected_list = [b.relpath(s) for s in selected_list]
1461
unchanged=False, strict=False, local=False):
1462
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1464
from bzrlib.msgeditor import edit_commit_message, \
1465
make_commit_message_template
1466
from tempfile import TemporaryFile
1469
# TODO: Need a blackbox test for invoking the external editor; may be
1470
# slightly problematic to run this cross-platform.
1472
# TODO: do more checks that the commit will succeed before
1473
# spending the user's valuable time typing a commit message.
1475
# TODO: if the commit *does* happen to fail, then save the commit
1476
# message to a temporary file where it can be recovered
1477
tree, selected_list = tree_files(selected_list)
1478
if local and not tree.branch.get_bound_location():
1479
raise errors.LocalRequiresBoundBranch()
1010
1480
if message is None and not file:
1011
catcher = StringIO()
1012
show_status(b, specific_files=selected_list,
1014
message = edit_commit_message(catcher.getvalue())
1481
template = make_commit_message_template(tree, selected_list)
1482
message = edit_commit_message(template)
1016
1483
if message is None:
1017
1484
raise BzrCommandError("please specify a commit message"
1018
1485
" with either --message or --file")
1109
1618
This creates temporary test directories in the working directory,
1110
1619
but not existing data is affected. These directories are deleted
1111
1620
if the tests pass, or left behind to help in debugging if they
1621
fail and --keep-output is specified.
1114
1623
If arguments are given, they are regular expressions that say
1115
which tests should run."""
1624
which tests should run.
1626
If the global option '--no-plugins' is given, plugins are not loaded
1627
before running the selftests. This has two effects: features provided or
1628
modified by plugins will not be tested, and tests provided by plugins will
1633
bzr --no-plugins selftest -v
1116
1635
# TODO: --list should give a list of all available tests
1637
# NB: this is used from the class without creating an instance, which is
1638
# why it does not have a self parameter.
1639
def get_transport_type(typestring):
1640
"""Parse and return a transport specifier."""
1641
if typestring == "sftp":
1642
from bzrlib.transport.sftp import SFTPAbsoluteServer
1643
return SFTPAbsoluteServer
1644
if typestring == "memory":
1645
from bzrlib.transport.memory import MemoryServer
1647
msg = "No known transport type %s. Supported types are: sftp\n" %\
1649
raise BzrCommandError(msg)
1118
takes_args = ['testnames*']
1119
takes_options = ['verbose', 'pattern']
1120
def run(self, testnames_list=None, verbose=False, pattern=".*"):
1652
takes_args = ['testspecs*']
1653
takes_options = ['verbose',
1654
Option('one', help='stop when one test fails'),
1655
Option('keep-output',
1656
help='keep output directories when tests fail'),
1658
help='Use a different transport by default '
1659
'throughout the test suite.',
1660
type=get_transport_type),
1663
def run(self, testspecs_list=None, verbose=False, one=False,
1664
keep_output=False, transport=None):
1121
1665
import bzrlib.ui
1122
from bzrlib.selftest import selftest
1666
from bzrlib.tests import selftest
1123
1667
# we don't want progress meters from the tests to go to the
1124
1668
# real output; and we don't want log messages cluttering up
1125
1669
# the real logs.
1871
class cmd_remerge(Command):
1874
takes_args = ['file*']
1875
takes_options = ['merge-type', 'reprocess',
1876
Option('show-base', help="Show base revision text in "
1879
def run(self, file_list=None, merge_type=None, show_base=False,
1881
from bzrlib.merge import merge_inner, transform_tree
1882
if merge_type is None:
1883
merge_type = Merge3Merger
1884
tree, file_list = tree_files(file_list)
1887
pending_merges = tree.pending_merges()
1888
if len(pending_merges) != 1:
1889
raise BzrCommandError("Sorry, remerge only works after normal"
1890
+ " merges. Not cherrypicking or"
1892
repository = tree.branch.repository
1893
base_revision = common_ancestor(tree.branch.last_revision(),
1894
pending_merges[0], repository)
1895
base_tree = repository.revision_tree(base_revision)
1896
other_tree = repository.revision_tree(pending_merges[0])
1897
interesting_ids = None
1898
if file_list is not None:
1899
interesting_ids = set()
1900
for filename in file_list:
1901
file_id = tree.path2id(filename)
1903
raise NotVersionedError(filename)
1904
interesting_ids.add(file_id)
1905
if tree.kind(file_id) != "directory":
1908
for name, ie in tree.inventory.iter_entries(file_id):
1909
interesting_ids.add(ie.file_id)
1910
transform_tree(tree, tree.basis_tree(), interesting_ids)
1911
if file_list is None:
1912
restore_files = list(tree.iter_conflicts())
1914
restore_files = file_list
1915
for filename in restore_files:
1917
restore(tree.abspath(filename))
1918
except NotConflicted:
1920
conflicts = merge_inner(tree.branch, other_tree, base_tree,
1922
interesting_ids = interesting_ids,
1923
other_rev_id=pending_merges[0],
1924
merge_type=merge_type,
1925
show_base=show_base,
1926
reprocess=reprocess)
1274
1934
class cmd_revert(Command):
1275
1935
"""Reverse all changes since the last commit.
1349
2013
def run(self, from_branch, to_branch):
1350
2014
from bzrlib.fetch import Fetcher
1351
2015
from bzrlib.branch import Branch
1352
from_b = Branch(from_branch)
1353
to_b = Branch(to_branch)
2016
from_b = Branch.open(from_branch)
2017
to_b = Branch.open(to_branch)
1354
2018
Fetcher(to_b, from_b)
1358
2021
class cmd_missing(Command):
1359
"""What is missing in this branch relative to other branch.
1361
# TODO: rewrite this in terms of ancestry so that it shows only
1364
takes_args = ['remote?']
1365
aliases = ['mis', 'miss']
1366
# We don't have to add quiet to the list, because
1367
# unknown options are parsed as booleans
1368
takes_options = ['verbose', 'quiet']
1370
def run(self, remote=None, verbose=False, quiet=False):
1371
from bzrlib.errors import BzrCommandError
1372
from bzrlib.missing import show_missing
1374
if verbose and quiet:
1375
raise BzrCommandError('Cannot pass both quiet and verbose')
1377
b = Branch.open_containing('.')
1378
parent = b.get_parent()
2022
"""Show unmerged/unpulled revisions between two branches.
2024
OTHER_BRANCH may be local or remote."""
2025
takes_args = ['other_branch?']
2026
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2028
'Display changes in the local branch only'),
2029
Option('theirs-only',
2030
'Display changes in the remote branch only'),
2039
def run(self, other_branch=None, reverse=False, mine_only=False,
2040
theirs_only=False, log_format=None, long=False, short=False, line=False,
2041
show_ids=False, verbose=False):
2042
from bzrlib.missing import find_unmerged, iter_log_data
2043
from bzrlib.log import log_formatter
2044
local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
2045
parent = local_branch.get_parent()
2046
if other_branch is None:
2047
other_branch = parent
2048
if other_branch is None:
1381
2049
raise BzrCommandError("No missing location known or specified.")
1384
print "Using last location: %s" % parent
1386
elif parent is None:
1387
# We only update parent if it did not exist, missing
1388
# should not change the parent
1389
b.set_parent(remote)
1390
br_remote = Branch.open_containing(remote)
1391
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
2050
print "Using last location: " + local_branch.get_parent()
2051
remote_branch = bzrlib.branch.Branch.open(other_branch)
2052
remote_branch.lock_read()
2054
local_branch.lock_write()
2056
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2057
if (log_format == None):
2058
default = bzrlib.config.BranchConfig(local_branch).log_format()
2059
log_format = get_log_format(long=long, short=short, line=line, default=default)
2060
lf = log_formatter(log_format, sys.stdout,
2062
show_timezone='original')
2063
if reverse is False:
2064
local_extra.reverse()
2065
remote_extra.reverse()
2066
if local_extra and not theirs_only:
2067
print "You have %d extra revision(s):" % len(local_extra)
2068
for data in iter_log_data(local_extra, local_branch.repository,
2071
printed_local = True
2073
printed_local = False
2074
if remote_extra and not mine_only:
2075
if printed_local is True:
2077
print "You are missing %d revision(s):" % len(remote_extra)
2078
for data in iter_log_data(remote_extra, remote_branch.repository,
2081
if not remote_extra and not local_extra:
2083
print "Branches are up to date."
2086
if parent is None and other_branch is not None:
2087
local_branch.set_parent(other_branch)
2090
local_branch.unlock()
2092
remote_branch.unlock()
1394
2095
class cmd_plugins(Command):
1395
2096
"""List plugins"""
1398
2100
import bzrlib.plugin
1399
2101
from inspect import getdoc
1400
for plugin in bzrlib.plugin.all_plugins:
2102
for name, plugin in bzrlib.plugin.all_plugins().items():
1401
2103
if hasattr(plugin, '__path__'):
1402
2104
print plugin.__path__[0]
1403
2105
elif hasattr(plugin, '__file__'):
1410
2112
print '\t', d.split('\n')[0]
2115
class cmd_testament(Command):
2116
"""Show testament (signing-form) of a revision."""
2117
takes_options = ['revision', 'long']
2118
takes_args = ['branch?']
2120
def run(self, branch=u'.', revision=None, long=False):
2121
from bzrlib.testament import Testament
2122
b = WorkingTree.open_containing(branch)[0].branch
2125
if revision is None:
2126
rev_id = b.last_revision()
2128
rev_id = revision[0].in_history(b).rev_id
2129
t = Testament.from_revision(b.repository, rev_id)
2131
sys.stdout.writelines(t.as_text_lines())
2133
sys.stdout.write(t.as_short_text())
2138
class cmd_annotate(Command):
2139
"""Show the origin of each line in a file.
2141
This prints out the given file with an annotation on the left side
2142
indicating which revision, author and date introduced the change.
2144
If the origin is the same for a run of consecutive lines, it is
2145
shown only at the top, unless the --all option is given.
2147
# TODO: annotate directories; showing when each file was last changed
2148
# TODO: annotate a previous version of a file
2149
# TODO: if the working copy is modified, show annotations on that
2150
# with new uncommitted lines marked
2151
aliases = ['blame', 'praise']
2152
takes_args = ['filename']
2153
takes_options = [Option('all', help='show annotations on all lines'),
2154
Option('long', help='show date in annotations'),
2158
def run(self, filename, all=False, long=False):
2159
from bzrlib.annotate import annotate_file
2160
tree, relpath = WorkingTree.open_containing(filename)
2161
branch = tree.branch
2164
file_id = tree.inventory.path2id(relpath)
2165
tree = branch.repository.revision_tree(branch.last_revision())
2166
file_version = tree.inventory[file_id].revision
2167
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
2172
class cmd_re_sign(Command):
2173
"""Create a digital signature for an existing revision."""
2174
# TODO be able to replace existing ones.
2176
hidden = True # is this right ?
2177
takes_args = ['revision_id*']
2178
takes_options = ['revision']
2180
def run(self, revision_id_list=None, revision=None):
2181
import bzrlib.config as config
2182
import bzrlib.gpg as gpg
2183
if revision_id_list is not None and revision is not None:
2184
raise BzrCommandError('You can only supply one of revision_id or --revision')
2185
if revision_id_list is None and revision is None:
2186
raise BzrCommandError('You must supply either --revision or a revision_id')
2187
b = WorkingTree.open_containing(u'.')[0].branch
2188
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
2189
if revision_id_list is not None:
2190
for revision_id in revision_id_list:
2191
b.repository.sign_revision(revision_id, gpg_strategy)
2192
elif revision is not None:
2193
if len(revision) == 1:
2194
revno, rev_id = revision[0].in_history(b)
2195
b.repository.sign_revision(rev_id, gpg_strategy)
2196
elif len(revision) == 2:
2197
# are they both on rh- if so we can walk between them
2198
# might be nice to have a range helper for arbitrary
2199
# revision paths. hmm.
2200
from_revno, from_revid = revision[0].in_history(b)
2201
to_revno, to_revid = revision[1].in_history(b)
2202
if to_revid is None:
2203
to_revno = b.revno()
2204
if from_revno is None or to_revno is None:
2205
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
2206
for revno in range(from_revno, to_revno + 1):
2207
b.repository.sign_revision(b.get_rev_id(revno),
2210
raise BzrCommandError('Please supply either one revision, or a range.')
2213
class cmd_bind(Command):
2214
"""Bind the current branch to a master branch.
2216
After binding, commits must succeed on the master branch
2217
before they are executed on the local one.
2220
takes_args = ['location']
2223
def run(self, location=None):
2224
b, relpath = Branch.open_containing(u'.')
2225
b_other = Branch.open(location)
2228
except DivergedBranches:
2229
raise BzrCommandError('These branches have diverged.'
2230
' Try merging, and then bind again.')
2233
class cmd_unbind(Command):
2234
"""Bind the current branch to its parent.
2236
After unbinding, the local branch is considered independent.
2243
b, relpath = Branch.open_containing(u'.')
2245
raise BzrCommandError('Local branch is not bound')
2248
class cmd_uncommit(bzrlib.commands.Command):
2249
"""Remove the last committed revision.
2251
By supplying the --all flag, it will not only remove the entry
2252
from revision_history, but also remove all of the entries in the
2255
--verbose will print out what is being removed.
2256
--dry-run will go through all the motions, but not actually
2259
In the future, uncommit will create a changeset, which can then
2263
# TODO: jam 20060108 Add an option to allow uncommit to remove
2264
# unreferenced information in 'branch-as-repostory' branches.
2265
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
2266
# information in shared branches as well.
2267
takes_options = ['verbose', 'revision',
2268
Option('dry-run', help='Don\'t actually make changes'),
2269
Option('force', help='Say yes to all questions.')]
2270
takes_args = ['location?']
2273
def run(self, location=None,
2274
dry_run=False, verbose=False,
2275
revision=None, force=False):
2276
from bzrlib.branch import Branch
2277
from bzrlib.log import log_formatter
2279
from bzrlib.uncommit import uncommit
2281
if location is None:
2283
control, relpath = bzrdir.BzrDir.open_containing(location)
2284
b = control.open_branch()
2286
tree = control.open_workingtree()
2287
except (errors.NoWorkingTree, errors.NotLocalUrl):
2290
if revision is None:
2292
rev_id = b.last_revision()
2294
revno, rev_id = revision[0].in_history(b)
2296
print 'No revisions to uncommit.'
2298
for r in range(revno, b.revno()+1):
2299
rev_id = b.get_rev_id(r)
2300
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2301
lf.show(r, b.repository.get_revision(rev_id), None)
2304
print 'Dry-run, pretending to remove the above revisions.'
2306
val = raw_input('Press <enter> to continue')
2308
print 'The above revision(s) will be removed.'
2310
val = raw_input('Are you sure [y/N]? ')
2311
if val.lower() not in ('y', 'yes'):
2315
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
2319
class cmd_break_lock(Command):
2320
"""Break a dead lock on a repository, branch or working directory.
2322
CAUTION: Locks should only be broken when you are sure that the process
2323
holding the lock has been stopped.
2328
takes_args = ['location']
2329
takes_options = [Option('show',
2330
help="just show information on the lock, " \
2333
def run(self, location, show=False):
2334
d = bzrdir.BzrDir.open(location)
2335
repo = d.open_repository()
2336
if not repo.is_locked():
2337
raise errors.ObjectNotLocked(repo)
2340
# command-line interpretation helper for merge-related commands
2341
def merge(other_revision, base_revision,
2342
check_clean=True, ignore_zero=False,
2343
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2344
file_list=None, show_base=False, reprocess=False,
2345
pb=DummyProgress()):
2346
"""Merge changes into a tree.
2349
list(path, revno) Base for three-way merge.
2350
If [None, None] then a base will be automatically determined.
2352
list(path, revno) Other revision for three-way merge.
2354
Directory to merge changes into; '.' by default.
2356
If true, this_dir must have no uncommitted changes before the
2358
ignore_zero - If true, suppress the "zero conflicts" message when
2359
there are no conflicts; should be set when doing something we expect
2360
to complete perfectly.
2361
file_list - If supplied, merge only changes to selected files.
2363
All available ancestors of other_revision and base_revision are
2364
automatically pulled into the branch.
2366
The revno may be -1 to indicate the last revision on the branch, which is
2369
This function is intended for use from the command line; programmatic
2370
clients might prefer to call merge.merge_inner(), which has less magic
2373
from bzrlib.merge import Merger
2374
if this_dir is None:
2376
this_tree = WorkingTree.open_containing(this_dir)[0]
2377
if show_base and not merge_type is Merge3Merger:
2378
raise BzrCommandError("Show-base is not supported for this merge"
2379
" type. %s" % merge_type)
2380
if reprocess and not merge_type is Merge3Merger:
2381
raise BzrCommandError("Reprocess is not supported for this merge"
2382
" type. %s" % merge_type)
2383
if reprocess and show_base:
2384
raise BzrCommandError("Cannot reprocess and show base.")
2386
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2387
merger.pp = ProgressPhase("Merge phase", 5, pb)
2388
merger.pp.next_phase()
2389
merger.check_basis(check_clean)
2390
merger.set_other(other_revision)
2391
merger.pp.next_phase()
2392
merger.set_base(base_revision)
2393
if merger.base_rev_id == merger.other_rev_id:
2394
note('Nothing to do.')
2396
merger.backup_files = backup_files
2397
merger.merge_type = merge_type
2398
merger.set_interesting_files(file_list)
2399
merger.show_base = show_base
2400
merger.reprocess = reprocess
2401
conflicts = merger.do_merge()
2402
merger.set_pending()
2408
# these get imported and then picked up by the scan for cmd_*
2409
# TODO: Some more consistent way to split command definitions across files;
2410
# we do need to load at least some information about them to know of
2412
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2413
from bzrlib.sign_my_commits import cmd_sign_my_commits