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
import bzrlib.errors as errors
30
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
31
from bzrlib.errors import DivergedBranches, NoSuchFile, NoWorkingTree
32
from bzrlib.option import Option
33
from bzrlib.revisionspec import RevisionSpec
35
from bzrlib.trace import mutter, note, log_error, warning
36
from bzrlib.workingtree import WorkingTree
39
def branch_files(file_list, default_branch='.'):
41
Return a branch and list of branch-relative paths.
42
If supplied file_list is empty or None, the branch default will be used,
43
and returned file_list will match the original.
45
if file_list is None or len(file_list) == 0:
46
return Branch.open_containing(default_branch)[0], file_list
47
b = Branch.open_containing(file_list[0])[0]
49
# note that if this is a remote branch, we would want
50
# relpath against the transport. RBC 20051018
51
# Most branch ops can't meaningfully operate on files in remote branches;
52
# the above comment was in cmd_status. ADHB 20051026
53
tree = WorkingTree(b.base, b)
55
for filename in file_list:
57
new_list.append(tree.relpath(filename))
58
except NotBranchError:
59
raise BzrCommandError("%s is not in the same branch as %s" %
60
(filename, file_list[0]))
64
# TODO: Make sure no commands unconditionally use the working directory as a
65
# branch. If a filename argument is used, the first of them should be used to
66
# specify the branch. (Perhaps this can be factored out into some kind of
67
# Argument class, representing a file in a branch, where the first occurrence
70
class cmd_status(Command):
71
"""Display status summary.
73
This reports on versioned and unknown files, reporting them
74
grouped by state. Possible states are:
77
Versioned in the working copy but not in the previous revision.
80
Versioned in the previous revision but removed or deleted
84
Path of this file changed from the previous revision;
85
the text may also have changed. This includes files whose
86
parent directory was renamed.
89
Text has changed since the previous revision.
92
Nothing about this file has changed since the previous revision.
93
Only shown with --all.
96
Not versioned and not matching an ignore pattern.
98
To see ignored files use 'bzr ignored'. For details in the
99
changes to file texts, use 'bzr diff'.
101
If no arguments are specified, the status of the entire working
102
directory is shown. Otherwise, only the status of the specified
103
files or directories is reported. If a directory is given, status
104
is reported for everything inside that directory.
106
If a revision argument is given, the status is calculated against
107
that revision, or between two revisions if two are provided.
110
# XXX: FIXME: bzr status should accept a -r option to show changes
111
# relative to a revision, or between revisions
113
# TODO: --no-recurse, --recurse options
115
takes_args = ['file*']
116
takes_options = ['all', 'show-ids']
117
aliases = ['st', 'stat']
120
def run(self, all=False, show_ids=False, file_list=None, revision=None):
121
b, file_list = branch_files(file_list)
123
from bzrlib.status import show_status
124
show_status(b, show_unchanged=all, show_ids=show_ids,
125
specific_files=file_list, revision=revision)
128
class cmd_cat_revision(Command):
129
"""Write out metadata for a revision.
131
The revision to print can either be specified by a specific
132
revision identifier, or you can use --revision.
136
takes_args = ['revision_id?']
137
takes_options = ['revision']
140
def run(self, revision_id=None, revision=None):
142
if revision_id is not None and revision is not None:
143
raise BzrCommandError('You can only supply one of revision_id or --revision')
144
if revision_id is None and revision is None:
145
raise BzrCommandError('You must supply either --revision or a revision_id')
146
b = Branch.open_containing('.')[0]
147
if revision_id is not None:
148
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
149
elif revision is not None:
152
raise BzrCommandError('You cannot specify a NULL revision.')
153
revno, rev_id = rev.in_history(b)
154
sys.stdout.write(b.get_revision_xml_file(rev_id).read())
157
class cmd_revno(Command):
158
"""Show current revision number.
160
This is equal to the number of revisions on this branch."""
163
print Branch.open_containing('.')[0].revno()
166
class cmd_revision_info(Command):
167
"""Show revision number and revision id for a given revision identifier.
170
takes_args = ['revision_info*']
171
takes_options = ['revision']
173
def run(self, revision=None, revision_info_list=[]):
176
if revision is not None:
177
revs.extend(revision)
178
if revision_info_list is not None:
179
for rev in revision_info_list:
180
revs.append(RevisionSpec(rev))
182
raise BzrCommandError('You must supply a revision identifier')
184
b = Branch.open_containing('.')[0]
187
revinfo = rev.in_history(b)
188
if revinfo.revno is None:
189
print ' %s' % revinfo.rev_id
191
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
194
class cmd_add(Command):
195
"""Add specified files or directories.
197
In non-recursive mode, all the named items are added, regardless
198
of whether they were previously ignored. A warning is given if
199
any of the named files are already versioned.
201
In recursive mode (the default), files are treated the same way
202
but the behaviour for directories is different. Directories that
203
are already versioned do not give a warning. All directories,
204
whether already versioned or not, are searched for files or
205
subdirectories that are neither versioned or ignored, and these
206
are added. This search proceeds recursively into versioned
207
directories. If no names are given '.' is assumed.
209
Therefore simply saying 'bzr add' will version all files that
210
are currently unknown.
212
Adding a file whose parent directory is not versioned will
213
implicitly add the parent, and so on up to the root. This means
214
you should never need to explictly add a directory, they'll just
215
get added when you add a file in the directory.
217
takes_args = ['file*']
218
takes_options = ['no-recurse', 'quiet']
220
def run(self, file_list, no_recurse=False, quiet=False):
221
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
223
reporter = add_reporter_null
225
reporter = add_reporter_print
226
smart_add(file_list, not no_recurse, reporter)
229
class cmd_mkdir(Command):
230
"""Create a new versioned directory.
232
This is equivalent to creating the directory and then adding it.
234
takes_args = ['dir+']
236
def run(self, dir_list):
241
b, dd = Branch.open_containing(d)
246
class cmd_relpath(Command):
247
"""Show path of a file relative to root"""
248
takes_args = ['filename']
252
def run(self, filename):
253
branch, relpath = Branch.open_containing(filename)
257
class cmd_inventory(Command):
258
"""Show inventory of the current working copy or a revision."""
259
takes_options = ['revision', 'show-ids']
262
def run(self, revision=None, show_ids=False):
263
b = Branch.open_containing('.')[0]
265
inv = b.working_tree().read_working_inventory()
267
if len(revision) > 1:
268
raise BzrCommandError('bzr inventory --revision takes'
269
' exactly one revision identifier')
270
inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
272
for path, entry in inv.entries():
274
print '%-50s %s' % (path, entry.file_id)
279
class cmd_move(Command):
280
"""Move files to a different directory.
285
The destination must be a versioned directory in the same branch.
287
takes_args = ['source$', 'dest']
288
def run(self, source_list, dest):
289
b, source_list = branch_files(source_list)
291
# TODO: glob expansion on windows?
292
tree = WorkingTree(b.base, b)
293
b.move(source_list, tree.relpath(dest))
296
class cmd_rename(Command):
297
"""Change the name of an entry.
300
bzr rename frob.c frobber.c
301
bzr rename src/frob.c lib/frob.c
303
It is an error if the destination name exists.
305
See also the 'move' command, which moves files into a different
306
directory without changing their name.
308
# TODO: Some way to rename multiple files without invoking
309
# bzr for each one?"""
310
takes_args = ['from_name', 'to_name']
312
def run(self, from_name, to_name):
313
b, (from_name, to_name) = branch_files((from_name, to_name))
314
b.rename_one(from_name, to_name)
317
class cmd_mv(Command):
318
"""Move or rename a file.
321
bzr mv OLDNAME NEWNAME
322
bzr mv SOURCE... DESTINATION
324
If the last argument is a versioned directory, all the other names
325
are moved into it. Otherwise, there must be exactly two arguments
326
and the file is changed to a new name, which must not already exist.
328
Files cannot be moved between branches.
330
takes_args = ['names*']
331
def run(self, names_list):
332
if len(names_list) < 2:
333
raise BzrCommandError("missing file argument")
334
b, rel_names = branch_files(names_list)
336
if os.path.isdir(names_list[-1]):
337
# move into existing directory
338
for pair in b.move(rel_names[:-1], rel_names[-1]):
339
print "%s => %s" % pair
341
if len(names_list) != 2:
342
raise BzrCommandError('to mv multiple files the destination '
343
'must be a versioned directory')
344
b.rename_one(rel_names[0], rel_names[1])
345
print "%s => %s" % (rel_names[0], rel_names[1])
348
class cmd_pull(Command):
349
"""Pull any changes from another branch into the current one.
351
If there is no default location set, the first pull will set it. After
352
that, you can omit the location to use the default. To change the
353
default, use --remember.
355
This command only works on branches that have not diverged. Branches are
356
considered diverged if both branches have had commits without first
357
pulling from the other.
359
If branches have diverged, you can use 'bzr merge' to pull the text changes
360
from one into the other. Once one branch has merged, the other should
361
be able to pull it again.
363
If you want to forget your local changes and just update your branch to
364
match the remote one, use --overwrite.
366
takes_options = ['remember', 'overwrite', 'verbose']
367
takes_args = ['location?']
369
def run(self, location=None, remember=False, overwrite=False, verbose=False):
370
from bzrlib.merge import merge
371
from shutil import rmtree
374
br_to = Branch.open_containing('.')[0]
375
stored_loc = br_to.get_parent()
377
if stored_loc is None:
378
raise BzrCommandError("No pull location known or specified.")
380
print "Using saved location: %s" % stored_loc
381
location = stored_loc
382
br_from = Branch.open(location)
384
old_rh = br_to.revision_history()
385
br_to.working_tree().pull(br_from, overwrite)
386
except DivergedBranches:
387
raise BzrCommandError("These branches have diverged."
389
if br_to.get_parent() is None or remember:
390
br_to.set_parent(location)
393
new_rh = br_to.revision_history()
396
from bzrlib.log import show_changed_revisions
397
show_changed_revisions(br_to, old_rh, new_rh)
400
class cmd_push(Command):
401
"""Push this branch into another branch.
403
The remote branch will not have its working tree populated because this
404
is both expensive, and may not be supported on the remote file system.
406
Some smart servers or protocols *may* put the working tree in place.
408
If there is no default push location set, the first push will set it.
409
After that, you can omit the location to use the default. To change the
410
default, use --remember.
412
This command only works on branches that have not diverged. Branches are
413
considered diverged if the branch being pushed to is not an older version
416
If branches have diverged, you can use 'bzr push --overwrite' to replace
417
the other branch completely.
419
If you want to ensure you have the different changes in the other branch,
420
do a merge (see bzr help merge) from the other branch, and commit that
421
before doing a 'push --overwrite'.
423
takes_options = ['remember', 'overwrite',
424
Option('create-prefix',
425
help='Create the path leading up to the branch '
426
'if it does not already exist')]
427
takes_args = ['location?']
429
def run(self, location=None, remember=False, overwrite=False,
430
create_prefix=False, verbose=False):
432
from shutil import rmtree
433
from bzrlib.transport import get_transport
435
br_from = Branch.open_containing('.')[0]
436
stored_loc = br_from.get_push_location()
438
if stored_loc is None:
439
raise BzrCommandError("No push location known or specified.")
441
print "Using saved location: %s" % stored_loc
442
location = stored_loc
444
br_to = Branch.open(location)
445
except NotBranchError:
447
transport = get_transport(location).clone('..')
448
if not create_prefix:
450
transport.mkdir(transport.relpath(location))
452
raise BzrCommandError("Parent directory of %s "
453
"does not exist." % location)
455
current = transport.base
456
needed = [(transport, transport.relpath(location))]
459
transport, relpath = needed[-1]
460
transport.mkdir(relpath)
463
new_transport = transport.clone('..')
464
needed.append((new_transport,
465
new_transport.relpath(transport.base)))
466
if new_transport.base == transport.base:
467
raise BzrCommandError("Could not creeate "
471
br_to = Branch.initialize(location)
473
old_rh = br_to.revision_history()
474
br_to.pull(br_from, overwrite)
475
except DivergedBranches:
476
raise BzrCommandError("These branches have diverged."
477
" Try a merge then push with overwrite.")
478
if br_from.get_push_location() is None or remember:
479
br_from.set_push_location(location)
482
new_rh = br_to.revision_history()
485
from bzrlib.log import show_changed_revisions
486
show_changed_revisions(br_to, old_rh, new_rh)
488
class cmd_branch(Command):
489
"""Create a new copy of a branch.
491
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
492
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
494
To retrieve the branch as of a particular revision, supply the --revision
495
parameter, as in "branch foo/bar -r 5".
497
--basis is to speed up branching from remote branches. When specified, it
498
copies all the file-contents, inventory and revision data from the basis
499
branch before copying anything from the remote branch.
501
takes_args = ['from_location', 'to_location?']
502
takes_options = ['revision', 'basis']
503
aliases = ['get', 'clone']
505
def run(self, from_location, to_location=None, revision=None, basis=None):
506
from bzrlib.clone import copy_branch
508
from shutil import rmtree
511
elif len(revision) > 1:
512
raise BzrCommandError(
513
'bzr branch --revision takes exactly 1 revision value')
515
br_from = Branch.open(from_location)
517
if e.errno == errno.ENOENT:
518
raise BzrCommandError('Source location "%s" does not'
519
' exist.' % to_location)
524
if basis is not None:
525
basis_branch = Branch.open_containing(basis)[0]
528
if len(revision) == 1 and revision[0] is not None:
529
revision_id = revision[0].in_history(br_from)[1]
532
if to_location is None:
533
to_location = os.path.basename(from_location.rstrip("/\\"))
536
name = os.path.basename(to_location) + '\n'
538
os.mkdir(to_location)
540
if e.errno == errno.EEXIST:
541
raise BzrCommandError('Target directory "%s" already'
542
' exists.' % to_location)
543
if e.errno == errno.ENOENT:
544
raise BzrCommandError('Parent of "%s" does not exist.' %
549
copy_branch(br_from, to_location, revision_id, basis_branch)
550
except bzrlib.errors.NoSuchRevision:
552
msg = "The branch %s has no revision %s." % (from_location, revision[0])
553
raise BzrCommandError(msg)
554
except bzrlib.errors.UnlistableBranch:
556
msg = "The branch %s cannot be used as a --basis"
557
raise BzrCommandError(msg)
559
branch = Branch.open(to_location)
560
name = StringIO(name)
561
branch.put_controlfile('branch-name', name)
566
class cmd_renames(Command):
567
"""Show list of renamed files.
569
# TODO: Option to show renames between two historical versions.
571
# TODO: Only show renames under dir, rather than in the whole branch.
572
takes_args = ['dir?']
575
def run(self, dir='.'):
576
b = Branch.open_containing(dir)[0]
577
old_inv = b.basis_tree().inventory
578
new_inv = b.working_tree().read_working_inventory()
580
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
582
for old_name, new_name in renames:
583
print "%s => %s" % (old_name, new_name)
586
class cmd_info(Command):
587
"""Show statistical information about a branch."""
588
takes_args = ['branch?']
591
def run(self, branch=None):
593
b = Branch.open_containing(branch)[0]
597
class cmd_remove(Command):
598
"""Make a file unversioned.
600
This makes bzr stop tracking changes to a versioned file. It does
601
not delete the working copy.
603
takes_args = ['file+']
604
takes_options = ['verbose']
607
def run(self, file_list, verbose=False):
608
b, file_list = branch_files(file_list)
609
tree = b.working_tree()
610
tree.remove(file_list, verbose=verbose)
613
class cmd_file_id(Command):
614
"""Print file_id of a particular file or directory.
616
The file_id is assigned when the file is first added and remains the
617
same through all revisions where the file exists, even when it is
621
takes_args = ['filename']
623
def run(self, filename):
624
b, relpath = Branch.open_containing(filename)
625
i = b.inventory.path2id(relpath)
627
raise BzrError("%r is not a versioned file" % filename)
632
class cmd_file_path(Command):
633
"""Print path of file_ids to a file or directory.
635
This prints one line for each directory down to the target,
636
starting at the branch root."""
638
takes_args = ['filename']
640
def run(self, filename):
641
b, relpath = Branch.open_containing(filename)
643
fid = inv.path2id(relpath)
645
raise BzrError("%r is not a versioned file" % filename)
646
for fip in inv.get_idpath(fid):
650
class cmd_revision_history(Command):
651
"""Display list of revision ids on this branch."""
655
for patchid in Branch.open_containing('.')[0].revision_history():
659
class cmd_ancestry(Command):
660
"""List all revisions merged into this branch."""
664
b = Branch.open_containing('.')[0]
665
for revision_id in b.get_ancestry(b.last_revision()):
669
class cmd_directories(Command):
670
"""Display list of versioned directories in this branch."""
673
for name, ie in (Branch.open_containing('.')[0].working_tree().
674
read_working_inventory().directories()):
681
class cmd_init(Command):
682
"""Make a directory into a versioned branch.
684
Use this to create an empty branch, or before importing an
687
Recipe for importing a tree of files:
692
bzr commit -m 'imported project'
694
takes_args = ['location?']
695
def run(self, location=None):
696
from bzrlib.branch import Branch
700
# The path has to exist to initialize a
701
# branch inside of it.
702
# Just using os.mkdir, since I don't
703
# believe that we want to create a bunch of
704
# locations if the user supplies an extended path
705
if not os.path.exists(location):
707
Branch.initialize(location)
710
class cmd_diff(Command):
711
"""Show differences in working tree.
713
If files are listed, only the changes in those files are listed.
714
Otherwise, all changes for the tree are listed.
721
# TODO: Allow diff across branches.
722
# TODO: Option to use external diff command; could be GNU diff, wdiff,
723
# or a graphical diff.
725
# TODO: Python difflib is not exactly the same as unidiff; should
726
# either fix it up or prefer to use an external diff.
728
# TODO: If a directory is given, diff everything under that.
730
# TODO: Selected-file diff is inefficient and doesn't show you
733
# TODO: This probably handles non-Unix newlines poorly.
735
takes_args = ['file*']
736
takes_options = ['revision', 'diff-options']
737
aliases = ['di', 'dif']
740
def run(self, revision=None, file_list=None, diff_options=None):
741
from bzrlib.diff import show_diff
743
b, file_list = branch_files(file_list)
744
if revision is not None:
745
if len(revision) == 1:
746
return show_diff(b, revision[0], specific_files=file_list,
747
external_diff_options=diff_options)
748
elif len(revision) == 2:
749
return show_diff(b, revision[0], specific_files=file_list,
750
external_diff_options=diff_options,
751
revision2=revision[1])
753
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
755
return show_diff(b, None, specific_files=file_list,
756
external_diff_options=diff_options)
759
class cmd_deleted(Command):
760
"""List files deleted in the working tree.
762
# TODO: Show files deleted since a previous revision, or
763
# between two revisions.
764
# TODO: Much more efficient way to do this: read in new
765
# directories with readdir, rather than stating each one. Same
766
# level of effort but possibly much less IO. (Or possibly not,
767
# if the directories are very large...)
769
def run(self, show_ids=False):
770
b = Branch.open_containing('.')[0]
772
new = b.working_tree()
773
for path, ie in old.inventory.iter_entries():
774
if not new.has_id(ie.file_id):
776
print '%-50s %s' % (path, ie.file_id)
781
class cmd_modified(Command):
782
"""List files modified in working tree."""
786
from bzrlib.delta import compare_trees
788
b = Branch.open_containing('.')[0]
789
td = compare_trees(b.basis_tree(), b.working_tree())
791
for path, id, kind, text_modified, meta_modified in td.modified:
796
class cmd_added(Command):
797
"""List files added in working tree."""
801
b = Branch.open_containing('.')[0]
802
wt = b.working_tree()
803
basis_inv = b.basis_tree().inventory
806
if file_id in basis_inv:
808
path = inv.id2path(file_id)
809
if not os.access(b.abspath(path), os.F_OK):
815
class cmd_root(Command):
816
"""Show the tree root directory.
818
The root is the nearest enclosing directory with a .bzr control
820
takes_args = ['filename?']
822
def run(self, filename=None):
823
"""Print the branch root."""
824
b = Branch.open_containing(filename)[0]
828
class cmd_log(Command):
829
"""Show log of this branch.
831
To request a range of logs, you can use the command -r begin..end
832
-r revision requests a specific revision, -r ..end or -r begin.. are
836
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
838
takes_args = ['filename?']
839
takes_options = [Option('forward',
840
help='show from oldest to newest'),
841
'timezone', 'verbose',
842
'show-ids', 'revision',
843
Option('line', help='format with one line per revision'),
846
help='show revisions whose message matches this regexp',
848
Option('short', help='use moderately short format'),
851
def run(self, filename=None, timezone='original',
860
from bzrlib.log import log_formatter, show_log
862
assert message is None or isinstance(message, basestring), \
863
"invalid message argument %r" % message
864
direction = (forward and 'forward') or 'reverse'
867
b, fp = Branch.open_containing(filename)
870
inv = b.working_tree().read_working_inventory()
871
except NoWorkingTree:
872
inv = b.get_inventory(b.last_revision())
873
file_id = inv.path2id(fp)
875
file_id = None # points to branch root
877
b, relpath = Branch.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
b, relpath = Branch.open_containing(filename)[0]
932
inv = b.working_tree().read_working_inventory()
933
file_id = inv.path2id(relpath)
934
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
935
print "%6d %s" % (revno, what)
938
class cmd_ls(Command):
939
"""List files in a tree.
941
# TODO: Take a revision or remote path and list that tree instead.
943
takes_options = ['verbose', 'revision',
944
Option('non-recursive',
945
help='don\'t recurse into sub-directories'),
947
help='Print all paths from the root of the branch.'),
948
Option('unknown', help='Print unknown files'),
949
Option('versioned', help='Print versioned files'),
950
Option('ignored', help='Print ignored files'),
952
Option('null', help='Null separate the files'),
955
def run(self, revision=None, verbose=False,
956
non_recursive=False, from_root=False,
957
unknown=False, versioned=False, ignored=False,
961
raise BzrCommandError('Cannot set both --verbose and --null')
962
all = not (unknown or versioned or ignored)
964
selection = {'I':ignored, '?':unknown, 'V':versioned}
966
b, relpath = Branch.open_containing('.')
972
tree = b.working_tree()
974
tree = b.revision_tree(revision[0].in_history(b).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')
994
class cmd_unknowns(Command):
995
"""List unknown files."""
998
from bzrlib.osutils import quotefn
999
for f in Branch.open_containing('.')[0].unknowns():
1004
class cmd_ignore(Command):
1005
"""Ignore a command or pattern.
1007
To remove patterns from the ignore list, edit the .bzrignore file.
1009
If the pattern contains a slash, it is compared to the whole path
1010
from the branch root. Otherwise, it is compared to only the last
1011
component of the path. To match a file only in the root directory,
1014
Ignore patterns are case-insensitive on case-insensitive systems.
1016
Note: wildcards must be quoted from the shell on Unix.
1019
bzr ignore ./Makefile
1020
bzr ignore '*.class'
1022
# TODO: Complain if the filename is absolute
1023
takes_args = ['name_pattern']
1025
def run(self, name_pattern):
1026
from bzrlib.atomicfile import AtomicFile
1029
b, relpath = Branch.open_containing('.')
1030
ifn = b.abspath('.bzrignore')
1032
if os.path.exists(ifn):
1035
igns = f.read().decode('utf-8')
1041
# TODO: If the file already uses crlf-style termination, maybe
1042
# we should use that for the newly added lines?
1044
if igns and igns[-1] != '\n':
1046
igns += name_pattern + '\n'
1049
f = AtomicFile(ifn, 'wt')
1050
f.write(igns.encode('utf-8'))
1055
inv = b.working_tree().inventory
1056
if inv.path2id('.bzrignore'):
1057
mutter('.bzrignore is already versioned')
1059
mutter('need to make new .bzrignore file versioned')
1060
b.add(['.bzrignore'])
1064
class cmd_ignored(Command):
1065
"""List ignored files and the patterns that matched them.
1067
See also: bzr ignore"""
1070
tree = Branch.open_containing('.')[0].working_tree()
1071
for path, file_class, kind, file_id, entry in tree.list_files():
1072
if file_class != 'I':
1074
## XXX: Slightly inefficient since this was already calculated
1075
pat = tree.is_ignored(path)
1076
print '%-50s %s' % (path, pat)
1079
class cmd_lookup_revision(Command):
1080
"""Lookup the revision-id from a revision-number
1083
bzr lookup-revision 33
1086
takes_args = ['revno']
1089
def run(self, revno):
1093
raise BzrCommandError("not a valid revision-number: %r" % revno)
1095
print Branch.open_containing('.')[0].get_rev_id(revno)
1098
class cmd_export(Command):
1099
"""Export past revision to destination directory.
1101
If no revision is specified this exports the last committed revision.
1103
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1104
given, try to find the format with the extension. If no extension
1105
is found exports to a directory (equivalent to --format=dir).
1107
Root may be the top directory for tar, tgz and tbz2 formats. If none
1108
is given, the top directory will be the root name of the file.
1110
Note: export of tree with non-ascii filenames to zip is not supported.
1112
Supported formats Autodetected by extension
1113
----------------- -------------------------
1116
tbz2 .tar.bz2, .tbz2
1120
takes_args = ['dest']
1121
takes_options = ['revision', 'format', 'root']
1122
def run(self, dest, revision=None, format=None, root=None):
1124
from bzrlib.export import export
1125
b = Branch.open_containing('.')[0]
1126
if revision is None:
1127
rev_id = b.last_revision()
1129
if len(revision) != 1:
1130
raise BzrError('bzr export --revision takes exactly 1 argument')
1131
rev_id = revision[0].in_history(b).rev_id
1132
t = b.revision_tree(rev_id)
1134
export(t, dest, format, root)
1135
except errors.NoSuchExportFormat, e:
1136
raise BzrCommandError('Unsupported export format: %s' % e.format)
1139
class cmd_cat(Command):
1140
"""Write a file's text from a previous revision."""
1142
takes_options = ['revision']
1143
takes_args = ['filename']
1146
def run(self, filename, revision=None):
1147
if revision is None:
1148
raise BzrCommandError("bzr cat requires a revision number")
1149
elif len(revision) != 1:
1150
raise BzrCommandError("bzr cat --revision takes exactly one number")
1151
b, relpath = Branch.open_containing(filename)
1152
b.print_file(relpath, revision[0].in_history(b).revno)
1155
class cmd_local_time_offset(Command):
1156
"""Show the offset in seconds from GMT to local time."""
1160
print bzrlib.osutils.local_time_offset()
1164
class cmd_commit(Command):
1165
"""Commit changes into a new revision.
1167
If no arguments are given, the entire tree is committed.
1169
If selected files are specified, only changes to those files are
1170
committed. If a directory is specified then the directory and everything
1171
within it is committed.
1173
A selected-file commit may fail in some cases where the committed
1174
tree would be invalid, such as trying to commit a file in a
1175
newly-added directory that is not itself committed.
1177
# TODO: Run hooks on tree to-be-committed, and after commit.
1179
# TODO: Strict commit that fails if there are deleted files.
1180
# (what does "deleted files" mean ??)
1182
# TODO: Give better message for -s, --summary, used by tla people
1184
# XXX: verbose currently does nothing
1186
takes_args = ['selected*']
1187
takes_options = ['message', 'verbose',
1189
help='commit even if nothing has changed'),
1190
Option('file', type=str,
1192
help='file containing commit message'),
1194
help="refuse to commit if there are unknown "
1195
"files in the working tree."),
1197
aliases = ['ci', 'checkin']
1199
def run(self, message=None, file=None, verbose=True, selected_list=None,
1200
unchanged=False, strict=False):
1201
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1203
from bzrlib.msgeditor import edit_commit_message
1204
from bzrlib.status import show_status
1205
from cStringIO import StringIO
1207
b, selected_list = branch_files(selected_list)
1208
if message is None and not file:
1209
catcher = StringIO()
1210
show_status(b, specific_files=selected_list,
1212
message = edit_commit_message(catcher.getvalue())
1215
raise BzrCommandError("please specify a commit message"
1216
" with either --message or --file")
1217
elif message and file:
1218
raise BzrCommandError("please specify either --message or --file")
1222
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1225
raise BzrCommandError("empty commit message specified")
1228
b.working_tree().commit(message, specific_files=selected_list,
1229
allow_pointless=unchanged, strict=strict)
1230
except PointlessCommit:
1231
# FIXME: This should really happen before the file is read in;
1232
# perhaps prepare the commit; get the message; then actually commit
1233
raise BzrCommandError("no changes to commit",
1234
["use --unchanged to commit anyhow"])
1235
except ConflictsInTree:
1236
raise BzrCommandError("Conflicts detected in working tree. "
1237
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1238
except StrictCommitFailed:
1239
raise BzrCommandError("Commit refused because there are unknown "
1240
"files in the working tree.")
1243
class cmd_check(Command):
1244
"""Validate consistency of branch history.
1246
This command checks various invariants about the branch storage to
1247
detect data corruption or bzr bugs.
1249
takes_args = ['dir?']
1250
takes_options = ['verbose']
1252
def run(self, dir='.', verbose=False):
1253
from bzrlib.check import check
1254
check(Branch.open_containing(dir)[0], verbose)
1257
class cmd_scan_cache(Command):
1260
from bzrlib.hashcache import HashCache
1266
print '%6d stats' % c.stat_count
1267
print '%6d in hashcache' % len(c._cache)
1268
print '%6d files removed from cache' % c.removed_count
1269
print '%6d hashes updated' % c.update_count
1270
print '%6d files changed too recently to cache' % c.danger_count
1277
class cmd_upgrade(Command):
1278
"""Upgrade branch storage to current format.
1280
The check command or bzr developers may sometimes advise you to run
1283
This version of this command upgrades from the full-text storage
1284
used by bzr 0.0.8 and earlier to the weave format (v5).
1286
takes_args = ['dir?']
1288
def run(self, dir='.'):
1289
from bzrlib.upgrade import upgrade
1293
class cmd_whoami(Command):
1294
"""Show bzr user id."""
1295
takes_options = ['email']
1298
def run(self, email=False):
1300
b = bzrlib.branch.Branch.open_containing('.')[0]
1301
config = bzrlib.config.BranchConfig(b)
1302
except NotBranchError:
1303
config = bzrlib.config.GlobalConfig()
1306
print config.user_email()
1308
print config.username()
1311
class cmd_selftest(Command):
1312
"""Run internal test suite.
1314
This creates temporary test directories in the working directory,
1315
but not existing data is affected. These directories are deleted
1316
if the tests pass, or left behind to help in debugging if they
1319
If arguments are given, they are regular expressions that say
1320
which tests should run.
1322
# TODO: --list should give a list of all available tests
1324
takes_args = ['testspecs*']
1325
takes_options = ['verbose',
1326
Option('one', help='stop when one test fails'),
1329
def run(self, testspecs_list=None, verbose=False, one=False):
1331
from bzrlib.selftest import selftest
1332
# we don't want progress meters from the tests to go to the
1333
# real output; and we don't want log messages cluttering up
1335
save_ui = bzrlib.ui.ui_factory
1336
bzrlib.trace.info('running tests...')
1338
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1339
if testspecs_list is not None:
1340
pattern = '|'.join(testspecs_list)
1343
result = selftest(verbose=verbose,
1345
stop_on_failure=one)
1347
bzrlib.trace.info('tests passed')
1349
bzrlib.trace.info('tests failed')
1350
return int(not result)
1352
bzrlib.ui.ui_factory = save_ui
1356
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1357
# is bzrlib itself in a branch?
1358
bzrrev = bzrlib.get_bzr_revision()
1360
print " (bzr checkout, revision %d {%s})" % bzrrev
1361
print bzrlib.__copyright__
1362
print "http://bazaar-ng.org/"
1364
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1365
print "you may use, modify and redistribute it under the terms of the GNU"
1366
print "General Public License version 2 or later."
1369
class cmd_version(Command):
1370
"""Show version of bzr."""
1375
class cmd_rocks(Command):
1376
"""Statement of optimism."""
1380
print "it sure does!"
1383
class cmd_find_merge_base(Command):
1384
"""Find and print a base revision for merging two branches.
1386
# TODO: Options to specify revisions on either side, as if
1387
# merging only part of the history.
1388
takes_args = ['branch', 'other']
1392
def run(self, branch, other):
1393
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1395
branch1 = Branch.open_containing(branch)[0]
1396
branch2 = Branch.open_containing(other)[0]
1398
history_1 = branch1.revision_history()
1399
history_2 = branch2.revision_history()
1401
last1 = branch1.last_revision()
1402
last2 = branch2.last_revision()
1404
source = MultipleRevisionSources(branch1, branch2)
1406
base_rev_id = common_ancestor(last1, last2, source)
1408
print 'merge base is revision %s' % base_rev_id
1412
if base_revno is None:
1413
raise bzrlib.errors.UnrelatedBranches()
1415
print ' r%-6d in %s' % (base_revno, branch)
1417
other_revno = branch2.revision_id_to_revno(base_revid)
1419
print ' r%-6d in %s' % (other_revno, other)
1423
class cmd_merge(Command):
1424
"""Perform a three-way merge.
1426
The branch is the branch you will merge from. By default, it will
1427
merge the latest revision. If you specify a revision, that
1428
revision will be merged. If you specify two revisions, the first
1429
will be used as a BASE, and the second one as OTHER. Revision
1430
numbers are always relative to the specified branch.
1432
By default bzr will try to merge in all new work from the other
1433
branch, automatically determining an appropriate base. If this
1434
fails, you may need to give an explicit base.
1438
To merge the latest revision from bzr.dev
1439
bzr merge ../bzr.dev
1441
To merge changes up to and including revision 82 from bzr.dev
1442
bzr merge -r 82 ../bzr.dev
1444
To merge the changes introduced by 82, without previous changes:
1445
bzr merge -r 81..82 ../bzr.dev
1447
merge refuses to run if there are any uncommitted changes, unless
1450
takes_args = ['branch?']
1451
takes_options = ['revision', 'force', 'merge-type', 'reprocess',
1452
Option('show-base', help="Show base revision text in "
1455
def run(self, branch=None, revision=None, force=False, merge_type=None,
1456
show_base=False, reprocess=False):
1457
from bzrlib.merge import merge
1458
from bzrlib.merge_core import ApplyMerge3
1459
if merge_type is None:
1460
merge_type = ApplyMerge3
1462
branch = Branch.open_containing('.')[0].get_parent()
1464
raise BzrCommandError("No merge location known or specified.")
1466
print "Using saved location: %s" % branch
1467
if revision is None or len(revision) < 1:
1469
other = [branch, -1]
1471
if len(revision) == 1:
1473
other_branch = Branch.open_containing(branch)[0]
1474
revno = revision[0].in_history(other_branch).revno
1475
other = [branch, revno]
1477
assert len(revision) == 2
1478
if None in revision:
1479
raise BzrCommandError(
1480
"Merge doesn't permit that revision specifier.")
1481
b = Branch.open_containing(branch)[0]
1483
base = [branch, revision[0].in_history(b).revno]
1484
other = [branch, revision[1].in_history(b).revno]
1487
conflict_count = merge(other, base, check_clean=(not force),
1488
merge_type=merge_type, reprocess=reprocess,
1489
show_base=show_base)
1490
if conflict_count != 0:
1494
except bzrlib.errors.AmbiguousBase, e:
1495
m = ("sorry, bzr can't determine the right merge base yet\n"
1496
"candidates are:\n "
1497
+ "\n ".join(e.bases)
1499
"please specify an explicit base with -r,\n"
1500
"and (if you want) report this to the bzr developers\n")
1504
class cmd_revert(Command):
1505
"""Reverse all changes since the last commit.
1507
Only versioned files are affected. Specify filenames to revert only
1508
those files. By default, any files that are changed will be backed up
1509
first. Backup files have a '~' appended to their name.
1511
takes_options = ['revision', 'no-backup']
1512
takes_args = ['file*']
1513
aliases = ['merge-revert']
1515
def run(self, revision=None, no_backup=False, file_list=None):
1516
from bzrlib.merge import merge_inner
1517
from bzrlib.commands import parse_spec
1518
if file_list is not None:
1519
if len(file_list) == 0:
1520
raise BzrCommandError("No files specified")
1523
if revision is None:
1525
b = Branch.open_containing('.')[0]
1526
rev_id = b.last_revision()
1527
elif len(revision) != 1:
1528
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1530
b, file_list = branch_files(file_list)
1531
rev_id = revision[0].in_history(b).rev_id
1532
b.working_tree().revert(file_list, b.revision_tree(rev_id),
1536
class cmd_assert_fail(Command):
1537
"""Test reporting of assertion failures"""
1540
assert False, "always fails"
1543
class cmd_help(Command):
1544
"""Show help on a command or other topic.
1546
For a list of all available commands, say 'bzr help commands'."""
1547
takes_options = ['long']
1548
takes_args = ['topic?']
1552
def run(self, topic=None, long=False):
1554
if topic is None and long:
1559
class cmd_shell_complete(Command):
1560
"""Show appropriate completions for context.
1562
For a list of all available commands, say 'bzr shell-complete'."""
1563
takes_args = ['context?']
1568
def run(self, context=None):
1569
import shellcomplete
1570
shellcomplete.shellcomplete(context)
1573
class cmd_fetch(Command):
1574
"""Copy in history from another branch but don't merge it.
1576
This is an internal method used for pull and merge."""
1578
takes_args = ['from_branch', 'to_branch']
1579
def run(self, from_branch, to_branch):
1580
from bzrlib.fetch import Fetcher
1581
from bzrlib.branch import Branch
1582
from_b = Branch.open(from_branch)
1583
to_b = Branch.open(to_branch)
1588
Fetcher(to_b, from_b)
1595
class cmd_missing(Command):
1596
"""What is missing in this branch relative to other branch.
1598
# TODO: rewrite this in terms of ancestry so that it shows only
1601
takes_args = ['remote?']
1602
aliases = ['mis', 'miss']
1603
# We don't have to add quiet to the list, because
1604
# unknown options are parsed as booleans
1605
takes_options = ['verbose', 'quiet']
1608
def run(self, remote=None, verbose=False, quiet=False):
1609
from bzrlib.errors import BzrCommandError
1610
from bzrlib.missing import show_missing
1612
if verbose and quiet:
1613
raise BzrCommandError('Cannot pass both quiet and verbose')
1615
b = Branch.open_containing('.')[0]
1616
parent = b.get_parent()
1619
raise BzrCommandError("No missing location known or specified.")
1622
print "Using last location: %s" % parent
1624
elif parent is None:
1625
# We only update parent if it did not exist, missing
1626
# should not change the parent
1627
b.set_parent(remote)
1628
br_remote = Branch.open_containing(remote)[0]
1629
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1632
class cmd_plugins(Command):
1637
import bzrlib.plugin
1638
from inspect import getdoc
1639
for plugin in bzrlib.plugin.all_plugins:
1640
if hasattr(plugin, '__path__'):
1641
print plugin.__path__[0]
1642
elif hasattr(plugin, '__file__'):
1643
print plugin.__file__
1649
print '\t', d.split('\n')[0]
1652
class cmd_testament(Command):
1653
"""Show testament (signing-form) of a revision."""
1654
takes_options = ['revision', 'long']
1655
takes_args = ['branch?']
1657
def run(self, branch='.', revision=None, long=False):
1658
from bzrlib.testament import Testament
1659
b = Branch.open_containing(branch)[0]
1662
if revision is None:
1663
rev_id = b.last_revision()
1665
rev_id = revision[0].in_history(b).rev_id
1666
t = Testament.from_revision(b, rev_id)
1668
sys.stdout.writelines(t.as_text_lines())
1670
sys.stdout.write(t.as_short_text())
1675
class cmd_annotate(Command):
1676
"""Show the origin of each line in a file.
1678
This prints out the given file with an annotation on the left side
1679
indicating which revision, author and date introduced the change.
1681
If the origin is the same for a run of consecutive lines, it is
1682
shown only at the top, unless the --all option is given.
1684
# TODO: annotate directories; showing when each file was last changed
1685
# TODO: annotate a previous version of a file
1686
# TODO: if the working copy is modified, show annotations on that
1687
# with new uncommitted lines marked
1688
aliases = ['blame', 'praise']
1689
takes_args = ['filename']
1690
takes_options = [Option('all', help='show annotations on all lines'),
1691
Option('long', help='show date in annotations'),
1695
def run(self, filename, all=False, long=False):
1696
from bzrlib.annotate import annotate_file
1697
b, relpath = Branch.open_containing(filename)
1700
tree = WorkingTree(b.base, b)
1701
tree = b.revision_tree(b.last_revision())
1702
file_id = tree.inventory.path2id(relpath)
1703
file_version = tree.inventory[file_id].revision
1704
annotate_file(b, file_version, file_id, long, all, sys.stdout)
1709
class cmd_re_sign(Command):
1710
"""Create a digital signature for an existing revision."""
1711
# TODO be able to replace existing ones.
1713
hidden = True # is this right ?
1714
takes_args = ['revision_id?']
1715
takes_options = ['revision']
1717
def run(self, revision_id=None, revision=None):
1718
import bzrlib.config as config
1719
import bzrlib.gpg as gpg
1720
if revision_id is not None and revision is not None:
1721
raise BzrCommandError('You can only supply one of revision_id or --revision')
1722
if revision_id is None and revision is None:
1723
raise BzrCommandError('You must supply either --revision or a revision_id')
1724
b = Branch.open_containing('.')[0]
1725
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1726
if revision_id is not None:
1727
b.sign_revision(revision_id, gpg_strategy)
1728
elif revision is not None:
1729
if len(revision) == 1:
1730
revno, rev_id = revision[0].in_history(b)
1731
b.sign_revision(rev_id, gpg_strategy)
1732
elif len(revision) == 2:
1733
# are they both on rh- if so we can walk between them
1734
# might be nice to have a range helper for arbitrary
1735
# revision paths. hmm.
1736
from_revno, from_revid = revision[0].in_history(b)
1737
to_revno, to_revid = revision[1].in_history(b)
1738
if to_revid is None:
1739
to_revno = b.revno()
1740
if from_revno is None or to_revno is None:
1741
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
1742
for revno in range(from_revno, to_revno + 1):
1743
b.sign_revision(b.get_rev_id(revno), gpg_strategy)
1745
raise BzrCommandError('Please supply either one revision, or a range.')
1748
# these get imported and then picked up by the scan for cmd_*
1749
# TODO: Some more consistent way to split command definitions across files;
1750
# we do need to load at least some information about them to know of
1752
from bzrlib.conflicts import cmd_resolve, cmd_conflicts