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
22
from bzrlib import BZRDIR
23
from bzrlib.commands import Command, display_command
24
from bzrlib.branch import Branch
25
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
26
from bzrlib.errors import DivergedBranches
27
from bzrlib.option import Option
28
from bzrlib.revisionspec import RevisionSpec
30
from bzrlib.trace import mutter, note, log_error, warning
31
from bzrlib.workingtree import WorkingTree
34
class cmd_status(Command):
35
"""Display status summary.
37
This reports on versioned and unknown files, reporting them
38
grouped by state. Possible states are:
41
Versioned in the working copy but not in the previous revision.
44
Versioned in the previous revision but removed or deleted
48
Path of this file changed from the previous revision;
49
the text may also have changed. This includes files whose
50
parent directory was renamed.
53
Text has changed since the previous revision.
56
Nothing about this file has changed since the previous revision.
57
Only shown with --all.
60
Not versioned and not matching an ignore pattern.
62
To see ignored files use 'bzr ignored'. For details in the
63
changes to file texts, use 'bzr diff'.
65
If no arguments are specified, the status of the entire working
66
directory is shown. Otherwise, only the status of the specified
67
files or directories is reported. If a directory is given, status
68
is reported for everything inside that directory.
70
If a revision argument is given, the status is calculated against
71
that revision, or between two revisions if two are provided.
74
# XXX: FIXME: bzr status should accept a -r option to show changes
75
# relative to a revision, or between revisions
77
# TODO: --no-recurse, --recurse options
79
takes_args = ['file*']
80
takes_options = ['all', 'show-ids']
81
aliases = ['st', 'stat']
84
def run(self, all=False, show_ids=False, file_list=None, revision=None):
86
b, relpath = Branch.open_containing(file_list[0])
87
if relpath == '' and len(file_list) == 1:
90
# generate relative paths.
91
# note that if this is a remote branch, we would want
92
# relpath against the transport. RBC 20051018
93
tree = WorkingTree(b.base, b)
94
file_list = [tree.relpath(x) for x in file_list]
96
b = Branch.open_containing('.')[0]
98
from bzrlib.status import show_status
99
show_status(b, show_unchanged=all, show_ids=show_ids,
100
specific_files=file_list, revision=revision)
103
class cmd_cat_revision(Command):
104
"""Write out metadata for a revision.
106
The revision to print can either be specified by a specific
107
revision identifier, or you can use --revision.
111
takes_args = ['revision_id?']
112
takes_options = ['revision']
115
def run(self, revision_id=None, revision=None):
117
if revision_id is not None and revision is not None:
118
raise BzrCommandError('You can only supply one of revision_id or --revision')
119
if revision_id is None and revision is None:
120
raise BzrCommandError('You must supply either --revision or a revision_id')
121
b = Branch.open_containing('.')[0]
122
if revision_id is not None:
123
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
124
elif revision is not None:
127
raise BzrCommandError('You cannot specify a NULL revision.')
128
revno, rev_id = rev.in_history(b)
129
sys.stdout.write(b.get_revision_xml_file(rev_id).read())
132
class cmd_revno(Command):
133
"""Show current revision number.
135
This is equal to the number of revisions on this branch."""
138
print Branch.open_containing('.')[0].revno()
141
class cmd_revision_info(Command):
142
"""Show revision number and revision id for a given revision identifier.
145
takes_args = ['revision_info*']
146
takes_options = ['revision']
148
def run(self, revision=None, revision_info_list=[]):
151
if revision is not None:
152
revs.extend(revision)
153
if revision_info_list is not None:
154
for rev in revision_info_list:
155
revs.append(RevisionSpec(rev))
157
raise BzrCommandError('You must supply a revision identifier')
159
b = Branch.open_containing('.')[0]
162
revinfo = rev.in_history(b)
163
if revinfo.revno is None:
164
print ' %s' % revinfo.rev_id
166
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
169
class cmd_add(Command):
170
"""Add specified files or directories.
172
In non-recursive mode, all the named items are added, regardless
173
of whether they were previously ignored. A warning is given if
174
any of the named files are already versioned.
176
In recursive mode (the default), files are treated the same way
177
but the behaviour for directories is different. Directories that
178
are already versioned do not give a warning. All directories,
179
whether already versioned or not, are searched for files or
180
subdirectories that are neither versioned or ignored, and these
181
are added. This search proceeds recursively into versioned
182
directories. If no names are given '.' is assumed.
184
Therefore simply saying 'bzr add' will version all files that
185
are currently unknown.
187
Adding a file whose parent directory is not versioned will
188
implicitly add the parent, and so on up to the root. This means
189
you should never need to explictly add a directory, they'll just
190
get added when you add a file in the directory.
192
takes_args = ['file*']
193
takes_options = ['no-recurse', 'quiet']
195
def run(self, file_list, no_recurse=False, quiet=False):
196
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
198
reporter = add_reporter_null
200
reporter = add_reporter_print
201
smart_add(file_list, not no_recurse, reporter)
204
class cmd_mkdir(Command):
205
"""Create a new versioned directory.
207
This is equivalent to creating the directory and then adding it.
209
takes_args = ['dir+']
211
def run(self, dir_list):
217
b = Branch.open_containing(d)[0]
222
class cmd_relpath(Command):
223
"""Show path of a file relative to root"""
224
takes_args = ['filename']
228
def run(self, filename):
229
branch, relpath = Branch.open_containing(filename)
233
class cmd_inventory(Command):
234
"""Show inventory of the current working copy or a revision."""
235
takes_options = ['revision', 'show-ids']
238
def run(self, revision=None, show_ids=False):
239
b = Branch.open_containing('.')[0]
241
inv = b.read_working_inventory()
243
if len(revision) > 1:
244
raise BzrCommandError('bzr inventory --revision takes'
245
' exactly one revision identifier')
246
inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
248
for path, entry in inv.entries():
250
print '%-50s %s' % (path, entry.file_id)
255
class cmd_move(Command):
256
"""Move files to a different directory.
261
The destination must be a versioned directory in the same branch.
263
takes_args = ['source$', 'dest']
264
def run(self, source_list, dest):
265
b = Branch.open_containing('.')[0]
267
# TODO: glob expansion on windows?
268
tree = WorkingTree(b.base, b)
269
b.move([tree.relpath(s) for s in source_list], tree.relpath(dest))
272
class cmd_rename(Command):
273
"""Change the name of an entry.
276
bzr rename frob.c frobber.c
277
bzr rename src/frob.c lib/frob.c
279
It is an error if the destination name exists.
281
See also the 'move' command, which moves files into a different
282
directory without changing their name.
284
# TODO: Some way to rename multiple files without invoking
285
# bzr for each one?"""
286
takes_args = ['from_name', 'to_name']
288
def run(self, from_name, to_name):
289
b = Branch.open_containing('.')[0]
290
tree = WorkingTree(b.base, b)
291
b.rename_one(tree.relpath(from_name), tree.relpath(to_name))
294
class cmd_mv(Command):
295
"""Move or rename a file.
298
bzr mv OLDNAME NEWNAME
299
bzr mv SOURCE... DESTINATION
301
If the last argument is a versioned directory, all the other names
302
are moved into it. Otherwise, there must be exactly two arguments
303
and the file is changed to a new name, which must not already exist.
305
Files cannot be moved between branches.
307
takes_args = ['names*']
308
def run(self, names_list):
309
if len(names_list) < 2:
310
raise BzrCommandError("missing file argument")
311
b = Branch.open_containing(names_list[0])[0]
312
tree = WorkingTree(b.base, b)
313
rel_names = [tree.relpath(x) for x in names_list]
315
if os.path.isdir(names_list[-1]):
316
# move into existing directory
317
for pair in b.move(rel_names[:-1], rel_names[-1]):
318
print "%s => %s" % pair
320
if len(names_list) != 2:
321
raise BzrCommandError('to mv multiple files the destination '
322
'must be a versioned directory')
323
b.rename_one(rel_names[0], rel_names[1])
324
print "%s => %s" % (rel_names[0], rel_names[1])
329
class cmd_pull(Command):
330
"""Pull any changes from another branch into the current one.
332
If the location is omitted, the last-used location will be used.
333
Both the revision history and the working directory will be
336
This command only works on branches that have not diverged. Branches are
337
considered diverged if both branches have had commits without first
338
pulling from the other.
340
If branches have diverged, you can use 'bzr merge' to pull the text changes
341
from one into the other.
343
takes_options = ['remember', 'clobber']
344
takes_args = ['location?']
346
def run(self, location=None, remember=False, clobber=False):
347
from bzrlib.merge import merge
349
from shutil import rmtree
352
br_to = Branch.open_containing('.')[0]
353
stored_loc = br_to.get_parent()
355
if stored_loc is None:
356
raise BzrCommandError("No pull location known or specified.")
358
print "Using saved location: %s" % stored_loc
359
location = stored_loc
360
br_from = Branch.open(location)
362
br_to.working_tree().pull(br_from, remember, clobber)
363
except DivergedBranches:
364
raise BzrCommandError("These branches have diverged."
368
class cmd_branch(Command):
369
"""Create a new copy of a branch.
371
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
372
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
374
To retrieve the branch as of a particular revision, supply the --revision
375
parameter, as in "branch foo/bar -r 5".
377
--basis is to speed up branching from remote branches. When specified, it
378
copies all the file-contents, inventory and revision data from the basis
379
branch before copying anything from the remote branch.
381
takes_args = ['from_location', 'to_location?']
382
takes_options = ['revision', 'basis']
383
aliases = ['get', 'clone']
385
def run(self, from_location, to_location=None, revision=None, basis=None):
386
from bzrlib.clone import copy_branch
389
from shutil import rmtree
390
cache_root = tempfile.mkdtemp()
393
elif len(revision) > 1:
394
raise BzrCommandError(
395
'bzr branch --revision takes exactly 1 revision value')
397
br_from = Branch.open(from_location)
399
if e.errno == errno.ENOENT:
400
raise BzrCommandError('Source location "%s" does not'
401
' exist.' % to_location)
406
br_from.setup_caching(cache_root)
407
if basis is not None:
408
basis_branch = Branch.open_containing(basis)[0]
411
if len(revision) == 1 and revision[0] is not None:
412
revision_id = revision[0].in_history(br_from)[1]
415
if to_location is None:
416
to_location = os.path.basename(from_location.rstrip("/\\"))
418
os.mkdir(to_location)
420
if e.errno == errno.EEXIST:
421
raise BzrCommandError('Target directory "%s" already'
422
' exists.' % to_location)
423
if e.errno == errno.ENOENT:
424
raise BzrCommandError('Parent of "%s" does not exist.' %
429
copy_branch(br_from, to_location, revision_id, basis_branch)
430
except bzrlib.errors.NoSuchRevision:
432
msg = "The branch %s has no revision %s." % (from_location, revision[0])
433
raise BzrCommandError(msg)
434
except bzrlib.errors.UnlistableBranch:
435
msg = "The branch %s cannot be used as a --basis"
441
class cmd_renames(Command):
442
"""Show list of renamed files.
444
# TODO: Option to show renames between two historical versions.
446
# TODO: Only show renames under dir, rather than in the whole branch.
447
takes_args = ['dir?']
450
def run(self, dir='.'):
451
b = Branch.open_containing(dir)[0]
452
old_inv = b.basis_tree().inventory
453
new_inv = b.read_working_inventory()
455
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
457
for old_name, new_name in renames:
458
print "%s => %s" % (old_name, new_name)
461
class cmd_info(Command):
462
"""Show statistical information about a branch."""
463
takes_args = ['branch?']
466
def run(self, branch=None):
468
b = Branch.open_containing(branch)[0]
472
class cmd_remove(Command):
473
"""Make a file unversioned.
475
This makes bzr stop tracking changes to a versioned file. It does
476
not delete the working copy.
478
takes_args = ['file+']
479
takes_options = ['verbose']
482
def run(self, file_list, verbose=False):
483
b = Branch.open_containing(file_list[0])[0]
484
tree = WorkingTree(b.base, b)
485
tree.remove([tree.relpath(f) for f in file_list], verbose=verbose)
488
class cmd_file_id(Command):
489
"""Print file_id of a particular file or directory.
491
The file_id is assigned when the file is first added and remains the
492
same through all revisions where the file exists, even when it is
496
takes_args = ['filename']
498
def run(self, filename):
499
b, relpath = Branch.open_containing(filename)
500
i = b.inventory.path2id(relpath)
502
raise BzrError("%r is not a versioned file" % filename)
507
class cmd_file_path(Command):
508
"""Print path of file_ids to a file or directory.
510
This prints one line for each directory down to the target,
511
starting at the branch root."""
513
takes_args = ['filename']
515
def run(self, filename):
516
b, relpath = Branch.open_containing(filename)
518
fid = inv.path2id(relpath)
520
raise BzrError("%r is not a versioned file" % filename)
521
for fip in inv.get_idpath(fid):
525
class cmd_revision_history(Command):
526
"""Display list of revision ids on this branch."""
530
for patchid in Branch.open_containing('.')[0].revision_history():
534
class cmd_ancestry(Command):
535
"""List all revisions merged into this branch."""
539
b = Branch.open_containing('.')[0]
540
for revision_id in b.get_ancestry(b.last_revision()):
544
class cmd_directories(Command):
545
"""Display list of versioned directories in this branch."""
548
for name, ie in Branch.open_containing('.')[0].read_working_inventory().directories():
555
class cmd_init(Command):
556
"""Make a directory into a versioned branch.
558
Use this to create an empty branch, or before importing an
561
Recipe for importing a tree of files:
566
bzr commit -m 'imported project'
569
Branch.initialize('.')
572
class cmd_diff(Command):
573
"""Show differences in working tree.
575
If files are listed, only the changes in those files are listed.
576
Otherwise, all changes for the tree are listed.
583
# TODO: Allow diff across branches.
584
# TODO: Option to use external diff command; could be GNU diff, wdiff,
585
# or a graphical diff.
587
# TODO: Python difflib is not exactly the same as unidiff; should
588
# either fix it up or prefer to use an external diff.
590
# TODO: If a directory is given, diff everything under that.
592
# TODO: Selected-file diff is inefficient and doesn't show you
595
# TODO: This probably handles non-Unix newlines poorly.
597
takes_args = ['file*']
598
takes_options = ['revision', 'diff-options']
599
aliases = ['di', 'dif']
602
def run(self, revision=None, file_list=None, diff_options=None):
603
from bzrlib.diff import show_diff
606
b = Branch.open_containing(file_list[0])[0]
607
tree = WorkingTree(b.base, b)
608
file_list = [tree.relpath(f) for f in file_list]
609
if file_list == ['']:
610
# just pointing to top-of-tree
613
b = Branch.open_containing('.')[0]
615
if revision is not None:
616
if len(revision) == 1:
617
show_diff(b, revision[0], specific_files=file_list,
618
external_diff_options=diff_options)
619
elif len(revision) == 2:
620
show_diff(b, revision[0], specific_files=file_list,
621
external_diff_options=diff_options,
622
revision2=revision[1])
624
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
626
show_diff(b, None, specific_files=file_list,
627
external_diff_options=diff_options)
632
class cmd_deleted(Command):
633
"""List files deleted in the working tree.
635
# TODO: Show files deleted since a previous revision, or
636
# between two revisions.
637
# TODO: Much more efficient way to do this: read in new
638
# directories with readdir, rather than stating each one. Same
639
# level of effort but possibly much less IO. (Or possibly not,
640
# if the directories are very large...)
642
def run(self, show_ids=False):
643
b = Branch.open_containing('.')[0]
645
new = b.working_tree()
646
for path, ie in old.inventory.iter_entries():
647
if not new.has_id(ie.file_id):
649
print '%-50s %s' % (path, ie.file_id)
654
class cmd_modified(Command):
655
"""List files modified in working tree."""
659
from bzrlib.delta import compare_trees
661
b = Branch.open_containing('.')[0]
662
td = compare_trees(b.basis_tree(), b.working_tree())
664
for path, id, kind, text_modified, meta_modified in td.modified:
669
class cmd_added(Command):
670
"""List files added in working tree."""
674
b = Branch.open_containing('.')[0]
675
wt = b.working_tree()
676
basis_inv = b.basis_tree().inventory
679
if file_id in basis_inv:
681
path = inv.id2path(file_id)
682
if not os.access(b.abspath(path), os.F_OK):
688
class cmd_root(Command):
689
"""Show the tree root directory.
691
The root is the nearest enclosing directory with a .bzr control
693
takes_args = ['filename?']
695
def run(self, filename=None):
696
"""Print the branch root."""
697
b = Branch.open_containing(filename)[0]
701
class cmd_log(Command):
702
"""Show log of this branch.
704
To request a range of logs, you can use the command -r begin:end
705
-r revision requests a specific revision, -r :end or -r begin: are
709
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
711
takes_args = ['filename?']
712
takes_options = [Option('forward',
713
help='show from oldest to newest'),
714
'timezone', 'verbose',
715
'show-ids', 'revision',
716
Option('line', help='format with one line per revision'),
719
help='show revisions whose message matches this regexp',
721
Option('short', help='use moderately short format'),
724
def run(self, filename=None, timezone='original',
733
from bzrlib.log import log_formatter, show_log
735
assert message is None or isinstance(message, basestring), \
736
"invalid message argument %r" % message
737
direction = (forward and 'forward') or 'reverse'
740
b, fp = Branch.open_containing(filename)
742
file_id = b.read_working_inventory().path2id(fp)
744
file_id = None # points to branch root
746
b, relpath = Branch.open_containing('.')
752
elif len(revision) == 1:
753
rev1 = rev2 = revision[0].in_history(b).revno
754
elif len(revision) == 2:
755
rev1 = revision[0].in_history(b).revno
756
rev2 = revision[1].in_history(b).revno
758
raise BzrCommandError('bzr log --revision takes one or two values.')
765
mutter('encoding log as %r' % bzrlib.user_encoding)
767
# use 'replace' so that we don't abort if trying to write out
768
# in e.g. the default C locale.
769
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
776
lf = log_formatter(log_format,
779
show_timezone=timezone)
792
class cmd_touching_revisions(Command):
793
"""Return revision-ids which affected a particular file.
795
A more user-friendly interface is "bzr log FILE"."""
797
takes_args = ["filename"]
799
def run(self, filename):
800
b, relpath = Branch.open_containing(filename)[0]
801
inv = b.read_working_inventory()
802
file_id = inv.path2id(relpath)
803
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
804
print "%6d %s" % (revno, what)
807
class cmd_ls(Command):
808
"""List files in a tree.
810
# TODO: Take a revision or remote path and list that tree instead.
813
def run(self, revision=None, verbose=False):
814
b, relpath = Branch.open_containing('.')[0]
816
tree = b.working_tree()
818
tree = b.revision_tree(revision.in_history(b).rev_id)
819
for fp, fc, kind, fid, entry in tree.list_files():
821
kindch = entry.kind_character()
822
print '%-8s %s%s' % (fc, fp, kindch)
828
class cmd_unknowns(Command):
829
"""List unknown files."""
832
from bzrlib.osutils import quotefn
833
for f in Branch.open_containing('.')[0].unknowns():
838
class cmd_ignore(Command):
839
"""Ignore a command or pattern.
841
To remove patterns from the ignore list, edit the .bzrignore file.
843
If the pattern contains a slash, it is compared to the whole path
844
from the branch root. Otherwise, it is compared to only the last
845
component of the path. To match a file only in the root directory,
848
Ignore patterns are case-insensitive on case-insensitive systems.
850
Note: wildcards must be quoted from the shell on Unix.
853
bzr ignore ./Makefile
856
# TODO: Complain if the filename is absolute
857
takes_args = ['name_pattern']
859
def run(self, name_pattern):
860
from bzrlib.atomicfile import AtomicFile
863
b, relpath = Branch.open_containing('.')
864
ifn = b.abspath('.bzrignore')
866
if os.path.exists(ifn):
869
igns = f.read().decode('utf-8')
875
# TODO: If the file already uses crlf-style termination, maybe
876
# we should use that for the newly added lines?
878
if igns and igns[-1] != '\n':
880
igns += name_pattern + '\n'
883
f = AtomicFile(ifn, 'wt')
884
f.write(igns.encode('utf-8'))
889
inv = b.working_tree().inventory
890
if inv.path2id('.bzrignore'):
891
mutter('.bzrignore is already versioned')
893
mutter('need to make new .bzrignore file versioned')
894
b.add(['.bzrignore'])
898
class cmd_ignored(Command):
899
"""List ignored files and the patterns that matched them.
901
See also: bzr ignore"""
904
tree = Branch.open_containing('.')[0].working_tree()
905
for path, file_class, kind, file_id, entry in tree.list_files():
906
if file_class != 'I':
908
## XXX: Slightly inefficient since this was already calculated
909
pat = tree.is_ignored(path)
910
print '%-50s %s' % (path, pat)
913
class cmd_lookup_revision(Command):
914
"""Lookup the revision-id from a revision-number
917
bzr lookup-revision 33
920
takes_args = ['revno']
923
def run(self, revno):
927
raise BzrCommandError("not a valid revision-number: %r" % revno)
929
print Branch.open_containing('.')[0].get_rev_id(revno)
932
class cmd_export(Command):
933
"""Export past revision to destination directory.
935
If no revision is specified this exports the last committed revision.
937
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
938
given, try to find the format with the extension. If no extension
939
is found exports to a directory (equivalent to --format=dir).
941
Root may be the top directory for tar, tgz and tbz2 formats. If none
942
is given, the top directory will be the root name of the file."""
943
# TODO: list known exporters
944
takes_args = ['dest']
945
takes_options = ['revision', 'format', 'root']
946
def run(self, dest, revision=None, format=None, root=None):
948
b = Branch.open_containing('.')[0]
950
rev_id = b.last_revision()
952
if len(revision) != 1:
953
raise BzrError('bzr export --revision takes exactly 1 argument')
954
rev_id = revision[0].in_history(b).rev_id
955
t = b.revision_tree(rev_id)
956
arg_root, ext = os.path.splitext(os.path.basename(dest))
957
if ext in ('.gz', '.bz2'):
958
new_root, new_ext = os.path.splitext(arg_root)
959
if new_ext == '.tar':
967
elif ext in (".tar.gz", ".tgz"):
969
elif ext in (".tar.bz2", ".tbz2"):
973
t.export(dest, format, root)
976
class cmd_cat(Command):
977
"""Write a file's text from a previous revision."""
979
takes_options = ['revision']
980
takes_args = ['filename']
983
def run(self, filename, revision=None):
985
raise BzrCommandError("bzr cat requires a revision number")
986
elif len(revision) != 1:
987
raise BzrCommandError("bzr cat --revision takes exactly one number")
988
b, relpath = Branch.open_containing(filename)
989
b.print_file(relpath, revision[0].in_history(b).revno)
992
class cmd_local_time_offset(Command):
993
"""Show the offset in seconds from GMT to local time."""
997
print bzrlib.osutils.local_time_offset()
1001
class cmd_commit(Command):
1002
"""Commit changes into a new revision.
1004
If no arguments are given, the entire tree is committed.
1006
If selected files are specified, only changes to those files are
1007
committed. If a directory is specified then the directory and everything
1008
within it is committed.
1010
A selected-file commit may fail in some cases where the committed
1011
tree would be invalid, such as trying to commit a file in a
1012
newly-added directory that is not itself committed.
1014
# TODO: Run hooks on tree to-be-committed, and after commit.
1016
# TODO: Strict commit that fails if there are deleted files.
1017
# (what does "deleted files" mean ??)
1019
# TODO: Give better message for -s, --summary, used by tla people
1021
# XXX: verbose currently does nothing
1023
takes_args = ['selected*']
1024
takes_options = ['message', 'verbose',
1026
help='commit even if nothing has changed'),
1027
Option('file', type=str,
1029
help='file containing commit message'),
1031
help="refuse to commit if there are unknown "
1032
"files in the working tree."),
1034
aliases = ['ci', 'checkin']
1036
def run(self, message=None, file=None, verbose=True, selected_list=None,
1037
unchanged=False, strict=False):
1038
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1040
from bzrlib.msgeditor import edit_commit_message
1041
from bzrlib.status import show_status
1042
from cStringIO import StringIO
1044
b = Branch.open_containing('.')[0]
1045
tree = WorkingTree(b.base, b)
1047
selected_list = [tree.relpath(s) for s in selected_list]
1048
if message is None and not file:
1049
catcher = StringIO()
1050
show_status(b, specific_files=selected_list,
1052
message = edit_commit_message(catcher.getvalue())
1055
raise BzrCommandError("please specify a commit message"
1056
" with either --message or --file")
1057
elif message and file:
1058
raise BzrCommandError("please specify either --message or --file")
1062
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1065
raise BzrCommandError("empty commit message specified")
1068
b.commit(message, specific_files=selected_list,
1069
allow_pointless=unchanged, strict=strict)
1070
except PointlessCommit:
1071
# FIXME: This should really happen before the file is read in;
1072
# perhaps prepare the commit; get the message; then actually commit
1073
raise BzrCommandError("no changes to commit",
1074
["use --unchanged to commit anyhow"])
1075
except ConflictsInTree:
1076
raise BzrCommandError("Conflicts detected in working tree. "
1077
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1078
except StrictCommitFailed:
1079
raise BzrCommandError("Commit refused because there are unknown "
1080
"files in the working tree.")
1083
class cmd_check(Command):
1084
"""Validate consistency of branch history.
1086
This command checks various invariants about the branch storage to
1087
detect data corruption or bzr bugs.
1089
takes_args = ['dir?']
1090
takes_options = ['verbose']
1092
def run(self, dir='.', verbose=False):
1093
from bzrlib.check import check
1094
check(Branch.open_containing(dir)[0], verbose)
1097
class cmd_scan_cache(Command):
1100
from bzrlib.hashcache import HashCache
1106
print '%6d stats' % c.stat_count
1107
print '%6d in hashcache' % len(c._cache)
1108
print '%6d files removed from cache' % c.removed_count
1109
print '%6d hashes updated' % c.update_count
1110
print '%6d files changed too recently to cache' % c.danger_count
1117
class cmd_upgrade(Command):
1118
"""Upgrade branch storage to current format.
1120
The check command or bzr developers may sometimes advise you to run
1123
This version of this command upgrades from the full-text storage
1124
used by bzr 0.0.8 and earlier to the weave format (v5).
1126
takes_args = ['dir?']
1128
def run(self, dir='.'):
1129
from bzrlib.upgrade import upgrade
1133
class cmd_whoami(Command):
1134
"""Show bzr user id."""
1135
takes_options = ['email']
1138
def run(self, email=False):
1140
b = bzrlib.branch.Branch.open_containing('.')[0]
1141
config = bzrlib.config.BranchConfig(b)
1142
except NotBranchError:
1143
config = bzrlib.config.GlobalConfig()
1146
print config.user_email()
1148
print config.username()
1151
class cmd_selftest(Command):
1152
"""Run internal test suite.
1154
This creates temporary test directories in the working directory,
1155
but not existing data is affected. These directories are deleted
1156
if the tests pass, or left behind to help in debugging if they
1159
If arguments are given, they are regular expressions that say
1160
which tests should run.
1162
# TODO: --list should give a list of all available tests
1164
takes_args = ['testspecs*']
1165
takes_options = ['verbose',
1166
Option('one', help='stop when one test fails'),
1169
def run(self, testspecs_list=None, verbose=False, one=False):
1171
from bzrlib.selftest import selftest
1172
# we don't want progress meters from the tests to go to the
1173
# real output; and we don't want log messages cluttering up
1175
save_ui = bzrlib.ui.ui_factory
1176
bzrlib.trace.info('running tests...')
1178
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1179
if testspecs_list is not None:
1180
pattern = '|'.join(testspecs_list)
1183
result = selftest(verbose=verbose,
1185
stop_on_failure=one)
1187
bzrlib.trace.info('tests passed')
1189
bzrlib.trace.info('tests failed')
1190
return int(not result)
1192
bzrlib.ui.ui_factory = save_ui
1196
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1197
# is bzrlib itself in a branch?
1198
bzrrev = bzrlib.get_bzr_revision()
1200
print " (bzr checkout, revision %d {%s})" % bzrrev
1201
print bzrlib.__copyright__
1202
print "http://bazaar-ng.org/"
1204
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1205
print "you may use, modify and redistribute it under the terms of the GNU"
1206
print "General Public License version 2 or later."
1209
class cmd_version(Command):
1210
"""Show version of bzr."""
1215
class cmd_rocks(Command):
1216
"""Statement of optimism."""
1220
print "it sure does!"
1223
class cmd_find_merge_base(Command):
1224
"""Find and print a base revision for merging two branches.
1226
# TODO: Options to specify revisions on either side, as if
1227
# merging only part of the history.
1228
takes_args = ['branch', 'other']
1232
def run(self, branch, other):
1233
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1235
branch1 = Branch.open_containing(branch)[0]
1236
branch2 = Branch.open_containing(other)[0]
1238
history_1 = branch1.revision_history()
1239
history_2 = branch2.revision_history()
1241
last1 = branch1.last_revision()
1242
last2 = branch2.last_revision()
1244
source = MultipleRevisionSources(branch1, branch2)
1246
base_rev_id = common_ancestor(last1, last2, source)
1248
print 'merge base is revision %s' % base_rev_id
1252
if base_revno is None:
1253
raise bzrlib.errors.UnrelatedBranches()
1255
print ' r%-6d in %s' % (base_revno, branch)
1257
other_revno = branch2.revision_id_to_revno(base_revid)
1259
print ' r%-6d in %s' % (other_revno, other)
1263
class cmd_merge(Command):
1264
"""Perform a three-way merge.
1266
The branch is the branch you will merge from. By default, it will
1267
merge the latest revision. If you specify a revision, that
1268
revision will be merged. If you specify two revisions, the first
1269
will be used as a BASE, and the second one as OTHER. Revision
1270
numbers are always relative to the specified branch.
1272
By default bzr will try to merge in all new work from the other
1273
branch, automatically determining an appropriate base. If this
1274
fails, you may need to give an explicit base.
1278
To merge the latest revision from bzr.dev
1279
bzr merge ../bzr.dev
1281
To merge changes up to and including revision 82 from bzr.dev
1282
bzr merge -r 82 ../bzr.dev
1284
To merge the changes introduced by 82, without previous changes:
1285
bzr merge -r 81..82 ../bzr.dev
1287
merge refuses to run if there are any uncommitted changes, unless
1290
takes_args = ['branch?']
1291
takes_options = ['revision', 'force', 'merge-type',
1292
Option('show-base', help="Show base revision text in "
1295
def run(self, branch=None, revision=None, force=False, merge_type=None,
1297
from bzrlib.merge import merge
1298
from bzrlib.merge_core import ApplyMerge3
1299
if merge_type is None:
1300
merge_type = ApplyMerge3
1302
branch = Branch.open_containing('.')[0].get_parent()
1304
raise BzrCommandError("No merge location known or specified.")
1306
print "Using saved location: %s" % branch
1307
if revision is None or len(revision) < 1:
1309
other = [branch, -1]
1311
if len(revision) == 1:
1313
other_branch = Branch.open_containing(branch)[0]
1314
revno = revision[0].in_history(other_branch).revno
1315
other = [branch, revno]
1317
assert len(revision) == 2
1318
if None in revision:
1319
raise BzrCommandError(
1320
"Merge doesn't permit that revision specifier.")
1321
b = Branch.open_containing(branch)[0]
1323
base = [branch, revision[0].in_history(b).revno]
1324
other = [branch, revision[1].in_history(b).revno]
1327
conflict_count = merge(other, base, check_clean=(not force),
1328
merge_type=merge_type,
1329
show_base=show_base)
1330
if conflict_count != 0:
1334
except bzrlib.errors.AmbiguousBase, e:
1335
m = ("sorry, bzr can't determine the right merge base yet\n"
1336
"candidates are:\n "
1337
+ "\n ".join(e.bases)
1339
"please specify an explicit base with -r,\n"
1340
"and (if you want) report this to the bzr developers\n")
1344
class cmd_revert(Command):
1345
"""Reverse all changes since the last commit.
1347
Only versioned files are affected. Specify filenames to revert only
1348
those files. By default, any files that are changed will be backed up
1349
first. Backup files have a '~' appended to their name.
1351
takes_options = ['revision', 'no-backup']
1352
takes_args = ['file*']
1353
aliases = ['merge-revert']
1355
def run(self, revision=None, no_backup=False, file_list=None):
1356
from bzrlib.merge import merge
1357
from bzrlib.commands import parse_spec
1359
if file_list is not None:
1360
if len(file_list) == 0:
1361
raise BzrCommandError("No files specified")
1362
if revision is None:
1364
elif len(revision) != 1:
1365
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1367
b = Branch.open_containing('.')[0]
1368
revno = revision[0].in_history(b).revno
1369
merge(('.', revno), parse_spec('.'),
1372
backup_files=not no_backup,
1373
file_list=file_list)
1375
Branch.open_containing('.')[0].set_pending_merges([])
1378
class cmd_assert_fail(Command):
1379
"""Test reporting of assertion failures"""
1382
assert False, "always fails"
1385
class cmd_help(Command):
1386
"""Show help on a command or other topic.
1388
For a list of all available commands, say 'bzr help commands'."""
1389
takes_options = ['long']
1390
takes_args = ['topic?']
1394
def run(self, topic=None, long=False):
1396
if topic is None and long:
1401
class cmd_shell_complete(Command):
1402
"""Show appropriate completions for context.
1404
For a list of all available commands, say 'bzr shell-complete'."""
1405
takes_args = ['context?']
1410
def run(self, context=None):
1411
import shellcomplete
1412
shellcomplete.shellcomplete(context)
1415
class cmd_fetch(Command):
1416
"""Copy in history from another branch but don't merge it.
1418
This is an internal method used for pull and merge."""
1420
takes_args = ['from_branch', 'to_branch']
1421
def run(self, from_branch, to_branch):
1422
from bzrlib.fetch import Fetcher
1423
from bzrlib.branch import Branch
1424
from_b = Branch(from_branch)
1425
to_b = Branch(to_branch)
1426
Fetcher(to_b, from_b)
1430
class cmd_missing(Command):
1431
"""What is missing in this branch relative to other branch.
1433
# TODO: rewrite this in terms of ancestry so that it shows only
1436
takes_args = ['remote?']
1437
aliases = ['mis', 'miss']
1438
# We don't have to add quiet to the list, because
1439
# unknown options are parsed as booleans
1440
takes_options = ['verbose', 'quiet']
1443
def run(self, remote=None, verbose=False, quiet=False):
1444
from bzrlib.errors import BzrCommandError
1445
from bzrlib.missing import show_missing
1447
if verbose and quiet:
1448
raise BzrCommandError('Cannot pass both quiet and verbose')
1450
b = Branch.open_containing('.')[0]
1451
parent = b.get_parent()
1454
raise BzrCommandError("No missing location known or specified.")
1457
print "Using last location: %s" % parent
1459
elif parent is None:
1460
# We only update parent if it did not exist, missing
1461
# should not change the parent
1462
b.set_parent(remote)
1463
br_remote = Branch.open_containing(remote)[0]
1464
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1467
class cmd_plugins(Command):
1472
import bzrlib.plugin
1473
from inspect import getdoc
1474
for plugin in bzrlib.plugin.all_plugins:
1475
if hasattr(plugin, '__path__'):
1476
print plugin.__path__[0]
1477
elif hasattr(plugin, '__file__'):
1478
print plugin.__file__
1484
print '\t', d.split('\n')[0]
1487
class cmd_testament(Command):
1488
"""Show testament (signing-form) of a revision."""
1489
takes_options = ['revision', 'long']
1490
takes_args = ['branch?']
1492
def run(self, branch='.', revision=None, long=False):
1493
from bzrlib.testament import Testament
1494
b = Branch.open_containing(branch)[0]
1497
if revision is None:
1498
rev_id = b.last_revision()
1500
rev_id = revision[0].in_history(b).rev_id
1501
t = Testament.from_revision(b, rev_id)
1503
sys.stdout.writelines(t.as_text_lines())
1505
sys.stdout.write(t.as_short_text())
1510
class cmd_annotate(Command):
1511
"""Show the origin of each line in a file.
1513
This prints out the given file with an annotation on the left side
1514
indicating which revision, author and date introduced the change.
1516
If the origin is the same for a run of consecutive lines, it is
1517
shown only at the top, unless the --all option is given.
1519
# TODO: annotate directories; showing when each file was last changed
1520
# TODO: annotate a previous version of a file
1521
# TODO: if the working copy is modified, show annotations on that
1522
# with new uncommitted lines marked
1523
aliases = ['blame', 'praise']
1524
takes_args = ['filename']
1525
takes_options = [Option('all', help='show annotations on all lines'),
1526
Option('long', help='show date in annotations'),
1530
def run(self, filename, all=False, long=False):
1531
from bzrlib.annotate import annotate_file
1532
b, relpath = Branch.open_containing(filename)
1535
tree = WorkingTree(b.base, b)
1536
tree = b.revision_tree(b.last_revision())
1537
file_id = tree.inventory.path2id(relpath)
1538
file_version = tree.inventory[file_id].revision
1539
annotate_file(b, file_version, file_id, long, all, sys.stdout)
1544
class cmd_re_sign(Command):
1545
"""Create a digital signature for an existing revision."""
1546
# TODO be able to replace existing ones.
1548
hidden = True # is this right ?
1549
takes_args = ['revision_id?']
1550
takes_options = ['revision']
1552
def run(self, revision_id=None, revision=None):
1553
import bzrlib.config as config
1554
import bzrlib.gpg as gpg
1555
if revision_id is not None and revision is not None:
1556
raise BzrCommandError('You can only supply one of revision_id or --revision')
1557
if revision_id is None and revision is None:
1558
raise BzrCommandError('You must supply either --revision or a revision_id')
1559
b = Branch.open_containing('.')[0]
1560
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1561
if revision_id is not None:
1562
b.sign_revision(revision_id, gpg_strategy)
1563
elif revision is not None:
1564
for rev in revision:
1566
raise BzrCommandError('You cannot specify a NULL revision.')
1567
revno, rev_id = rev.in_history(b)
1568
b.sign_revision(rev_id, gpg_strategy)
1571
# these get imported and then picked up by the scan for cmd_*
1572
# TODO: Some more consistent way to split command definitions across files;
1573
# we do need to load at least some information about them to know of
1575
from bzrlib.conflicts import cmd_resolve, cmd_conflicts