1
# Copyright (C) 2004, 2005 by Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# DO NOT change this to cStringIO - it results in control files
19
# FIXIT! (Only deal with byte streams OR unicode at any one layer.)
21
from StringIO import StringIO
26
from bzrlib import BZRDIR
27
from bzrlib.commands import Command, display_command
28
from bzrlib.branch import Branch
29
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
30
from bzrlib.errors import DivergedBranches, NoSuchFile, NoWorkingTree
31
from bzrlib.option import Option
32
from bzrlib.revisionspec import RevisionSpec
34
from bzrlib.trace import mutter, note, log_error, warning
35
from bzrlib.workingtree import WorkingTree
38
def tree_files(file_list, default_branch='.'):
40
Return a branch and list of branch-relative paths.
41
If supplied file_list is empty or None, the branch default will be used,
42
and returned file_list will match the original.
44
if file_list is None or len(file_list) == 0:
45
return WorkingTree.open_containing(default_branch)[0], file_list
46
tree = WorkingTree.open_containing(file_list[0])[0]
48
for filename in file_list:
50
new_list.append(tree.relpath(filename))
51
except NotBranchError:
52
raise BzrCommandError("%s is not in the same tree as %s" %
53
(filename, file_list[0]))
57
# TODO: Make sure no commands unconditionally use the working directory as a
58
# branch. If a filename argument is used, the first of them should be used to
59
# specify the branch. (Perhaps this can be factored out into some kind of
60
# Argument class, representing a file in a branch, where the first occurrence
63
class cmd_status(Command):
64
"""Display status summary.
66
This reports on versioned and unknown files, reporting them
67
grouped by state. Possible states are:
70
Versioned in the working copy but not in the previous revision.
73
Versioned in the previous revision but removed or deleted
77
Path of this file changed from the previous revision;
78
the text may also have changed. This includes files whose
79
parent directory was renamed.
82
Text has changed since the previous revision.
85
Nothing about this file has changed since the previous revision.
86
Only shown with --all.
89
Not versioned and not matching an ignore pattern.
91
To see ignored files use 'bzr ignored'. For details in the
92
changes to file texts, use 'bzr diff'.
94
If no arguments are specified, the status of the entire working
95
directory is shown. Otherwise, only the status of the specified
96
files or directories is reported. If a directory is given, status
97
is reported for everything inside that directory.
99
If a revision argument is given, the status is calculated against
100
that revision, or between two revisions if two are provided.
103
# XXX: FIXME: bzr status should accept a -r option to show changes
104
# relative to a revision, or between revisions
106
# TODO: --no-recurse, --recurse options
108
takes_args = ['file*']
109
takes_options = ['all', 'show-ids']
110
aliases = ['st', 'stat']
113
def run(self, all=False, show_ids=False, file_list=None, revision=None):
114
tree, file_list = tree_files(file_list)
116
from bzrlib.status import show_status
117
show_status(tree.branch, show_unchanged=all, show_ids=show_ids,
118
specific_files=file_list, revision=revision)
121
class cmd_cat_revision(Command):
122
"""Write out metadata for a revision.
124
The revision to print can either be specified by a specific
125
revision identifier, or you can use --revision.
129
takes_args = ['revision_id?']
130
takes_options = ['revision']
133
def run(self, revision_id=None, revision=None):
135
if revision_id is not None and revision is not None:
136
raise BzrCommandError('You can only supply one of revision_id or --revision')
137
if revision_id is None and revision is None:
138
raise BzrCommandError('You must supply either --revision or a revision_id')
139
b = WorkingTree.open_containing('.')[0].branch
140
if revision_id is not None:
141
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
142
elif revision is not None:
145
raise BzrCommandError('You cannot specify a NULL revision.')
146
revno, rev_id = rev.in_history(b)
147
sys.stdout.write(b.get_revision_xml_file(rev_id).read())
150
class cmd_revno(Command):
151
"""Show current revision number.
153
This is equal to the number of revisions on this branch."""
156
print Branch.open_containing('.')[0].revno()
159
class cmd_revision_info(Command):
160
"""Show revision number and revision id for a given revision identifier.
163
takes_args = ['revision_info*']
164
takes_options = ['revision']
166
def run(self, revision=None, revision_info_list=[]):
169
if revision is not None:
170
revs.extend(revision)
171
if revision_info_list is not None:
172
for rev in revision_info_list:
173
revs.append(RevisionSpec(rev))
175
raise BzrCommandError('You must supply a revision identifier')
177
b = WorkingTree.open_containing('.')[0].branch
180
revinfo = rev.in_history(b)
181
if revinfo.revno is None:
182
print ' %s' % revinfo.rev_id
184
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
187
class cmd_add(Command):
188
"""Add specified files or directories.
190
In non-recursive mode, all the named items are added, regardless
191
of whether they were previously ignored. A warning is given if
192
any of the named files are already versioned.
194
In recursive mode (the default), files are treated the same way
195
but the behaviour for directories is different. Directories that
196
are already versioned do not give a warning. All directories,
197
whether already versioned or not, are searched for files or
198
subdirectories that are neither versioned or ignored, and these
199
are added. This search proceeds recursively into versioned
200
directories. If no names are given '.' is assumed.
202
Therefore simply saying 'bzr add' will version all files that
203
are currently unknown.
205
Adding a file whose parent directory is not versioned will
206
implicitly add the parent, and so on up to the root. This means
207
you should never need to explictly add a directory, they'll just
208
get added when you add a file in the directory.
210
takes_args = ['file*']
211
takes_options = ['no-recurse', 'quiet']
213
def run(self, file_list, no_recurse=False, quiet=False):
214
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
216
reporter = add_reporter_null
218
reporter = add_reporter_print
219
smart_add(file_list, not no_recurse, reporter)
222
class cmd_mkdir(Command):
223
"""Create a new versioned directory.
225
This is equivalent to creating the directory and then adding it.
227
takes_args = ['dir+']
229
def run(self, dir_list):
232
wt, dd = WorkingTree.open_containing(d)
237
class cmd_relpath(Command):
238
"""Show path of a file relative to root"""
239
takes_args = ['filename']
243
def run(self, filename):
244
tree, relpath = WorkingTree.open_containing(filename)
248
class cmd_inventory(Command):
249
"""Show inventory of the current working copy or a revision."""
250
takes_options = ['revision', 'show-ids']
253
def run(self, revision=None, show_ids=False):
254
tree = WorkingTree.open_containing('.')[0]
256
inv = tree.read_working_inventory()
258
if len(revision) > 1:
259
raise BzrCommandError('bzr inventory --revision takes'
260
' exactly one revision identifier')
261
inv = tree.branch.get_revision_inventory(
262
revision[0].in_history(tree.branch).rev_id)
264
for path, entry in inv.entries():
266
print '%-50s %s' % (path, entry.file_id)
271
class cmd_move(Command):
272
"""Move files to a different directory.
277
The destination must be a versioned directory in the same branch.
279
takes_args = ['source$', 'dest']
280
def run(self, source_list, dest):
281
tree, source_list = tree_files(source_list)
282
# TODO: glob expansion on windows?
283
tree.move(source_list, tree.relpath(dest))
286
class cmd_rename(Command):
287
"""Change the name of an entry.
290
bzr rename frob.c frobber.c
291
bzr rename src/frob.c lib/frob.c
293
It is an error if the destination name exists.
295
See also the 'move' command, which moves files into a different
296
directory without changing their name.
298
# TODO: Some way to rename multiple files without invoking
299
# bzr for each one?"""
300
takes_args = ['from_name', 'to_name']
302
def run(self, from_name, to_name):
303
tree, (from_name, to_name) = tree_files((from_name, to_name))
304
tree.rename_one(from_name, to_name)
307
class cmd_mv(Command):
308
"""Move or rename a file.
311
bzr mv OLDNAME NEWNAME
312
bzr mv SOURCE... DESTINATION
314
If the last argument is a versioned directory, all the other names
315
are moved into it. Otherwise, there must be exactly two arguments
316
and the file is changed to a new name, which must not already exist.
318
Files cannot be moved between branches.
320
takes_args = ['names*']
321
def run(self, names_list):
322
if len(names_list) < 2:
323
raise BzrCommandError("missing file argument")
324
tree, rel_names = tree_files(names_list)
326
if os.path.isdir(names_list[-1]):
327
# move into existing directory
328
for pair in tree.move(rel_names[:-1], rel_names[-1]):
329
print "%s => %s" % pair
331
if len(names_list) != 2:
332
raise BzrCommandError('to mv multiple files the destination '
333
'must be a versioned directory')
334
tree.rename_one(rel_names[0], rel_names[1])
335
print "%s => %s" % (rel_names[0], rel_names[1])
338
class cmd_pull(Command):
339
"""Pull any changes from another branch into the current one.
341
If there is no default location set, the first pull will set it. After
342
that, you can omit the location to use the default. To change the
343
default, use --remember.
345
This command only works on branches that have not diverged. Branches are
346
considered diverged if both branches have had commits without first
347
pulling from the other.
349
If branches have diverged, you can use 'bzr merge' to pull the text changes
350
from one into the other. Once one branch has merged, the other should
351
be able to pull it again.
353
If you want to forget your local changes and just update your branch to
354
match the remote one, use --overwrite.
356
takes_options = ['remember', 'overwrite', 'verbose']
357
takes_args = ['location?']
359
def run(self, location=None, remember=False, overwrite=False, verbose=False):
360
from bzrlib.merge import merge
361
from shutil import rmtree
364
tree_to = WorkingTree.open_containing('.')[0]
365
stored_loc = tree_to.branch.get_parent()
367
if stored_loc is None:
368
raise BzrCommandError("No pull location known or specified.")
370
print "Using saved location: %s" % stored_loc
371
location = stored_loc
372
br_from = Branch.open(location)
374
old_rh = tree_to.branch.revision_history()
375
tree_to.pull(br_from, overwrite)
376
except DivergedBranches:
377
raise BzrCommandError("These branches have diverged."
379
if tree_to.branch.get_parent() is None or remember:
380
tree_to.branch.set_parent(location)
383
new_rh = tree_to.branch.revision_history()
386
from bzrlib.log import show_changed_revisions
387
show_changed_revisions(tree_to.branch, old_rh, new_rh)
390
class cmd_push(Command):
391
"""Push this branch into another branch.
393
The remote branch will not have its working tree populated because this
394
is both expensive, and may not be supported on the remote file system.
396
Some smart servers or protocols *may* put the working tree in place.
398
If there is no default push location set, the first push will set it.
399
After that, you can omit the location to use the default. To change the
400
default, use --remember.
402
This command only works on branches that have not diverged. Branches are
403
considered diverged if the branch being pushed to is not an older version
406
If branches have diverged, you can use 'bzr push --overwrite' to replace
407
the other branch completely.
409
If you want to ensure you have the different changes in the other branch,
410
do a merge (see bzr help merge) from the other branch, and commit that
411
before doing a 'push --overwrite'.
413
takes_options = ['remember', 'overwrite',
414
Option('create-prefix',
415
help='Create the path leading up to the branch '
416
'if it does not already exist')]
417
takes_args = ['location?']
419
def run(self, location=None, remember=False, overwrite=False,
420
create_prefix=False, verbose=False):
422
from shutil import rmtree
423
from bzrlib.transport import get_transport
425
tree_from = WorkingTree.open_containing('.')[0]
426
stored_loc = tree_from.branch.get_push_location()
428
if stored_loc is None:
429
raise BzrCommandError("No push location known or specified.")
431
print "Using saved location: %s" % stored_loc
432
location = stored_loc
434
br_to = Branch.open(location)
435
except NotBranchError:
437
transport = get_transport(location).clone('..')
438
if not create_prefix:
440
transport.mkdir(transport.relpath(location))
442
raise BzrCommandError("Parent directory of %s "
443
"does not exist." % location)
445
current = transport.base
446
needed = [(transport, transport.relpath(location))]
449
transport, relpath = needed[-1]
450
transport.mkdir(relpath)
453
new_transport = transport.clone('..')
454
needed.append((new_transport,
455
new_transport.relpath(transport.base)))
456
if new_transport.base == transport.base:
457
raise BzrCommandError("Could not creeate "
461
br_to = Branch.initialize(location)
463
old_rh = br_to.revision_history()
464
br_to.pull(tree_from.branch, overwrite)
465
except DivergedBranches:
466
raise BzrCommandError("These branches have diverged."
467
" Try a merge then push with overwrite.")
468
if tree_from.branch.get_push_location() is None or remember:
469
tree_from.branch.set_push_location(location)
472
new_rh = br_to.revision_history()
475
from bzrlib.log import show_changed_revisions
476
show_changed_revisions(br_to, old_rh, new_rh)
479
class cmd_branch(Command):
480
"""Create a new copy of a branch.
482
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
483
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
485
To retrieve the branch as of a particular revision, supply the --revision
486
parameter, as in "branch foo/bar -r 5".
488
--basis is to speed up branching from remote branches. When specified, it
489
copies all the file-contents, inventory and revision data from the basis
490
branch before copying anything from the remote branch.
492
takes_args = ['from_location', 'to_location?']
493
takes_options = ['revision', 'basis']
494
aliases = ['get', 'clone']
496
def run(self, from_location, to_location=None, revision=None, basis=None):
497
from bzrlib.clone import copy_branch
499
from shutil import rmtree
502
elif len(revision) > 1:
503
raise BzrCommandError(
504
'bzr branch --revision takes exactly 1 revision value')
506
br_from = Branch.open(from_location)
508
if e.errno == errno.ENOENT:
509
raise BzrCommandError('Source location "%s" does not'
510
' exist.' % to_location)
515
if basis is not None:
516
basis_branch = WorkingTree.open_containing(basis)[0].branch
519
if len(revision) == 1 and revision[0] is not None:
520
revision_id = revision[0].in_history(br_from)[1]
523
if to_location is None:
524
to_location = os.path.basename(from_location.rstrip("/\\"))
527
name = os.path.basename(to_location) + '\n'
529
os.mkdir(to_location)
531
if e.errno == errno.EEXIST:
532
raise BzrCommandError('Target directory "%s" already'
533
' exists.' % to_location)
534
if e.errno == errno.ENOENT:
535
raise BzrCommandError('Parent of "%s" does not exist.' %
540
copy_branch(br_from, to_location, revision_id, basis_branch)
541
except bzrlib.errors.NoSuchRevision:
543
msg = "The branch %s has no revision %s." % (from_location, revision[0])
544
raise BzrCommandError(msg)
545
except bzrlib.errors.UnlistableBranch:
547
msg = "The branch %s cannot be used as a --basis"
548
raise BzrCommandError(msg)
550
branch = Branch.open(to_location)
551
name = StringIO(name)
552
branch.put_controlfile('branch-name', name)
557
class cmd_renames(Command):
558
"""Show list of renamed files.
560
# TODO: Option to show renames between two historical versions.
562
# TODO: Only show renames under dir, rather than in the whole branch.
563
takes_args = ['dir?']
566
def run(self, dir='.'):
567
tree = WorkingTree.open_containing(dir)[0]
568
old_inv = tree.branch.basis_tree().inventory
569
new_inv = tree.read_working_inventory()
571
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
573
for old_name, new_name in renames:
574
print "%s => %s" % (old_name, new_name)
577
class cmd_info(Command):
578
"""Show statistical information about a branch."""
579
takes_args = ['branch?']
582
def run(self, branch=None):
584
b = WorkingTree.open_containing(branch)[0].branch
588
class cmd_remove(Command):
589
"""Make a file unversioned.
591
This makes bzr stop tracking changes to a versioned file. It does
592
not delete the working copy.
594
takes_args = ['file+']
595
takes_options = ['verbose']
598
def run(self, file_list, verbose=False):
599
tree, file_list = tree_files(file_list)
600
tree.remove(file_list, verbose=verbose)
603
class cmd_file_id(Command):
604
"""Print file_id of a particular file or directory.
606
The file_id is assigned when the file is first added and remains the
607
same through all revisions where the file exists, even when it is
611
takes_args = ['filename']
613
def run(self, filename):
614
tree, relpath = WorkingTree.open_containing(filename)
615
i = tree.inventory.path2id(relpath)
617
raise BzrError("%r is not a versioned file" % filename)
622
class cmd_file_path(Command):
623
"""Print path of file_ids to a file or directory.
625
This prints one line for each directory down to the target,
626
starting at the branch root."""
628
takes_args = ['filename']
630
def run(self, filename):
631
tree, relpath = WorkingTree.open_containing(filename)
633
fid = inv.path2id(relpath)
635
raise BzrError("%r is not a versioned file" % filename)
636
for fip in inv.get_idpath(fid):
640
class cmd_revision_history(Command):
641
"""Display list of revision ids on this branch."""
645
branch = WorkingTree.open_containing('.')[0].branch
646
for patchid in branch.revision_history():
650
class cmd_ancestry(Command):
651
"""List all revisions merged into this branch."""
655
tree = WorkingTree.open_containing('.')[0]
657
# FIXME. should be tree.last_revision
658
for revision_id in b.get_ancestry(b.last_revision()):
662
class cmd_directories(Command):
663
"""Display list of versioned directories in this tree."""
666
for name, ie in (WorkingTree.open_containing('.')[0].
667
read_working_inventory().directories()):
674
class cmd_init(Command):
675
"""Make a directory into a versioned branch.
677
Use this to create an empty branch, or before importing an
680
Recipe for importing a tree of files:
685
bzr commit -m 'imported project'
687
takes_args = ['location?']
688
def run(self, location=None):
689
from bzrlib.branch import Branch
693
# The path has to exist to initialize a
694
# branch inside of it.
695
# Just using os.mkdir, since I don't
696
# believe that we want to create a bunch of
697
# locations if the user supplies an extended path
698
if not os.path.exists(location):
700
Branch.initialize(location)
703
class cmd_diff(Command):
704
"""Show differences in working tree.
706
If files are listed, only the changes in those files are listed.
707
Otherwise, all changes for the tree are listed.
714
# TODO: Allow diff across branches.
715
# TODO: Option to use external diff command; could be GNU diff, wdiff,
716
# or a graphical diff.
718
# TODO: Python difflib is not exactly the same as unidiff; should
719
# either fix it up or prefer to use an external diff.
721
# TODO: If a directory is given, diff everything under that.
723
# TODO: Selected-file diff is inefficient and doesn't show you
726
# TODO: This probably handles non-Unix newlines poorly.
728
takes_args = ['file*']
729
takes_options = ['revision', 'diff-options']
730
aliases = ['di', 'dif']
733
def run(self, revision=None, file_list=None, diff_options=None):
734
from bzrlib.diff import show_diff
736
tree, file_list = tree_files(file_list)
737
if revision is not None:
738
if len(revision) == 1:
739
return show_diff(tree.branch, revision[0], specific_files=file_list,
740
external_diff_options=diff_options)
741
elif len(revision) == 2:
742
return show_diff(tree.branch, revision[0], specific_files=file_list,
743
external_diff_options=diff_options,
744
revision2=revision[1])
746
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
748
return show_diff(tree.branch, None, specific_files=file_list,
749
external_diff_options=diff_options)
752
class cmd_deleted(Command):
753
"""List files deleted in the working tree.
755
# TODO: Show files deleted since a previous revision, or
756
# between two revisions.
757
# TODO: Much more efficient way to do this: read in new
758
# directories with readdir, rather than stating each one. Same
759
# level of effort but possibly much less IO. (Or possibly not,
760
# if the directories are very large...)
762
def run(self, show_ids=False):
763
tree = WorkingTree.open_containing('.')[0]
764
old = tree.branch.basis_tree()
765
for path, ie in old.inventory.iter_entries():
766
if not tree.has_id(ie.file_id):
768
print '%-50s %s' % (path, ie.file_id)
773
class cmd_modified(Command):
774
"""List files modified in working tree."""
778
from bzrlib.delta import compare_trees
780
tree = WorkingTree.open_containing('.')[0]
781
td = compare_trees(tree.branch.basis_tree(), tree)
783
for path, id, kind, text_modified, meta_modified in td.modified:
788
class cmd_added(Command):
789
"""List files added in working tree."""
793
wt = WorkingTree.open_containing('.')[0]
794
basis_inv = wt.branch.basis_tree().inventory
797
if file_id in basis_inv:
799
path = inv.id2path(file_id)
800
if not os.access(b.abspath(path), os.F_OK):
806
class cmd_root(Command):
807
"""Show the tree root directory.
809
The root is the nearest enclosing directory with a .bzr control
811
takes_args = ['filename?']
813
def run(self, filename=None):
814
"""Print the branch root."""
815
tree = WorkingTree.open_containing(filename)[0]
819
class cmd_log(Command):
820
"""Show log of this branch.
822
To request a range of logs, you can use the command -r begin..end
823
-r revision requests a specific revision, -r ..end or -r begin.. are
827
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
829
takes_args = ['filename?']
830
takes_options = [Option('forward',
831
help='show from oldest to newest'),
832
'timezone', 'verbose',
833
'show-ids', 'revision',
834
Option('line', help='format with one line per revision'),
837
help='show revisions whose message matches this regexp',
839
Option('short', help='use moderately short format'),
842
def run(self, filename=None, timezone='original',
851
from bzrlib.log import log_formatter, show_log
853
assert message is None or isinstance(message, basestring), \
854
"invalid message argument %r" % message
855
direction = (forward and 'forward') or 'reverse'
861
tree, fp = WorkingTree.open_containing(filename)
864
inv = tree.read_working_inventory()
865
except NotBranchError:
868
b, fp = Branch.open_containing(filename)
870
inv = b.get_inventory(b.last_revision())
872
file_id = inv.path2id(fp)
874
file_id = None # points to branch root
876
tree, relpath = WorkingTree.open_containing('.')
883
elif len(revision) == 1:
884
rev1 = rev2 = revision[0].in_history(b).revno
885
elif len(revision) == 2:
886
rev1 = revision[0].in_history(b).revno
887
rev2 = revision[1].in_history(b).revno
889
raise BzrCommandError('bzr log --revision takes one or two values.')
896
mutter('encoding log as %r', bzrlib.user_encoding)
898
# use 'replace' so that we don't abort if trying to write out
899
# in e.g. the default C locale.
900
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
907
lf = log_formatter(log_format,
910
show_timezone=timezone)
923
class cmd_touching_revisions(Command):
924
"""Return revision-ids which affected a particular file.
926
A more user-friendly interface is "bzr log FILE"."""
928
takes_args = ["filename"]
930
def run(self, filename):
931
tree, relpath = WorkingTree.open_containing(filename)
933
inv = tree.read_working_inventory()
934
file_id = inv.path2id(relpath)
935
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
936
print "%6d %s" % (revno, what)
939
class cmd_ls(Command):
940
"""List files in a tree.
942
# TODO: Take a revision or remote path and list that tree instead.
944
takes_options = ['verbose', 'revision',
945
Option('non-recursive',
946
help='don\'t recurse into sub-directories'),
948
help='Print all paths from the root of the branch.'),
949
Option('unknown', help='Print unknown files'),
950
Option('versioned', help='Print versioned files'),
951
Option('ignored', help='Print ignored files'),
953
Option('null', help='Null separate the files'),
956
def run(self, revision=None, verbose=False,
957
non_recursive=False, from_root=False,
958
unknown=False, versioned=False, ignored=False,
962
raise BzrCommandError('Cannot set both --verbose and --null')
963
all = not (unknown or versioned or ignored)
965
selection = {'I':ignored, '?':unknown, 'V':versioned}
967
tree, relpath = WorkingTree.open_containing('.')
972
if revision is not None:
973
tree = tree.branch.revision_tree(
974
revision[0].in_history(tree.branch).rev_id)
975
for fp, fc, kind, fid, entry in tree.list_files():
976
if fp.startswith(relpath):
977
fp = fp[len(relpath):]
978
if non_recursive and '/' in fp:
980
if not all and not selection[fc]:
983
kindch = entry.kind_character()
984
print '%-8s %s%s' % (fc, fp, kindch)
987
sys.stdout.write('\0')
993
class cmd_unknowns(Command):
994
"""List unknown files."""
997
from bzrlib.osutils import quotefn
998
for f in WorkingTree.open_containing('.')[0].unknowns():
1002
class cmd_ignore(Command):
1003
"""Ignore a command or pattern.
1005
To remove patterns from the ignore list, edit the .bzrignore file.
1007
If the pattern contains a slash, it is compared to the whole path
1008
from the branch root. Otherwise, it is compared to only the last
1009
component of the path. To match a file only in the root directory,
1012
Ignore patterns are case-insensitive on case-insensitive systems.
1014
Note: wildcards must be quoted from the shell on Unix.
1017
bzr ignore ./Makefile
1018
bzr ignore '*.class'
1020
# TODO: Complain if the filename is absolute
1021
takes_args = ['name_pattern']
1023
def run(self, name_pattern):
1024
from bzrlib.atomicfile import AtomicFile
1027
tree, relpath = WorkingTree.open_containing('.')
1028
ifn = tree.abspath('.bzrignore')
1030
if os.path.exists(ifn):
1033
igns = f.read().decode('utf-8')
1039
# TODO: If the file already uses crlf-style termination, maybe
1040
# we should use that for the newly added lines?
1042
if igns and igns[-1] != '\n':
1044
igns += name_pattern + '\n'
1047
f = AtomicFile(ifn, 'wt')
1048
f.write(igns.encode('utf-8'))
1053
inv = tree.inventory
1054
if inv.path2id('.bzrignore'):
1055
mutter('.bzrignore is already versioned')
1057
mutter('need to make new .bzrignore file versioned')
1058
tree.add(['.bzrignore'])
1061
class cmd_ignored(Command):
1062
"""List ignored files and the patterns that matched them.
1064
See also: bzr ignore"""
1067
tree = WorkingTree.open_containing('.')[0]
1068
for path, file_class, kind, file_id, entry in tree.list_files():
1069
if file_class != 'I':
1071
## XXX: Slightly inefficient since this was already calculated
1072
pat = tree.is_ignored(path)
1073
print '%-50s %s' % (path, pat)
1076
class cmd_lookup_revision(Command):
1077
"""Lookup the revision-id from a revision-number
1080
bzr lookup-revision 33
1083
takes_args = ['revno']
1086
def run(self, revno):
1090
raise BzrCommandError("not a valid revision-number: %r" % revno)
1092
print WorkingTree.open_containing('.')[0].branch.get_rev_id(revno)
1095
class cmd_export(Command):
1096
"""Export past revision to destination directory.
1098
If no revision is specified this exports the last committed revision.
1100
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1101
given, try to find the format with the extension. If no extension
1102
is found exports to a directory (equivalent to --format=dir).
1104
Root may be the top directory for tar, tgz and tbz2 formats. If none
1105
is given, the top directory will be the root name of the file."""
1106
# TODO: list known exporters
1107
takes_args = ['dest']
1108
takes_options = ['revision', 'format', 'root']
1109
def run(self, dest, revision=None, format=None, root=None):
1111
tree = WorkingTree.open_containing('.')[0]
1113
if revision is None:
1114
# should be tree.last_revision FIXME
1115
rev_id = tree.branch.last_revision()
1117
if len(revision) != 1:
1118
raise BzrError('bzr export --revision takes exactly 1 argument')
1119
rev_id = revision[0].in_history(b).rev_id
1120
t = b.revision_tree(rev_id)
1121
arg_root, ext = os.path.splitext(os.path.basename(dest))
1122
if ext in ('.gz', '.bz2'):
1123
new_root, new_ext = os.path.splitext(arg_root)
1124
if new_ext == '.tar':
1130
if ext in (".tar",):
1132
elif ext in (".tar.gz", ".tgz"):
1134
elif ext in (".tar.bz2", ".tbz2"):
1138
t.export(dest, format, root)
1141
class cmd_cat(Command):
1142
"""Write a file's text from a previous revision."""
1144
takes_options = ['revision']
1145
takes_args = ['filename']
1148
def run(self, filename, revision=None):
1149
if revision is None:
1150
raise BzrCommandError("bzr cat requires a revision number")
1151
elif len(revision) != 1:
1152
raise BzrCommandError("bzr cat --revision takes exactly one number")
1155
tree, relpath = WorkingTree.open_containing(filename)
1157
except NotBranchError:
1160
b, relpath = Branch.open_containing(filename)
1161
b.print_file(relpath, revision[0].in_history(b).revno)
1164
class cmd_local_time_offset(Command):
1165
"""Show the offset in seconds from GMT to local time."""
1169
print bzrlib.osutils.local_time_offset()
1173
class cmd_commit(Command):
1174
"""Commit changes into a new revision.
1176
If no arguments are given, the entire tree is committed.
1178
If selected files are specified, only changes to those files are
1179
committed. If a directory is specified then the directory and everything
1180
within it is committed.
1182
A selected-file commit may fail in some cases where the committed
1183
tree would be invalid, such as trying to commit a file in a
1184
newly-added directory that is not itself committed.
1186
# TODO: Run hooks on tree to-be-committed, and after commit.
1188
# TODO: Strict commit that fails if there are deleted files.
1189
# (what does "deleted files" mean ??)
1191
# TODO: Give better message for -s, --summary, used by tla people
1193
# XXX: verbose currently does nothing
1195
takes_args = ['selected*']
1196
takes_options = ['message', 'verbose',
1198
help='commit even if nothing has changed'),
1199
Option('file', type=str,
1201
help='file containing commit message'),
1203
help="refuse to commit if there are unknown "
1204
"files in the working tree."),
1206
aliases = ['ci', 'checkin']
1208
def run(self, message=None, file=None, verbose=True, selected_list=None,
1209
unchanged=False, strict=False):
1210
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1212
from bzrlib.msgeditor import edit_commit_message
1213
from bzrlib.status import show_status
1214
from cStringIO import StringIO
1216
tree, selected_list = tree_files(selected_list)
1217
if message is None and not file:
1218
catcher = StringIO()
1219
show_status(tree.branch, specific_files=selected_list,
1221
message = edit_commit_message(catcher.getvalue())
1224
raise BzrCommandError("please specify a commit message"
1225
" with either --message or --file")
1226
elif message and file:
1227
raise BzrCommandError("please specify either --message or --file")
1231
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1234
raise BzrCommandError("empty commit message specified")
1237
tree.commit(message, specific_files=selected_list,
1238
allow_pointless=unchanged, strict=strict)
1239
except PointlessCommit:
1240
# FIXME: This should really happen before the file is read in;
1241
# perhaps prepare the commit; get the message; then actually commit
1242
raise BzrCommandError("no changes to commit",
1243
["use --unchanged to commit anyhow"])
1244
except ConflictsInTree:
1245
raise BzrCommandError("Conflicts detected in working tree. "
1246
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1247
except StrictCommitFailed:
1248
raise BzrCommandError("Commit refused because there are unknown "
1249
"files in the working tree.")
1252
class cmd_check(Command):
1253
"""Validate consistency of branch history.
1255
This command checks various invariants about the branch storage to
1256
detect data corruption or bzr bugs.
1258
takes_args = ['dir?']
1259
takes_options = ['verbose']
1261
def run(self, dir='.', verbose=False):
1262
from bzrlib.check import check
1263
check(WorkingTree.open_containing(dir)[0].branch, verbose)
1266
class cmd_scan_cache(Command):
1269
from bzrlib.hashcache import HashCache
1275
print '%6d stats' % c.stat_count
1276
print '%6d in hashcache' % len(c._cache)
1277
print '%6d files removed from cache' % c.removed_count
1278
print '%6d hashes updated' % c.update_count
1279
print '%6d files changed too recently to cache' % c.danger_count
1286
class cmd_upgrade(Command):
1287
"""Upgrade branch storage to current format.
1289
The check command or bzr developers may sometimes advise you to run
1292
This version of this command upgrades from the full-text storage
1293
used by bzr 0.0.8 and earlier to the weave format (v5).
1295
takes_args = ['dir?']
1297
def run(self, dir='.'):
1298
from bzrlib.upgrade import upgrade
1302
class cmd_whoami(Command):
1303
"""Show bzr user id."""
1304
takes_options = ['email']
1307
def run(self, email=False):
1309
b = WorkingTree.open_containing('.')[0].branch
1310
config = bzrlib.config.BranchConfig(b)
1311
except NotBranchError:
1312
config = bzrlib.config.GlobalConfig()
1315
print config.user_email()
1317
print config.username()
1320
class cmd_selftest(Command):
1321
"""Run internal test suite.
1323
This creates temporary test directories in the working directory,
1324
but not existing data is affected. These directories are deleted
1325
if the tests pass, or left behind to help in debugging if they
1328
If arguments are given, they are regular expressions that say
1329
which tests should run.
1331
# TODO: --list should give a list of all available tests
1333
takes_args = ['testspecs*']
1334
takes_options = ['verbose',
1335
Option('one', help='stop when one test fails'),
1338
def run(self, testspecs_list=None, verbose=False, one=False):
1340
from bzrlib.selftest import selftest
1341
# we don't want progress meters from the tests to go to the
1342
# real output; and we don't want log messages cluttering up
1344
save_ui = bzrlib.ui.ui_factory
1345
bzrlib.trace.info('running tests...')
1347
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1348
if testspecs_list is not None:
1349
pattern = '|'.join(testspecs_list)
1352
result = selftest(verbose=verbose,
1354
stop_on_failure=one)
1356
bzrlib.trace.info('tests passed')
1358
bzrlib.trace.info('tests failed')
1359
return int(not result)
1361
bzrlib.ui.ui_factory = save_ui
1365
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1366
# is bzrlib itself in a branch?
1367
bzrrev = bzrlib.get_bzr_revision()
1369
print " (bzr checkout, revision %d {%s})" % bzrrev
1370
print bzrlib.__copyright__
1371
print "http://bazaar-ng.org/"
1373
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1374
print "you may use, modify and redistribute it under the terms of the GNU"
1375
print "General Public License version 2 or later."
1378
class cmd_version(Command):
1379
"""Show version of bzr."""
1384
class cmd_rocks(Command):
1385
"""Statement of optimism."""
1389
print "it sure does!"
1392
class cmd_find_merge_base(Command):
1393
"""Find and print a base revision for merging two branches.
1395
# TODO: Options to specify revisions on either side, as if
1396
# merging only part of the history.
1397
takes_args = ['branch', 'other']
1401
def run(self, branch, other):
1402
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1404
branch1 = Branch.open_containing(branch)[0]
1405
branch2 = Branch.open_containing(other)[0]
1407
history_1 = branch1.revision_history()
1408
history_2 = branch2.revision_history()
1410
last1 = branch1.last_revision()
1411
last2 = branch2.last_revision()
1413
source = MultipleRevisionSources(branch1, branch2)
1415
base_rev_id = common_ancestor(last1, last2, source)
1417
print 'merge base is revision %s' % base_rev_id
1421
if base_revno is None:
1422
raise bzrlib.errors.UnrelatedBranches()
1424
print ' r%-6d in %s' % (base_revno, branch)
1426
other_revno = branch2.revision_id_to_revno(base_revid)
1428
print ' r%-6d in %s' % (other_revno, other)
1432
class cmd_merge(Command):
1433
"""Perform a three-way merge.
1435
The branch is the branch you will merge from. By default, it will
1436
merge the latest revision. If you specify a revision, that
1437
revision will be merged. If you specify two revisions, the first
1438
will be used as a BASE, and the second one as OTHER. Revision
1439
numbers are always relative to the specified branch.
1441
By default bzr will try to merge in all new work from the other
1442
branch, automatically determining an appropriate base. If this
1443
fails, you may need to give an explicit base.
1447
To merge the latest revision from bzr.dev
1448
bzr merge ../bzr.dev
1450
To merge changes up to and including revision 82 from bzr.dev
1451
bzr merge -r 82 ../bzr.dev
1453
To merge the changes introduced by 82, without previous changes:
1454
bzr merge -r 81..82 ../bzr.dev
1456
merge refuses to run if there are any uncommitted changes, unless
1459
takes_args = ['branch?']
1460
takes_options = ['revision', 'force', 'merge-type', 'reprocess',
1461
Option('show-base', help="Show base revision text in "
1464
def run(self, branch=None, revision=None, force=False, merge_type=None,
1465
show_base=False, reprocess=False):
1466
from bzrlib.merge import merge
1467
from bzrlib.merge_core import ApplyMerge3
1468
if merge_type is None:
1469
merge_type = ApplyMerge3
1471
branch = WorkingTree.open_containing('.')[0].branch.get_parent()
1473
raise BzrCommandError("No merge location known or specified.")
1475
print "Using saved location: %s" % branch
1476
if revision is None or len(revision) < 1:
1478
other = [branch, -1]
1480
if len(revision) == 1:
1482
other_branch = Branch.open_containing(branch)[0]
1483
revno = revision[0].in_history(other_branch).revno
1484
other = [branch, revno]
1486
assert len(revision) == 2
1487
if None in revision:
1488
raise BzrCommandError(
1489
"Merge doesn't permit that revision specifier.")
1490
b = Branch.open_containing(branch)[0]
1492
base = [branch, revision[0].in_history(b).revno]
1493
other = [branch, revision[1].in_history(b).revno]
1496
conflict_count = merge(other, base, check_clean=(not force),
1497
merge_type=merge_type, reprocess=reprocess,
1498
show_base=show_base)
1499
if conflict_count != 0:
1503
except bzrlib.errors.AmbiguousBase, e:
1504
m = ("sorry, bzr can't determine the right merge base yet\n"
1505
"candidates are:\n "
1506
+ "\n ".join(e.bases)
1508
"please specify an explicit base with -r,\n"
1509
"and (if you want) report this to the bzr developers\n")
1513
class cmd_revert(Command):
1514
"""Reverse all changes since the last commit.
1516
Only versioned files are affected. Specify filenames to revert only
1517
those files. By default, any files that are changed will be backed up
1518
first. Backup files have a '~' appended to their name.
1520
takes_options = ['revision', 'no-backup']
1521
takes_args = ['file*']
1522
aliases = ['merge-revert']
1524
def run(self, revision=None, no_backup=False, file_list=None):
1525
from bzrlib.merge import merge_inner
1526
from bzrlib.commands import parse_spec
1527
if file_list is not None:
1528
if len(file_list) == 0:
1529
raise BzrCommandError("No files specified")
1532
if revision is None:
1534
tree = WorkingTree.open_containing('.')[0]
1535
# FIXME should be tree.last_revision
1536
rev_id = tree.branch.last_revision()
1537
elif len(revision) != 1:
1538
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1540
tree, file_list = tree_files(file_list)
1541
rev_id = revision[0].in_history(tree.branch).rev_id
1542
tree.revert(file_list, tree.branch.revision_tree(rev_id),
1546
class cmd_assert_fail(Command):
1547
"""Test reporting of assertion failures"""
1550
assert False, "always fails"
1553
class cmd_help(Command):
1554
"""Show help on a command or other topic.
1556
For a list of all available commands, say 'bzr help commands'."""
1557
takes_options = ['long']
1558
takes_args = ['topic?']
1562
def run(self, topic=None, long=False):
1564
if topic is None and long:
1569
class cmd_shell_complete(Command):
1570
"""Show appropriate completions for context.
1572
For a list of all available commands, say 'bzr shell-complete'."""
1573
takes_args = ['context?']
1578
def run(self, context=None):
1579
import shellcomplete
1580
shellcomplete.shellcomplete(context)
1583
class cmd_fetch(Command):
1584
"""Copy in history from another branch but don't merge it.
1586
This is an internal method used for pull and merge."""
1588
takes_args = ['from_branch', 'to_branch']
1589
def run(self, from_branch, to_branch):
1590
from bzrlib.fetch import Fetcher
1591
from bzrlib.branch import Branch
1592
from_b = Branch.open(from_branch)
1593
to_b = Branch.open(to_branch)
1598
Fetcher(to_b, from_b)
1605
class cmd_missing(Command):
1606
"""What is missing in this branch relative to other branch.
1608
# TODO: rewrite this in terms of ancestry so that it shows only
1611
takes_args = ['remote?']
1612
aliases = ['mis', 'miss']
1613
# We don't have to add quiet to the list, because
1614
# unknown options are parsed as booleans
1615
takes_options = ['verbose', 'quiet']
1618
def run(self, remote=None, verbose=False, quiet=False):
1619
from bzrlib.errors import BzrCommandError
1620
from bzrlib.missing import show_missing
1622
if verbose and quiet:
1623
raise BzrCommandError('Cannot pass both quiet and verbose')
1625
tree = WorkingTree.open_containing('.')[0]
1626
parent = tree.branch.get_parent()
1629
raise BzrCommandError("No missing location known or specified.")
1632
print "Using last location: %s" % parent
1634
elif parent is None:
1635
# We only update parent if it did not exist, missing
1636
# should not change the parent
1637
tree.branch.set_parent(remote)
1638
br_remote = Branch.open_containing(remote)[0]
1639
return show_missing(tree.branch, br_remote, verbose=verbose, quiet=quiet)
1642
class cmd_plugins(Command):
1647
import bzrlib.plugin
1648
from inspect import getdoc
1649
for plugin in bzrlib.plugin.all_plugins:
1650
if hasattr(plugin, '__path__'):
1651
print plugin.__path__[0]
1652
elif hasattr(plugin, '__file__'):
1653
print plugin.__file__
1659
print '\t', d.split('\n')[0]
1662
class cmd_testament(Command):
1663
"""Show testament (signing-form) of a revision."""
1664
takes_options = ['revision', 'long']
1665
takes_args = ['branch?']
1667
def run(self, branch='.', revision=None, long=False):
1668
from bzrlib.testament import Testament
1669
b = WorkingTree.open_containing(branch)[0].branch
1672
if revision is None:
1673
rev_id = b.last_revision()
1675
rev_id = revision[0].in_history(b).rev_id
1676
t = Testament.from_revision(b, rev_id)
1678
sys.stdout.writelines(t.as_text_lines())
1680
sys.stdout.write(t.as_short_text())
1685
class cmd_annotate(Command):
1686
"""Show the origin of each line in a file.
1688
This prints out the given file with an annotation on the left side
1689
indicating which revision, author and date introduced the change.
1691
If the origin is the same for a run of consecutive lines, it is
1692
shown only at the top, unless the --all option is given.
1694
# TODO: annotate directories; showing when each file was last changed
1695
# TODO: annotate a previous version of a file
1696
# TODO: if the working copy is modified, show annotations on that
1697
# with new uncommitted lines marked
1698
aliases = ['blame', 'praise']
1699
takes_args = ['filename']
1700
takes_options = [Option('all', help='show annotations on all lines'),
1701
Option('long', help='show date in annotations'),
1705
def run(self, filename, all=False, long=False):
1706
from bzrlib.annotate import annotate_file
1707
tree, relpath = WorkingTree.open_containing(filename)
1708
branch = tree.branch
1711
file_id = tree.inventory.path2id(relpath)
1712
tree = branch.revision_tree(branch.last_revision())
1713
file_version = tree.inventory[file_id].revision
1714
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
1719
class cmd_re_sign(Command):
1720
"""Create a digital signature for an existing revision."""
1721
# TODO be able to replace existing ones.
1723
hidden = True # is this right ?
1724
takes_args = ['revision_id?']
1725
takes_options = ['revision']
1727
def run(self, revision_id=None, revision=None):
1728
import bzrlib.config as config
1729
import bzrlib.gpg as gpg
1730
if revision_id is not None and revision is not None:
1731
raise BzrCommandError('You can only supply one of revision_id or --revision')
1732
if revision_id is None and revision is None:
1733
raise BzrCommandError('You must supply either --revision or a revision_id')
1734
b = WorkingTree.open_containing('.')[0].branch
1735
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1736
if revision_id is not None:
1737
b.sign_revision(revision_id, gpg_strategy)
1738
elif revision is not None:
1739
if len(revision) == 1:
1740
revno, rev_id = revision[0].in_history(b)
1741
b.sign_revision(rev_id, gpg_strategy)
1742
elif len(revision) == 2:
1743
# are they both on rh- if so we can walk between them
1744
# might be nice to have a range helper for arbitrary
1745
# revision paths. hmm.
1746
from_revno, from_revid = revision[0].in_history(b)
1747
to_revno, to_revid = revision[1].in_history(b)
1748
if to_revid is None:
1749
to_revno = b.revno()
1750
if from_revno is None or to_revno is None:
1751
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
1752
for revno in range(from_revno, to_revno + 1):
1753
b.sign_revision(b.get_rev_id(revno), gpg_strategy)
1755
raise BzrCommandError('Please supply either one revision, or a range.')
1758
# these get imported and then picked up by the scan for cmd_*
1759
# TODO: Some more consistent way to split command definitions across files;
1760
# we do need to load at least some information about them to know of
1762
from bzrlib.conflicts import cmd_resolve, cmd_conflicts