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"""
19
# DO NOT change this to cStringIO - it results in control files
21
# FIXIT! (Only deal with byte streams OR unicode at any one layer.)
24
from StringIO import StringIO
29
from bzrlib import BZRDIR
30
from bzrlib.commands import Command, display_command
31
from bzrlib.branch import Branch
32
from bzrlib.revision import common_ancestor
33
import bzrlib.errors as errors
34
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError,
35
NotBranchError, DivergedBranches, NotConflicted,
36
NoSuchFile, NoWorkingTree, FileInWrongBranch)
37
from bzrlib.option import Option
38
from bzrlib.revisionspec import RevisionSpec
22
39
import bzrlib.trace
23
from bzrlib.trace import mutter, note, log_error, warning
24
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
25
from bzrlib.branch import find_branch
26
from bzrlib.revisionspec import RevisionSpec
27
from bzrlib import BZRDIR
28
from bzrlib.commands import Command
40
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
41
from bzrlib.workingtree import WorkingTree
42
from bzrlib.log import show_one_log
45
def tree_files(file_list, default_branch=u'.'):
47
return internal_tree_files(file_list, default_branch)
48
except FileInWrongBranch, e:
49
raise BzrCommandError("%s is not in the same branch as %s" %
50
(e.path, file_list[0]))
52
def internal_tree_files(file_list, default_branch=u'.'):
54
Return a branch and list of branch-relative paths.
55
If supplied file_list is empty or None, the branch default will be used,
56
and returned file_list will match the original.
58
if file_list is None or len(file_list) == 0:
59
return WorkingTree.open_containing(default_branch)[0], file_list
60
tree = WorkingTree.open_containing(file_list[0])[0]
62
for filename in file_list:
64
new_list.append(tree.relpath(filename))
65
except errors.PathNotChild:
66
raise FileInWrongBranch(tree.branch, filename)
70
# TODO: Make sure no commands unconditionally use the working directory as a
71
# branch. If a filename argument is used, the first of them should be used to
72
# specify the branch. (Perhaps this can be factored out into some kind of
73
# Argument class, representing a file in a branch, where the first occurrence
31
76
class cmd_status(Command):
32
77
"""Display status summary.
64
109
files or directories is reported. If a directory is given, status
65
110
is reported for everything inside that directory.
67
If a revision is specified, the changes since that revision are shown.
112
If a revision argument is given, the status is calculated against
113
that revision, or between two revisions if two are provided.
116
# TODO: --no-recurse, --recurse options
69
118
takes_args = ['file*']
70
119
takes_options = ['all', 'show-ids', 'revision']
71
120
aliases = ['st', 'stat']
73
def run(self, all=False, show_ids=False, file_list=None):
75
b = find_branch(file_list[0])
76
file_list = [b.relpath(x) for x in file_list]
77
# special case: only one path was given and it's the root
123
def run(self, all=False, show_ids=False, file_list=None, revision=None):
124
tree, file_list = tree_files(file_list)
84
126
from bzrlib.status import show_status
85
show_status(b, show_unchanged=all, show_ids=show_ids,
86
specific_files=file_list)
127
show_status(tree.branch, show_unchanged=all, show_ids=show_ids,
128
specific_files=file_list, revision=revision)
89
131
class cmd_cat_revision(Command):
90
"""Write out metadata for a revision."""
132
"""Write out metadata for a revision.
134
The revision to print can either be specified by a specific
135
revision identifier, or you can use --revision.
93
takes_args = ['revision_id']
139
takes_args = ['revision_id?']
140
takes_options = ['revision']
95
def run(self, revision_id):
97
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
143
def run(self, revision_id=None, revision=None):
145
if revision_id is not None and revision is not None:
146
raise BzrCommandError('You can only supply one of revision_id or --revision')
147
if revision_id is None and revision is None:
148
raise BzrCommandError('You must supply either --revision or a revision_id')
149
b = WorkingTree.open_containing(u'.')[0].branch
150
if revision_id is not None:
151
sys.stdout.write(b.get_revision_xml(revision_id))
152
elif revision is not None:
155
raise BzrCommandError('You cannot specify a NULL revision.')
156
revno, rev_id = rev.in_history(b)
157
sys.stdout.write(b.get_revision_xml(rev_id))
100
160
class cmd_revno(Command):
101
161
"""Show current revision number.
103
163
This is equal to the number of revisions on this branch."""
105
print find_branch('.').revno()
164
takes_args = ['location?']
166
def run(self, location=u'.'):
167
print Branch.open_containing(location)[0].revno()
108
170
class cmd_revision_info(Command):
146
213
Therefore simply saying 'bzr add' will version all files that
147
214
are currently unknown.
149
TODO: Perhaps adding a file whose directly is not versioned should
150
recursively add that parent, rather than giving an error?
216
Adding a file whose parent directory is not versioned will
217
implicitly add the parent, and so on up to the root. This means
218
you should never need to explictly add a directory, they'll just
219
get added when you add a file in the directory.
221
--dry-run will show which files would be added, but not actually
152
224
takes_args = ['file*']
153
takes_options = ['verbose', 'no-recurse']
155
def run(self, file_list, verbose=False, no_recurse=False):
156
# verbose currently has no effect
157
from bzrlib.add import smart_add, add_reporter_print
158
smart_add(file_list, not no_recurse, add_reporter_print)
225
takes_options = ['no-recurse', 'dry-run', 'verbose']
227
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
232
# This is pointless, but I'd rather not raise an error
233
action = bzrlib.add.add_action_null
235
action = bzrlib.add.add_action_print
237
action = bzrlib.add.add_action_add
239
action = bzrlib.add.add_action_add_and_print
241
added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
244
for glob in sorted(ignored.keys()):
245
match_len = len(ignored[glob])
247
for path in ignored[glob]:
248
print "ignored %s matching \"%s\"" % (path, glob)
250
print "ignored %d file(s) matching \"%s\"" % (match_len,
252
print "If you wish to add some of these files, please add them"\
162
256
class cmd_mkdir(Command):
182
273
takes_args = ['filename']
185
277
def run(self, filename):
186
print find_branch(filename).relpath(filename)
278
tree, relpath = WorkingTree.open_containing(filename)
190
282
class cmd_inventory(Command):
191
"""Show inventory of the current working copy or a revision."""
192
takes_options = ['revision', 'show-ids']
283
"""Show inventory of the current working copy or a revision.
285
It is possible to limit the output to a particular entry
286
type using the --kind option. For example; --kind file.
288
takes_options = ['revision', 'show-ids', 'kind']
194
def run(self, revision=None, show_ids=False):
197
inv = b.read_working_inventory()
291
def run(self, revision=None, show_ids=False, kind=None):
292
if kind and kind not in ['file', 'directory', 'symlink']:
293
raise BzrCommandError('invalid kind specified')
294
tree = WorkingTree.open_containing(u'.')[0]
296
inv = tree.read_working_inventory()
199
298
if len(revision) > 1:
200
299
raise BzrCommandError('bzr inventory --revision takes'
201
300
' exactly one revision identifier')
202
inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
301
inv = tree.branch.get_revision_inventory(
302
revision[0].in_history(tree.branch).rev_id)
204
304
for path, entry in inv.entries():
305
if kind and kind != entry.kind:
206
308
print '%-50s %s' % (path, entry.file_id)
263
363
def run(self, names_list):
264
364
if len(names_list) < 2:
265
365
raise BzrCommandError("missing file argument")
266
b = find_branch(names_list[0])
268
rel_names = [b.relpath(x) for x in names_list]
366
tree, rel_names = tree_files(names_list)
270
368
if os.path.isdir(names_list[-1]):
271
369
# move into existing directory
272
for pair in b.move(rel_names[:-1], rel_names[-1]):
370
for pair in tree.move(rel_names[:-1], rel_names[-1]):
273
371
print "%s => %s" % pair
275
373
if len(names_list) != 2:
276
374
raise BzrCommandError('to mv multiple files the destination '
277
375
'must be a versioned directory')
278
for pair in b.move(rel_names[0], rel_names[1]):
279
print "%s => %s" % pair
376
tree.rename_one(rel_names[0], rel_names[1])
377
print "%s => %s" % (rel_names[0], rel_names[1])
284
380
class cmd_pull(Command):
285
381
"""Pull any changes from another branch into the current one.
287
If the location is omitted, the last-used location will be used.
288
Both the revision history and the working directory will be
383
If there is no default location set, the first pull will set it. After
384
that, you can omit the location to use the default. To change the
385
default, use --remember.
291
387
This command only works on branches that have not diverged. Branches are
292
388
considered diverged if both branches have had commits without first
293
389
pulling from the other.
295
391
If branches have diverged, you can use 'bzr merge' to pull the text changes
296
from one into the other.
392
from one into the other. Once one branch has merged, the other should
393
be able to pull it again.
395
If you want to forget your local changes and just update your branch to
396
match the remote one, use --overwrite.
398
takes_options = ['remember', 'overwrite', 'verbose']
298
399
takes_args = ['location?']
300
def run(self, location=None):
401
def run(self, location=None, remember=False, overwrite=False, verbose=False):
301
402
from bzrlib.merge import merge
303
403
from shutil import rmtree
306
br_to = find_branch('.')
309
stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
311
if e.errno != errno.ENOENT:
405
# FIXME: too much stuff is in the command class
406
tree_to = WorkingTree.open_containing(u'.')[0]
407
stored_loc = tree_to.branch.get_parent()
313
408
if location is None:
314
409
if stored_loc is None:
315
410
raise BzrCommandError("No pull location known or specified.")
317
print "Using last location: %s" % stored_loc
318
location = stored_loc
319
cache_root = tempfile.mkdtemp()
320
from bzrlib.branch import DivergedBranches
321
br_from = find_branch(location)
322
location = br_from.base
323
old_revno = br_to.revno()
325
from branch import find_cached_branch, DivergedBranches
326
br_from = find_cached_branch(location, cache_root)
327
location = br_from.base
328
old_revno = br_to.revno()
412
print "Using saved location: %s" % stored_loc
413
location = stored_loc
415
br_from = Branch.open(location)
416
br_to = tree_to.branch
418
old_rh = br_to.revision_history()
419
count = tree_to.pull(br_from, overwrite)
421
if br_to.get_parent() is None or remember:
422
br_to.set_parent(location)
423
note('%d revision(s) pulled.' % (count,))
426
new_rh = tree_to.branch.revision_history()
429
from bzrlib.log import show_changed_revisions
430
show_changed_revisions(tree_to.branch, old_rh, new_rh)
433
class cmd_push(Command):
434
"""Push this branch into another branch.
436
The remote branch will not have its working tree populated because this
437
is both expensive, and may not be supported on the remote file system.
439
Some smart servers or protocols *may* put the working tree in place.
441
If there is no default push location set, the first push will set it.
442
After that, you can omit the location to use the default. To change the
443
default, use --remember.
445
This command only works on branches that have not diverged. Branches are
446
considered diverged if the branch being pushed to is not an older version
449
If branches have diverged, you can use 'bzr push --overwrite' to replace
450
the other branch completely.
452
If you want to ensure you have the different changes in the other branch,
453
do a merge (see bzr help merge) from the other branch, and commit that
454
before doing a 'push --overwrite'.
456
takes_options = ['remember', 'overwrite',
457
Option('create-prefix',
458
help='Create the path leading up to the branch '
459
'if it does not already exist')]
460
takes_args = ['location?']
462
def run(self, location=None, remember=False, overwrite=False,
463
create_prefix=False, verbose=False):
464
# FIXME: Way too big! Put this into a function called from the
467
from shutil import rmtree
468
from bzrlib.transport import get_transport
470
tree_from = WorkingTree.open_containing(u'.')[0]
471
br_from = tree_from.branch
472
stored_loc = tree_from.branch.get_push_location()
474
if stored_loc is None:
475
raise BzrCommandError("No push location known or specified.")
477
print "Using saved location: %s" % stored_loc
478
location = stored_loc
480
br_to = Branch.open(location)
481
except NotBranchError:
483
transport = get_transport(location).clone('..')
484
if not create_prefix:
486
transport.mkdir(transport.relpath(location))
488
raise BzrCommandError("Parent directory of %s "
489
"does not exist." % location)
491
current = transport.base
492
needed = [(transport, transport.relpath(location))]
495
transport, relpath = needed[-1]
496
transport.mkdir(relpath)
499
new_transport = transport.clone('..')
500
needed.append((new_transport,
501
new_transport.relpath(transport.base)))
502
if new_transport.base == transport.base:
503
raise BzrCommandError("Could not creeate "
505
br_to = Branch.initialize(location)
506
old_rh = br_to.revision_history()
330
br_to.update_revisions(br_from)
331
except DivergedBranches:
332
raise BzrCommandError("These branches have diverged."
335
merge(('.', -1), ('.', old_revno), check_clean=False)
336
if location != stored_loc:
337
br_to.controlfile("x-pull", "wb").write(location + "\n")
509
tree_to = br_to.working_tree()
510
except NoWorkingTree:
511
# TODO: This should be updated for branches which don't have a
512
# working tree, as opposed to ones where we just couldn't
514
warning('Unable to update the working tree of: %s' % (br_to.base,))
515
count = br_to.pull(br_from, overwrite)
517
count = tree_to.pull(br_from, overwrite)
518
except DivergedBranches:
519
raise BzrCommandError("These branches have diverged."
520
" Try a merge then push with overwrite.")
521
if br_from.get_push_location() is None or remember:
522
br_from.set_push_location(location)
523
note('%d revision(s) pushed.' % (count,))
526
new_rh = br_to.revision_history()
529
from bzrlib.log import show_changed_revisions
530
show_changed_revisions(br_to, old_rh, new_rh)
343
533
class cmd_branch(Command):
349
539
To retrieve the branch as of a particular revision, supply the --revision
350
540
parameter, as in "branch foo/bar -r 5".
542
--basis is to speed up branching from remote branches. When specified, it
543
copies all the file-contents, inventory and revision data from the basis
544
branch before copying anything from the remote branch.
352
546
takes_args = ['from_location', 'to_location?']
353
takes_options = ['revision']
547
takes_options = ['revision', 'basis', 'bound', 'unbound']
354
548
aliases = ['get', 'clone']
356
def run(self, from_location, to_location=None, revision=None):
357
from bzrlib.branch import copy_branch, find_cached_branch
550
def run(self, from_location, to_location=None, revision=None, basis=None,
551
bound=False, unbound=False):
552
from bzrlib.clone import copy_branch
360
554
from shutil import rmtree
361
cache_root = tempfile.mkdtemp()
365
elif len(revision) > 1:
366
raise BzrCommandError(
367
'bzr branch --revision takes exactly 1 revision value')
369
br_from = find_cached_branch(from_location, cache_root)
371
if e.errno == errno.ENOENT:
372
raise BzrCommandError('Source location "%s" does not'
373
' exist.' % to_location)
557
elif len(revision) > 1:
558
raise BzrCommandError(
559
'bzr branch --revision takes exactly 1 revision value')
560
if bound and unbound:
561
raise BzrCommandError('Cannot supply both bound and unbound at the same time')
563
br_from = Branch.open(from_location)
565
if e.errno == errno.ENOENT:
566
raise BzrCommandError('Source location "%s" does not'
567
' exist.' % to_location)
572
if basis is not None:
573
basis_branch = WorkingTree.open_containing(basis)[0].branch
576
if len(revision) == 1 and revision[0] is not None:
577
revision_id = revision[0].in_history(br_from)[1]
376
580
if to_location is None:
377
581
to_location = os.path.basename(from_location.rstrip("/\\"))
584
name = os.path.basename(to_location) + '\n'
379
586
os.mkdir(to_location)
380
587
except OSError, e:
390
copy_branch(br_from, to_location, revision[0])
597
copy_branch(br_from, to_location, revision_id, basis_branch)
391
598
except bzrlib.errors.NoSuchRevision:
392
599
rmtree(to_location)
393
msg = "The branch %s has no revision %d." % (from_location, revision[0])
394
raise BzrCommandError(msg)
600
msg = "The branch %s has no revision %s." % (from_location, revision[0])
601
raise BzrCommandError(msg)
602
except bzrlib.errors.UnlistableBranch:
604
msg = "The branch %s cannot be used as a --basis" % (basis,)
605
raise BzrCommandError(msg)
606
branch = Branch.open(to_location)
608
name = StringIO(name)
609
branch.put_controlfile('branch-name', name)
610
note('Branched %d revision(s).' % branch.revno())
399
617
class cmd_renames(Command):
400
618
"""Show list of renamed files.
402
TODO: Option to show renames between two historical versions.
404
TODO: Only show renames under dir, rather than in the whole branch.
620
# TODO: Option to show renames between two historical versions.
622
# TODO: Only show renames under dir, rather than in the whole branch.
406
623
takes_args = ['dir?']
408
def run(self, dir='.'):
410
old_inv = b.basis_tree().inventory
411
new_inv = b.read_working_inventory()
626
def run(self, dir=u'.'):
627
tree = WorkingTree.open_containing(dir)[0]
628
old_inv = tree.branch.basis_tree().inventory
629
new_inv = tree.read_working_inventory()
413
631
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
518
754
If files are listed, only the changes in those files are listed.
519
755
Otherwise, all changes for the tree are listed.
521
TODO: Allow diff across branches.
523
TODO: Option to use external diff command; could be GNU diff, wdiff,
526
TODO: Python difflib is not exactly the same as unidiff; should
527
either fix it up or prefer to use an external diff.
529
TODO: If a directory is given, diff everything under that.
531
TODO: Selected-file diff is inefficient and doesn't show you
534
TODO: This probably handles non-Unix newlines poorly.
762
# TODO: Allow diff across branches.
763
# TODO: Option to use external diff command; could be GNU diff, wdiff,
764
# or a graphical diff.
766
# TODO: Python difflib is not exactly the same as unidiff; should
767
# either fix it up or prefer to use an external diff.
769
# TODO: If a directory is given, diff everything under that.
771
# TODO: Selected-file diff is inefficient and doesn't show you
774
# TODO: This probably handles non-Unix newlines poorly.
542
776
takes_args = ['file*']
543
777
takes_options = ['revision', 'diff-options']
544
778
aliases = ['di', 'dif']
546
781
def run(self, revision=None, file_list=None, diff_options=None):
547
782
from bzrlib.diff import show_diff
550
b = find_branch(file_list[0])
551
file_list = [b.relpath(f) for f in file_list]
552
if file_list == ['']:
553
# just pointing to top-of-tree
784
tree, file_list = internal_tree_files(file_list)
787
except FileInWrongBranch:
788
if len(file_list) != 2:
789
raise BzrCommandError("Files are in different branches")
791
b, file1 = Branch.open_containing(file_list[0])
792
b2, file2 = Branch.open_containing(file_list[1])
793
if file1 != "" or file2 != "":
794
# FIXME diff those two files. rbc 20051123
795
raise BzrCommandError("Files are in different branches")
558
797
if revision is not None:
799
raise BzrCommandError("Can't specify -r with two branches")
559
800
if len(revision) == 1:
560
show_diff(b, revision[0], specific_files=file_list,
561
external_diff_options=diff_options)
801
return show_diff(tree.branch, revision[0], specific_files=file_list,
802
external_diff_options=diff_options)
562
803
elif len(revision) == 2:
563
show_diff(b, revision[0], specific_files=file_list,
564
external_diff_options=diff_options,
565
revision2=revision[1])
804
return show_diff(tree.branch, revision[0], specific_files=file_list,
805
external_diff_options=diff_options,
806
revision2=revision[1])
567
808
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
569
show_diff(b, None, specific_files=file_list,
570
external_diff_options=diff_options)
811
return show_diff(b, None, specific_files=file_list,
812
external_diff_options=diff_options, b2=b2)
814
return show_diff(tree.branch, None, specific_files=file_list,
815
external_diff_options=diff_options)
575
818
class cmd_deleted(Command):
576
819
"""List files deleted in the working tree.
578
TODO: Show files deleted since a previous revision, or between two revisions.
821
# TODO: Show files deleted since a previous revision, or
822
# between two revisions.
823
# TODO: Much more efficient way to do this: read in new
824
# directories with readdir, rather than stating each one. Same
825
# level of effort but possibly much less IO. (Or possibly not,
826
# if the directories are very large...)
580
828
def run(self, show_ids=False):
583
new = b.working_tree()
585
## TODO: Much more efficient way to do this: read in new
586
## directories with readdir, rather than stating each one. Same
587
## level of effort but possibly much less IO. (Or possibly not,
588
## if the directories are very large...)
829
tree = WorkingTree.open_containing(u'.')[0]
830
old = tree.branch.basis_tree()
590
831
for path, ie in old.inventory.iter_entries():
591
if not new.has_id(ie.file_id):
832
if not tree.has_id(ie.file_id):
593
834
print '%-50s %s' % (path, ie.file_id)
633
875
The root is the nearest enclosing directory with a .bzr control
635
877
takes_args = ['filename?']
636
879
def run(self, filename=None):
637
880
"""Print the branch root."""
638
b = find_branch(filename)
881
tree = WorkingTree.open_containing(filename)[0]
642
885
class cmd_log(Command):
643
886
"""Show log of this branch.
645
To request a range of logs, you can use the command -r begin:end
646
-r revision requests a specific revision, -r :end or -r begin: are
888
To request a range of logs, you can use the command -r begin..end
889
-r revision requests a specific revision, -r ..end or -r begin.. are
649
--message allows you to give a regular expression, which will be evaluated
650
so that only matching entries will be displayed.
652
TODO: Make --revision support uuid: and hash: [future tag:] notation.
893
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
656
895
takes_args = ['filename?']
657
takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
658
'long', 'message', 'short',]
896
takes_options = [Option('forward',
897
help='show from oldest to newest'),
898
'timezone', 'verbose',
899
'show-ids', 'revision',
902
help='show revisions whose message matches this regexp',
660
907
def run(self, filename=None, timezone='original',
668
916
from bzrlib.log import log_formatter, show_log
918
assert message is None or isinstance(message, basestring), \
919
"invalid message argument %r" % message
671
920
direction = (forward and 'forward') or 'reverse'
674
b = find_branch(filename)
675
fp = b.relpath(filename)
677
file_id = b.read_working_inventory().path2id(fp)
926
tree, fp = WorkingTree.open_containing(filename)
929
inv = tree.read_working_inventory()
930
except NotBranchError:
933
b, fp = Branch.open_containing(filename)
935
inv = b.get_inventory(b.last_revision())
937
file_id = inv.path2id(fp)
679
939
file_id = None # points to branch root
941
tree, relpath = WorkingTree.open_containing(u'.')
684
945
if revision is None:
687
948
elif len(revision) == 1:
688
rev1 = rev2 = RevisionSpec(b, revision[0]).revno
949
rev1 = rev2 = revision[0].in_history(b).revno
689
950
elif len(revision) == 2:
690
rev1 = RevisionSpec(b, revision[0]).revno
691
rev2 = RevisionSpec(b, revision[1]).revno
951
rev1 = revision[0].in_history(b).revno
952
rev2 = revision[1].in_history(b).revno
693
954
raise BzrCommandError('bzr log --revision takes one or two values.')
956
# By this point, the revision numbers are converted to the +ve
957
# form if they were supplied in the -ve form, so we can do
958
# this comparison in relative safety
960
(rev2, rev1) = (rev1, rev2)
700
mutter('encoding log as %r' % bzrlib.user_encoding)
962
mutter('encoding log as %r', bzrlib.user_encoding)
702
964
# use 'replace' so that we don't abort if trying to write out
703
965
# in e.g. the default C locale.
704
966
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
968
log_format = get_log_format(long=long, short=short, line=line)
710
969
lf = log_formatter(log_format,
711
970
show_ids=show_ids,
729
997
A more user-friendly interface is "bzr log FILE"."""
731
999
takes_args = ["filename"]
732
1001
def run(self, filename):
733
b = find_branch(filename)
734
inv = b.read_working_inventory()
735
file_id = inv.path2id(b.relpath(filename))
1002
tree, relpath = WorkingTree.open_containing(filename)
1004
inv = tree.read_working_inventory()
1005
file_id = inv.path2id(relpath)
736
1006
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
737
1007
print "%6d %s" % (revno, what)
740
1010
class cmd_ls(Command):
741
1011
"""List files in a tree.
743
TODO: Take a revision or remote path and list that tree instead.
1013
# TODO: Take a revision or remote path and list that tree instead.
746
def run(self, revision=None, verbose=False):
749
tree = b.working_tree()
751
tree = b.revision_tree(b.lookup_revision(revision))
753
for fp, fc, kind, fid in tree.list_files():
755
if kind == 'directory':
1015
takes_options = ['verbose', 'revision',
1016
Option('non-recursive',
1017
help='don\'t recurse into sub-directories'),
1019
help='Print all paths from the root of the branch.'),
1020
Option('unknown', help='Print unknown files'),
1021
Option('versioned', help='Print versioned files'),
1022
Option('ignored', help='Print ignored files'),
1024
Option('null', help='Null separate the files'),
1027
def run(self, revision=None, verbose=False,
1028
non_recursive=False, from_root=False,
1029
unknown=False, versioned=False, ignored=False,
1032
if verbose and null:
1033
raise BzrCommandError('Cannot set both --verbose and --null')
1034
all = not (unknown or versioned or ignored)
1036
selection = {'I':ignored, '?':unknown, 'V':versioned}
1038
tree, relpath = WorkingTree.open_containing(u'.')
1043
if revision is not None:
1044
tree = tree.branch.revision_tree(
1045
revision[0].in_history(tree.branch).rev_id)
1046
for fp, fc, kind, fid, entry in tree.list_files():
1047
if fp.startswith(relpath):
1048
fp = fp[len(relpath):]
1049
if non_recursive and '/' in fp:
1051
if not all and not selection[fc]:
1054
kindch = entry.kind_character()
1055
print '%-8s %s%s' % (fc, fp, kindch)
1057
sys.stdout.write(fp)
1058
sys.stdout.write('\0')
762
print '%-8s %s%s' % (fc, fp, kindch)
768
1064
class cmd_unknowns(Command):
769
1065
"""List unknown files."""
771
1068
from bzrlib.osutils import quotefn
772
for f in find_branch('.').unknowns():
1069
for f in WorkingTree.open_containing(u'.')[0].unknowns():
773
1070
print quotefn(f)
777
1073
class cmd_ignore(Command):
778
1074
"""Ignore a command or pattern.
780
1076
To remove patterns from the ignore list, edit the .bzrignore file.
782
1078
If the pattern contains a slash, it is compared to the whole path
783
from the branch root. Otherwise, it is comapred to only the last
784
component of the path.
1079
from the branch root. Otherwise, it is compared to only the last
1080
component of the path. To match a file only in the root directory,
786
1083
Ignore patterns are case-insensitive on case-insensitive systems.
874
1173
is found exports to a directory (equivalent to --format=dir).
876
1175
Root may be the top directory for tar, tgz and tbz2 formats. If none
877
is given, the top directory will be the root name of the file."""
878
# TODO: list known exporters
1176
is given, the top directory will be the root name of the file.
1178
Note: export of tree with non-ascii filenames to zip is not supported.
1180
Supported formats Autodetected by extension
1181
----------------- -------------------------
1184
tbz2 .tar.bz2, .tbz2
879
1188
takes_args = ['dest']
880
1189
takes_options = ['revision', 'format', 'root']
881
1190
def run(self, dest, revision=None, format=None, root=None):
1192
from bzrlib.export import export
1193
tree = WorkingTree.open_containing(u'.')[0]
884
1195
if revision is None:
885
rev_id = b.last_patch()
1196
# should be tree.last_revision FIXME
1197
rev_id = b.last_revision()
887
1199
if len(revision) != 1:
888
1200
raise BzrError('bzr export --revision takes exactly 1 argument')
889
rev_id = RevisionSpec(b, revision[0]).rev_id
1201
rev_id = revision[0].in_history(b).rev_id
890
1202
t = b.revision_tree(rev_id)
891
root, ext = os.path.splitext(dest)
895
elif ext in (".gz", ".tgz"):
897
elif ext in (".bz2", ".tbz2"):
901
t.export(dest, format, root)
1204
export(t, dest, format, root)
1205
except errors.NoSuchExportFormat, e:
1206
raise BzrCommandError('Unsupported export format: %s' % e.format)
904
1209
class cmd_cat(Command):
936
1253
A selected-file commit may fail in some cases where the committed
937
1254
tree would be invalid, such as trying to commit a file in a
938
1255
newly-added directory that is not itself committed.
940
TODO: Run hooks on tree to-be-committed, and after commit.
942
TODO: Strict commit that fails if there are unknown or deleted files.
1257
# TODO: Run hooks on tree to-be-committed, and after commit.
1259
# TODO: Strict commit that fails if there are deleted files.
1260
# (what does "deleted files" mean ??)
1262
# TODO: Give better message for -s, --summary, used by tla people
1264
# XXX: verbose currently does nothing
944
1266
takes_args = ['selected*']
945
takes_options = ['message', 'file', 'verbose', 'unchanged']
1267
takes_options = ['message', 'verbose',
1269
help='commit even if nothing has changed'),
1270
Option('file', type=str,
1272
help='file containing commit message'),
1274
help="refuse to commit if there are unknown "
1275
"files in the working tree."),
946
1277
aliases = ['ci', 'checkin']
948
# TODO: Give better message for -s, --summary, used by tla people
950
1279
def run(self, message=None, file=None, verbose=True, selected_list=None,
952
from bzrlib.errors import PointlessCommit
953
from bzrlib.msgeditor import edit_commit_message
1280
unchanged=False, strict=False):
1281
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1283
from bzrlib.msgeditor import edit_commit_message, \
1284
make_commit_message_template
954
1285
from bzrlib.status import show_status
955
from cStringIO import StringIO
959
selected_list = [b.relpath(s) for s in selected_list]
961
if not message and not file:
963
show_status(b, specific_files=selected_list,
965
message = edit_commit_message(catcher.getvalue())
1286
from tempfile import TemporaryFile
1289
# TODO: Need a blackbox test for invoking the external editor; may be
1290
# slightly problematic to run this cross-platform.
1292
# TODO: do more checks that the commit will succeed before
1293
# spending the user's valuable time typing a commit message.
1295
# TODO: if the commit *does* happen to fail, then save the commit
1296
# message to a temporary file where it can be recovered
1297
tree, selected_list = tree_files(selected_list)
1298
if message is None and not file:
1299
template = make_commit_message_template(tree, selected_list)
1300
message = edit_commit_message(template)
967
1301
if message is None:
968
1302
raise BzrCommandError("please specify a commit message"
969
1303
" with either --message or --file")
1028
1377
The check command or bzr developers may sometimes advise you to run
1380
This version of this command upgrades from the full-text storage
1381
used by bzr 0.0.8 and earlier to the weave format (v5).
1031
1383
takes_args = ['dir?']
1033
def run(self, dir='.'):
1385
def run(self, dir=u'.'):
1034
1386
from bzrlib.upgrade import upgrade
1035
upgrade(find_branch(dir))
1039
1390
class cmd_whoami(Command):
1040
1391
"""Show bzr user id."""
1041
1392
takes_options = ['email']
1043
1395
def run(self, email=False):
1045
b = bzrlib.branch.find_branch('.')
1397
b = WorkingTree.open_containing(u'.')[0].branch
1398
config = bzrlib.config.BranchConfig(b)
1399
except NotBranchError:
1400
config = bzrlib.config.GlobalConfig()
1050
print bzrlib.osutils.user_email(b)
1052
print bzrlib.osutils.username(b)
1403
print config.user_email()
1405
print config.username()
1407
class cmd_nick(Command):
1409
Print or set the branch nickname.
1410
If unset, the tree root directory name is used as the nickname
1411
To print the current nickname, execute with no argument.
1413
takes_args = ['nickname?']
1414
def run(self, nickname=None):
1415
branch = Branch.open_containing(u'.')[0]
1416
if nickname is None:
1417
self.printme(branch)
1419
branch.nick = nickname
1422
def printme(self, branch):
1055
1425
class cmd_selftest(Command):
1056
"""Run internal test suite"""
1426
"""Run internal test suite.
1428
This creates temporary test directories in the working directory,
1429
but not existing data is affected. These directories are deleted
1430
if the tests pass, or left behind to help in debugging if they
1431
fail and --keep-output is specified.
1433
If arguments are given, they are regular expressions that say
1434
which tests should run.
1436
# TODO: --list should give a list of all available tests
1058
takes_options = ['verbose', 'pattern']
1059
def run(self, verbose=False, pattern=".*"):
1438
takes_args = ['testspecs*']
1439
takes_options = ['verbose',
1440
Option('one', help='stop when one test fails'),
1441
Option('keep-output',
1442
help='keep output directories when tests fail')
1445
def run(self, testspecs_list=None, verbose=False, one=False,
1060
1447
import bzrlib.ui
1061
from bzrlib.selftest import selftest
1448
from bzrlib.tests import selftest
1062
1449
# we don't want progress meters from the tests to go to the
1063
1450
# real output; and we don't want log messages cluttering up
1064
1451
# the real logs.
1170
1585
--force is given.
1172
1587
takes_args = ['branch?']
1173
takes_options = ['revision', 'force', 'merge-type']
1588
takes_options = ['revision', 'force', 'merge-type', 'reprocess',
1589
Option('show-base', help="Show base revision text in "
1175
def run(self, branch='.', revision=None, force=False,
1592
def run(self, branch=None, revision=None, force=False, merge_type=None,
1593
show_base=False, reprocess=False):
1177
1594
from bzrlib.merge import merge
1178
1595
from bzrlib.merge_core import ApplyMerge3
1179
1596
if merge_type is None:
1180
1597
merge_type = ApplyMerge3
1599
branch = WorkingTree.open_containing(u'.')[0].branch.get_parent()
1601
raise BzrCommandError("No merge location known or specified.")
1603
print "Using saved location: %s" % branch
1182
1604
if revision is None or len(revision) < 1:
1183
1605
base = [None, None]
1184
1606
other = [branch, -1]
1186
1608
if len(revision) == 1:
1187
other = [branch, revision[0]]
1188
1609
base = [None, None]
1610
other_branch = Branch.open_containing(branch)[0]
1611
revno = revision[0].in_history(other_branch).revno
1612
other = [branch, revno]
1190
1614
assert len(revision) == 2
1191
1615
if None in revision:
1192
1616
raise BzrCommandError(
1193
1617
"Merge doesn't permit that revision specifier.")
1194
base = [branch, revision[0]]
1195
other = [branch, revision[1]]
1618
b = Branch.open_containing(branch)[0]
1620
base = [branch, revision[0].in_history(b).revno]
1621
other = [branch, revision[1].in_history(b).revno]
1198
merge(other, base, check_clean=(not force), merge_type=merge_type)
1624
conflict_count = merge(other, base, check_clean=(not force),
1625
merge_type=merge_type, reprocess=reprocess,
1626
show_base=show_base)
1627
if conflict_count != 0:
1199
1631
except bzrlib.errors.AmbiguousBase, e:
1200
1632
m = ("sorry, bzr can't determine the right merge base yet\n"
1201
1633
"candidates are:\n "
1641
class cmd_remerge(Command):
1644
takes_args = ['file*']
1645
takes_options = ['merge-type', 'reprocess',
1646
Option('show-base', help="Show base revision text in "
1649
def run(self, file_list=None, merge_type=None, show_base=False,
1651
from bzrlib.merge import merge_inner, transform_tree
1652
from bzrlib.merge_core import ApplyMerge3
1653
if merge_type is None:
1654
merge_type = ApplyMerge3
1655
tree, file_list = tree_files(file_list)
1658
pending_merges = tree.pending_merges()
1659
if len(pending_merges) != 1:
1660
raise BzrCommandError("Sorry, remerge only works after normal"
1661
+ " merges. Not cherrypicking or"
1663
base_revision = common_ancestor(tree.branch.last_revision(),
1664
pending_merges[0], tree.branch)
1665
base_tree = tree.branch.revision_tree(base_revision)
1666
other_tree = tree.branch.revision_tree(pending_merges[0])
1667
interesting_ids = None
1668
if file_list is not None:
1669
interesting_ids = set()
1670
for filename in file_list:
1671
file_id = tree.path2id(filename)
1672
interesting_ids.add(file_id)
1673
if tree.kind(file_id) != "directory":
1676
for name, ie in tree.inventory.iter_entries(file_id):
1677
interesting_ids.add(ie.file_id)
1678
transform_tree(tree, tree.branch.basis_tree(), interesting_ids)
1679
if file_list is None:
1680
restore_files = list(tree.iter_conflicts())
1682
restore_files = file_list
1683
for filename in restore_files:
1685
restore(tree.abspath(filename))
1686
except NotConflicted:
1688
conflicts = merge_inner(tree.branch, other_tree, base_tree,
1689
interesting_ids = interesting_ids,
1690
other_rev_id=pending_merges[0],
1691
merge_type=merge_type,
1692
show_base=show_base,
1693
reprocess=reprocess)
1209
1701
class cmd_revert(Command):
1210
1702
"""Reverse all changes since the last commit.
1268
1762
aliases = ['s-c']
1271
1766
def run(self, context=None):
1272
1767
import shellcomplete
1273
1768
shellcomplete.shellcomplete(context)
1771
class cmd_fetch(Command):
1772
"""Copy in history from another branch but don't merge it.
1774
This is an internal method used for pull and merge."""
1776
takes_args = ['from_branch', 'to_branch']
1777
def run(self, from_branch, to_branch):
1778
from bzrlib.fetch import Fetcher
1779
from bzrlib.branch import Branch
1780
from_b = Branch.open(from_branch)
1781
to_b = Branch.open(to_branch)
1786
Fetcher(to_b, from_b)
1276
1793
class cmd_missing(Command):
1277
"""What is missing in this branch relative to other branch.
1279
takes_args = ['remote?']
1280
aliases = ['mis', 'miss']
1281
# We don't have to add quiet to the list, because
1282
# unknown options are parsed as booleans
1283
takes_options = ['verbose', 'quiet']
1285
def run(self, remote=None, verbose=False, quiet=False):
1286
from bzrlib.errors import BzrCommandError
1287
from bzrlib.missing import show_missing
1289
if verbose and quiet:
1290
raise BzrCommandError('Cannot pass both quiet and verbose')
1292
b = find_branch('.')
1293
parent = b.get_parent()
1794
"""Show unmerged/unpulled revisions between two branches.
1796
OTHER_BRANCH may be local or remote."""
1797
takes_args = ['other_branch?']
1798
takes_options = [Option('reverse', 'Reverse the order of revisions'),
1800
'Display changes in the local branch only'),
1801
Option('theirs-only',
1802
'Display changes in the remote branch only'),
1810
def run(self, other_branch=None, reverse=False, mine_only=False,
1811
theirs_only=False, long=True, short=False, line=False,
1812
show_ids=False, verbose=False):
1813
from bzrlib.missing import find_unmerged, iter_log_data
1814
from bzrlib.log import log_formatter
1815
local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
1816
parent = local_branch.get_parent()
1817
if other_branch is None:
1818
other_branch = parent
1819
if other_branch is None:
1296
1820
raise BzrCommandError("No missing location known or specified.")
1299
print "Using last location: %s" % parent
1301
elif parent is None:
1302
# We only update x-pull if it did not exist, missing should not change the parent
1303
b.controlfile('x-pull', 'wb').write(remote + '\n')
1304
br_remote = find_branch(remote)
1306
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1821
print "Using last location: " + local_branch.get_parent()
1822
remote_branch = bzrlib.branch.Branch.open(other_branch)
1823
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
1824
log_format = get_log_format(long=long, short=short, line=line)
1825
lf = log_formatter(log_format, sys.stdout,
1827
show_timezone='original')
1828
if reverse is False:
1829
local_extra.reverse()
1830
remote_extra.reverse()
1831
if local_extra and not theirs_only:
1832
print "You have %d extra revision(s):" % len(local_extra)
1833
for data in iter_log_data(local_extra, local_branch, verbose):
1835
printed_local = True
1837
printed_local = False
1838
if remote_extra and not mine_only:
1839
if printed_local is True:
1841
print "You are missing %d revision(s):" % len(remote_extra)
1842
for data in iter_log_data(remote_extra, remote_branch, verbose):
1844
if not remote_extra and not local_extra:
1846
print "Branches are up to date."
1849
if parent is None and other_branch is not None:
1850
local_branch.set_parent(other_branch)
1310
1854
class cmd_plugins(Command):
1311
1855
"""List plugins"""
1314
1859
import bzrlib.plugin
1315
1860
from inspect import getdoc
1316
for plugin in bzrlib.plugin.all_plugins:
1861
for name, plugin in bzrlib.plugin.all_plugins().items():
1317
1862
if hasattr(plugin, '__path__'):
1318
1863
print plugin.__path__[0]
1319
1864
elif hasattr(plugin, '__file__'):
1326
1871
print '\t', d.split('\n')[0]
1874
class cmd_testament(Command):
1875
"""Show testament (signing-form) of a revision."""
1876
takes_options = ['revision', 'long']
1877
takes_args = ['branch?']
1879
def run(self, branch=u'.', revision=None, long=False):
1880
from bzrlib.testament import Testament
1881
b = WorkingTree.open_containing(branch)[0].branch
1884
if revision is None:
1885
rev_id = b.last_revision()
1887
rev_id = revision[0].in_history(b).rev_id
1888
t = Testament.from_revision(b, rev_id)
1890
sys.stdout.writelines(t.as_text_lines())
1892
sys.stdout.write(t.as_short_text())
1897
class cmd_annotate(Command):
1898
"""Show the origin of each line in a file.
1900
This prints out the given file with an annotation on the left side
1901
indicating which revision, author and date introduced the change.
1903
If the origin is the same for a run of consecutive lines, it is
1904
shown only at the top, unless the --all option is given.
1906
# TODO: annotate directories; showing when each file was last changed
1907
# TODO: annotate a previous version of a file
1908
# TODO: if the working copy is modified, show annotations on that
1909
# with new uncommitted lines marked
1910
aliases = ['blame', 'praise']
1911
takes_args = ['filename']
1912
takes_options = [Option('all', help='show annotations on all lines'),
1913
Option('long', help='show date in annotations'),
1917
def run(self, filename, all=False, long=False):
1918
from bzrlib.annotate import annotate_file
1919
tree, relpath = WorkingTree.open_containing(filename)
1920
branch = tree.branch
1923
file_id = tree.inventory.path2id(relpath)
1924
tree = branch.revision_tree(branch.last_revision())
1925
file_version = tree.inventory[file_id].revision
1926
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
1931
class cmd_re_sign(Command):
1932
"""Create a digital signature for an existing revision."""
1933
# TODO be able to replace existing ones.
1935
hidden = True # is this right ?
1936
takes_args = ['revision_id?']
1937
takes_options = ['revision']
1939
def run(self, revision_id=None, revision=None):
1940
import bzrlib.config as config
1941
import bzrlib.gpg as gpg
1942
if revision_id is not None and revision is not None:
1943
raise BzrCommandError('You can only supply one of revision_id or --revision')
1944
if revision_id is None and revision is None:
1945
raise BzrCommandError('You must supply either --revision or a revision_id')
1946
b = WorkingTree.open_containing(u'.')[0].branch
1947
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1948
if revision_id is not None:
1949
b.sign_revision(revision_id, gpg_strategy)
1950
elif revision is not None:
1951
if len(revision) == 1:
1952
revno, rev_id = revision[0].in_history(b)
1953
b.sign_revision(rev_id, gpg_strategy)
1954
elif len(revision) == 2:
1955
# are they both on rh- if so we can walk between them
1956
# might be nice to have a range helper for arbitrary
1957
# revision paths. hmm.
1958
from_revno, from_revid = revision[0].in_history(b)
1959
to_revno, to_revid = revision[1].in_history(b)
1960
if to_revid is None:
1961
to_revno = b.revno()
1962
if from_revno is None or to_revno is None:
1963
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
1964
for revno in range(from_revno, to_revno + 1):
1965
b.sign_revision(b.get_rev_id(revno), gpg_strategy)
1967
raise BzrCommandError('Please supply either one revision, or a range.')
1970
class cmd_bind(Command):
1971
"""Bind the current branch to its parent.
1973
After binding, commits must succeed on the parent branch
1974
before they can be done on the local one.
1977
takes_args = ['location?']
1980
def run(self, location=None):
1981
b, relpath = Branch.open_containing(u'.')
1982
if location is None:
1983
location = b.get_bound_location()
1984
if location is None:
1985
location = b.get_parent()
1986
if location is None:
1987
raise BzrCommandError('Branch has no parent,'
1988
' you must supply a bind location.')
1989
b_other = Branch.open(location)
1992
except DivergedBranches:
1993
raise BzrCommandError('These branches have diverged.'
1994
' Try merging, and then bind again.')
1997
class cmd_unbind(Command):
1998
"""Bind the current branch to its parent.
2000
After unbinding, the local branch is considered independent.
2007
b, relpath = Branch.open_containing(u'.')
2009
raise BzrCommandError('Local branch is not bound')
2012
class cmd_update(Command):
2013
"""Update the local tree for checkouts and bound branches.
2016
wt, relpath = WorkingTree.open_containing(u'.')
2017
# TODO: jam 20051127 Check here to see if this is a checkout
2018
bound_loc = wt.branch.get_bound_location()
2020
raise BzrCommandError('Working tree %s is not a checkout'
2021
' or a bound branch, you probably'
2022
' want pull' % wt.base)
2024
br_bound = Branch.open(bound_loc)
2026
wt.pull(br_bound, overwrite=False)
2027
except DivergedBranches:
2028
raise BzrCommandError("These branches have diverged."
2032
class cmd_uncommit(bzrlib.commands.Command):
2033
"""Remove the last committed revision.
2035
By supplying the --all flag, it will not only remove the entry
2036
from revision_history, but also remove all of the entries in the
2039
--verbose will print out what is being removed.
2040
--dry-run will go through all the motions, but not actually
2043
In the future, uncommit will create a changeset, which can then
2046
takes_options = ['all', 'verbose', 'revision',
2047
Option('dry-run', help='Don\'t actually make changes'),
2048
Option('force', help='Say yes to all questions.')]
2049
takes_args = ['location?']
2052
def run(self, location=None, all=False,
2053
dry_run=False, verbose=False,
2054
revision=None, force=False):
2055
from bzrlib.branch import Branch
2056
from bzrlib.log import log_formatter
2058
from bzrlib.uncommit import uncommit
2060
if location is None:
2062
b, relpath = Branch.open_containing(location)
2064
if revision is None:
2066
rev_id = b.last_revision()
2068
revno, rev_id = revision[0].in_history(b)
2070
print 'No revisions to uncommit.'
2072
for r in range(revno, b.revno()+1):
2073
rev_id = b.get_rev_id(r)
2074
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2075
lf.show(r, b.get_revision(rev_id), None)
2078
print 'Dry-run, pretending to remove the above revisions.'
2080
val = raw_input('Press <enter> to continue')
2082
print 'The above revision(s) will be removed.'
2084
val = raw_input('Are you sure [y/N]? ')
2085
if val.lower() not in ('y', 'yes'):
2089
uncommit(b, remove_files=all,
2090
dry_run=dry_run, verbose=verbose,
2094
# these get imported and then picked up by the scan for cmd_*
2095
# TODO: Some more consistent way to split command definitions across files;
2096
# we do need to load at least some information about them to know of
2098
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore