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.
73
# XXX: FIXME: bzr status should accept a -r option to show changes
74
# relative to a revision, or between revisions
76
takes_args = ['file*']
77
takes_options = ['all', 'show-ids']
78
aliases = ['st', 'stat']
81
def run(self, all=False, show_ids=False, file_list=None, revision=None):
83
b, relpath = Branch.open_containing(file_list[0])
84
if relpath == '' and len(file_list) == 1:
87
# generate relative paths.
88
# note that if this is a remote branch, we would want
89
# relpath against the transport. RBC 20051018
90
tree = WorkingTree(b.base, b)
91
file_list = [tree.relpath(x) for x in file_list]
93
b = Branch.open_containing('.')[0]
95
from bzrlib.status import show_status
96
show_status(b, show_unchanged=all, show_ids=show_ids,
97
specific_files=file_list, revision=revision)
100
class cmd_cat_revision(Command):
101
"""Write out metadata for a revision.
103
The revision to print can either be specified by a specific
104
revision identifier, or you can use --revision.
108
takes_args = ['revision_id?']
109
takes_options = ['revision']
112
def run(self, revision_id=None, revision=None):
114
if revision_id is not None and revision is not None:
115
raise BzrCommandError('You can only supply one of revision_id or --revision')
116
if revision_id is None and revision is None:
117
raise BzrCommandError('You must supply either --revision or a revision_id')
118
b = Branch.open_containing('.')[0]
119
if revision_id is not None:
120
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
121
elif revision is not None:
124
raise BzrCommandError('You cannot specify a NULL revision.')
125
revno, rev_id = rev.in_history(b)
126
sys.stdout.write(b.get_revision_xml_file(rev_id).read())
129
class cmd_revno(Command):
130
"""Show current revision number.
132
This is equal to the number of revisions on this branch."""
135
print Branch.open_containing('.')[0].revno()
138
class cmd_revision_info(Command):
139
"""Show revision number and revision id for a given revision identifier.
142
takes_args = ['revision_info*']
143
takes_options = ['revision']
145
def run(self, revision=None, revision_info_list=[]):
148
if revision is not None:
149
revs.extend(revision)
150
if revision_info_list is not None:
151
for rev in revision_info_list:
152
revs.append(RevisionSpec(rev))
154
raise BzrCommandError('You must supply a revision identifier')
156
b = Branch.open_containing('.')[0]
159
revinfo = rev.in_history(b)
160
if revinfo.revno is None:
161
print ' %s' % revinfo.rev_id
163
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
166
class cmd_add(Command):
167
"""Add specified files or directories.
169
In non-recursive mode, all the named items are added, regardless
170
of whether they were previously ignored. A warning is given if
171
any of the named files are already versioned.
173
In recursive mode (the default), files are treated the same way
174
but the behaviour for directories is different. Directories that
175
are already versioned do not give a warning. All directories,
176
whether already versioned or not, are searched for files or
177
subdirectories that are neither versioned or ignored, and these
178
are added. This search proceeds recursively into versioned
179
directories. If no names are given '.' is assumed.
181
Therefore simply saying 'bzr add' will version all files that
182
are currently unknown.
184
Adding a file whose parent directory is not versioned will
185
implicitly add the parent, and so on up to the root. This means
186
you should never need to explictly add a directory, they'll just
187
get added when you add a file in the directory.
189
takes_args = ['file*']
190
takes_options = ['no-recurse', 'quiet']
192
def run(self, file_list, no_recurse=False, quiet=False):
193
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
195
reporter = add_reporter_null
197
reporter = add_reporter_print
198
smart_add(file_list, not no_recurse, reporter)
201
class cmd_mkdir(Command):
202
"""Create a new versioned directory.
204
This is equivalent to creating the directory and then adding it.
206
takes_args = ['dir+']
208
def run(self, dir_list):
214
b = Branch.open_containing(d)[0]
219
class cmd_relpath(Command):
220
"""Show path of a file relative to root"""
221
takes_args = ['filename']
225
def run(self, filename):
226
branch, relpath = Branch.open_containing(filename)
230
class cmd_inventory(Command):
231
"""Show inventory of the current working copy or a revision."""
232
takes_options = ['revision', 'show-ids']
235
def run(self, revision=None, show_ids=False):
236
b = Branch.open_containing('.')[0]
238
inv = b.read_working_inventory()
240
if len(revision) > 1:
241
raise BzrCommandError('bzr inventory --revision takes'
242
' exactly one revision identifier')
243
inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
245
for path, entry in inv.entries():
247
print '%-50s %s' % (path, entry.file_id)
252
class cmd_move(Command):
253
"""Move files to a different directory.
258
The destination must be a versioned directory in the same branch.
260
takes_args = ['source$', 'dest']
261
def run(self, source_list, dest):
262
b = Branch.open_containing('.')[0]
264
# TODO: glob expansion on windows?
265
tree = WorkingTree(b.base, b)
266
b.move([tree.relpath(s) for s in source_list], tree.relpath(dest))
269
class cmd_rename(Command):
270
"""Change the name of an entry.
273
bzr rename frob.c frobber.c
274
bzr rename src/frob.c lib/frob.c
276
It is an error if the destination name exists.
278
See also the 'move' command, which moves files into a different
279
directory without changing their name.
281
# TODO: Some way to rename multiple files without invoking
282
# bzr for each one?"""
283
takes_args = ['from_name', 'to_name']
285
def run(self, from_name, to_name):
286
b = Branch.open_containing('.')[0]
287
tree = WorkingTree(b.base, b)
288
b.rename_one(tree.relpath(from_name), tree.relpath(to_name))
291
class cmd_mv(Command):
292
"""Move or rename a file.
295
bzr mv OLDNAME NEWNAME
296
bzr mv SOURCE... DESTINATION
298
If the last argument is a versioned directory, all the other names
299
are moved into it. Otherwise, there must be exactly two arguments
300
and the file is changed to a new name, which must not already exist.
302
Files cannot be moved between branches.
304
takes_args = ['names*']
305
def run(self, names_list):
306
if len(names_list) < 2:
307
raise BzrCommandError("missing file argument")
308
b = Branch.open_containing(names_list[0])[0]
309
tree = WorkingTree(b.base, b)
310
rel_names = [tree.relpath(x) for x in names_list]
312
if os.path.isdir(names_list[-1]):
313
# move into existing directory
314
for pair in b.move(rel_names[:-1], rel_names[-1]):
315
print "%s => %s" % pair
317
if len(names_list) != 2:
318
raise BzrCommandError('to mv multiple files the destination '
319
'must be a versioned directory')
320
b.rename_one(rel_names[0], rel_names[1])
321
print "%s => %s" % (rel_names[0], rel_names[1])
326
class cmd_pull(Command):
327
"""Pull any changes from another branch into the current one.
329
If the location is omitted, the last-used location will be used.
330
Both the revision history and the working directory will be
333
This command only works on branches that have not diverged. Branches are
334
considered diverged if both branches have had commits without first
335
pulling from the other.
337
If branches have diverged, you can use 'bzr merge' to pull the text changes
338
from one into the other.
340
takes_options = ['remember', 'clobber']
341
takes_args = ['location?']
343
def run(self, location=None, remember=False, clobber=False):
344
from bzrlib.merge import merge
346
from shutil import rmtree
349
br_to = Branch.open_containing('.')[0]
350
stored_loc = br_to.get_parent()
352
if stored_loc is None:
353
raise BzrCommandError("No pull location known or specified.")
355
print "Using saved location: %s" % stored_loc
356
location = stored_loc
357
br_from = Branch.open(location)
359
br_to.working_tree().pull(br_from, remember, clobber)
360
except DivergedBranches:
361
raise BzrCommandError("These branches have diverged."
365
class cmd_branch(Command):
366
"""Create a new copy of a branch.
368
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
369
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
371
To retrieve the branch as of a particular revision, supply the --revision
372
parameter, as in "branch foo/bar -r 5".
374
--basis is to speed up branching from remote branches. When specified, it
375
copies all the file-contents, inventory and revision data from the basis
376
branch before copying anything from the remote branch.
378
takes_args = ['from_location', 'to_location?']
379
takes_options = ['revision', 'basis']
380
aliases = ['get', 'clone']
382
def run(self, from_location, to_location=None, revision=None, basis=None):
383
from bzrlib.clone import copy_branch
386
from shutil import rmtree
387
cache_root = tempfile.mkdtemp()
390
elif len(revision) > 1:
391
raise BzrCommandError(
392
'bzr branch --revision takes exactly 1 revision value')
394
br_from = Branch.open(from_location)
396
if e.errno == errno.ENOENT:
397
raise BzrCommandError('Source location "%s" does not'
398
' exist.' % to_location)
403
br_from.setup_caching(cache_root)
404
if basis is not None:
405
basis_branch = Branch.open_containing(basis)[0]
408
if len(revision) == 1 and revision[0] is not None:
409
revision_id = revision[0].in_history(br_from)[1]
412
if to_location is None:
413
to_location = os.path.basename(from_location.rstrip("/\\"))
415
os.mkdir(to_location)
417
if e.errno == errno.EEXIST:
418
raise BzrCommandError('Target directory "%s" already'
419
' exists.' % to_location)
420
if e.errno == errno.ENOENT:
421
raise BzrCommandError('Parent of "%s" does not exist.' %
426
copy_branch(br_from, to_location, revision_id, basis_branch)
427
except bzrlib.errors.NoSuchRevision:
429
msg = "The branch %s has no revision %d." % (from_location, revision[0])
430
raise BzrCommandError(msg)
431
except bzrlib.errors.UnlistableBranch:
432
msg = "The branch %s cannot be used as a --basis"
438
class cmd_renames(Command):
439
"""Show list of renamed files.
441
# TODO: Option to show renames between two historical versions.
443
# TODO: Only show renames under dir, rather than in the whole branch.
444
takes_args = ['dir?']
447
def run(self, dir='.'):
448
b = Branch.open_containing(dir)[0]
449
old_inv = b.basis_tree().inventory
450
new_inv = b.read_working_inventory()
452
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
454
for old_name, new_name in renames:
455
print "%s => %s" % (old_name, new_name)
458
class cmd_info(Command):
459
"""Show statistical information about a branch."""
460
takes_args = ['branch?']
463
def run(self, branch=None):
465
b = Branch.open_containing(branch)[0]
469
class cmd_remove(Command):
470
"""Make a file unversioned.
472
This makes bzr stop tracking changes to a versioned file. It does
473
not delete the working copy.
475
takes_args = ['file+']
476
takes_options = ['verbose']
479
def run(self, file_list, verbose=False):
480
b = Branch.open_containing(file_list[0])[0]
481
tree = WorkingTree(b.base, b)
482
tree.remove([tree.relpath(f) for f in file_list], verbose=verbose)
485
class cmd_file_id(Command):
486
"""Print file_id of a particular file or directory.
488
The file_id is assigned when the file is first added and remains the
489
same through all revisions where the file exists, even when it is
493
takes_args = ['filename']
495
def run(self, filename):
496
b, relpath = Branch.open_containing(filename)
497
i = b.inventory.path2id(relpath)
499
raise BzrError("%r is not a versioned file" % filename)
504
class cmd_file_path(Command):
505
"""Print path of file_ids to a file or directory.
507
This prints one line for each directory down to the target,
508
starting at the branch root."""
510
takes_args = ['filename']
512
def run(self, filename):
513
b, relpath = Branch.open_containing(filename)
515
fid = inv.path2id(relpath)
517
raise BzrError("%r is not a versioned file" % filename)
518
for fip in inv.get_idpath(fid):
522
class cmd_revision_history(Command):
523
"""Display list of revision ids on this branch."""
527
for patchid in Branch.open_containing('.')[0].revision_history():
531
class cmd_ancestry(Command):
532
"""List all revisions merged into this branch."""
536
b = Branch.open_containing('.')[0]
537
for revision_id in b.get_ancestry(b.last_revision()):
541
class cmd_directories(Command):
542
"""Display list of versioned directories in this branch."""
545
for name, ie in Branch.open_containing('.')[0].read_working_inventory().directories():
552
class cmd_init(Command):
553
"""Make a directory into a versioned branch.
555
Use this to create an empty branch, or before importing an
558
Recipe for importing a tree of files:
563
bzr commit -m 'imported project'
566
Branch.initialize('.')
569
class cmd_diff(Command):
570
"""Show differences in working tree.
572
If files are listed, only the changes in those files are listed.
573
Otherwise, all changes for the tree are listed.
580
# TODO: Allow diff across branches.
581
# TODO: Option to use external diff command; could be GNU diff, wdiff,
582
# or a graphical diff.
584
# TODO: Python difflib is not exactly the same as unidiff; should
585
# either fix it up or prefer to use an external diff.
587
# TODO: If a directory is given, diff everything under that.
589
# TODO: Selected-file diff is inefficient and doesn't show you
592
# TODO: This probably handles non-Unix newlines poorly.
594
takes_args = ['file*']
595
takes_options = ['revision', 'diff-options']
596
aliases = ['di', 'dif']
599
def run(self, revision=None, file_list=None, diff_options=None):
600
from bzrlib.diff import show_diff
603
b = Branch.open_containing(file_list[0])[0]
604
tree = WorkingTree(b.base, b)
605
file_list = [tree.relpath(f) for f in file_list]
606
if file_list == ['']:
607
# just pointing to top-of-tree
610
b = Branch.open_containing('.')[0]
612
if revision is not None:
613
if len(revision) == 1:
614
show_diff(b, revision[0], specific_files=file_list,
615
external_diff_options=diff_options)
616
elif len(revision) == 2:
617
show_diff(b, revision[0], specific_files=file_list,
618
external_diff_options=diff_options,
619
revision2=revision[1])
621
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
623
show_diff(b, None, specific_files=file_list,
624
external_diff_options=diff_options)
629
class cmd_deleted(Command):
630
"""List files deleted in the working tree.
632
# TODO: Show files deleted since a previous revision, or
633
# between two revisions.
634
# TODO: Much more efficient way to do this: read in new
635
# directories with readdir, rather than stating each one. Same
636
# level of effort but possibly much less IO. (Or possibly not,
637
# if the directories are very large...)
639
def run(self, show_ids=False):
640
b = Branch.open_containing('.')[0]
642
new = b.working_tree()
643
for path, ie in old.inventory.iter_entries():
644
if not new.has_id(ie.file_id):
646
print '%-50s %s' % (path, ie.file_id)
651
class cmd_modified(Command):
652
"""List files modified in working tree."""
656
from bzrlib.delta import compare_trees
658
b = Branch.open_containing('.')[0]
659
td = compare_trees(b.basis_tree(), b.working_tree())
661
for path, id, kind, text_modified, meta_modified in td.modified:
666
class cmd_added(Command):
667
"""List files added in working tree."""
671
b = Branch.open_containing('.')[0]
672
wt = b.working_tree()
673
basis_inv = b.basis_tree().inventory
676
if file_id in basis_inv:
678
path = inv.id2path(file_id)
679
if not os.access(b.abspath(path), os.F_OK):
685
class cmd_root(Command):
686
"""Show the tree root directory.
688
The root is the nearest enclosing directory with a .bzr control
690
takes_args = ['filename?']
692
def run(self, filename=None):
693
"""Print the branch root."""
694
b = Branch.open_containing(filename)[0]
698
class cmd_log(Command):
699
"""Show log of this branch.
701
To request a range of logs, you can use the command -r begin:end
702
-r revision requests a specific revision, -r :end or -r begin: are
706
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
708
takes_args = ['filename?']
709
takes_options = [Option('forward',
710
help='show from oldest to newest'),
711
'timezone', 'verbose',
712
'show-ids', 'revision',
713
Option('line', help='format with one line per revision'),
716
help='show revisions whose message matches this regexp',
718
Option('short', help='use moderately short format'),
721
def run(self, filename=None, timezone='original',
730
from bzrlib.log import log_formatter, show_log
732
assert message is None or isinstance(message, basestring), \
733
"invalid message argument %r" % message
734
direction = (forward and 'forward') or 'reverse'
737
b, fp = Branch.open_containing(filename)
739
file_id = b.read_working_inventory().path2id(fp)
741
file_id = None # points to branch root
743
b, relpath = Branch.open_containing('.')
749
elif len(revision) == 1:
750
rev1 = rev2 = revision[0].in_history(b).revno
751
elif len(revision) == 2:
752
rev1 = revision[0].in_history(b).revno
753
rev2 = revision[1].in_history(b).revno
755
raise BzrCommandError('bzr log --revision takes one or two values.')
762
mutter('encoding log as %r' % bzrlib.user_encoding)
764
# use 'replace' so that we don't abort if trying to write out
765
# in e.g. the default C locale.
766
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
773
lf = log_formatter(log_format,
776
show_timezone=timezone)
789
class cmd_touching_revisions(Command):
790
"""Return revision-ids which affected a particular file.
792
A more user-friendly interface is "bzr log FILE"."""
794
takes_args = ["filename"]
796
def run(self, filename):
797
b, relpath = Branch.open_containing(filename)[0]
798
inv = b.read_working_inventory()
799
file_id = inv.path2id(relpath)
800
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
801
print "%6d %s" % (revno, what)
804
class cmd_ls(Command):
805
"""List files in a tree.
807
# TODO: Take a revision or remote path and list that tree instead.
810
def run(self, revision=None, verbose=False):
811
b, relpath = Branch.open_containing('.')[0]
813
tree = b.working_tree()
815
tree = b.revision_tree(revision.in_history(b).rev_id)
816
for fp, fc, kind, fid, entry in tree.list_files():
818
kindch = entry.kind_character()
819
print '%-8s %s%s' % (fc, fp, kindch)
825
class cmd_unknowns(Command):
826
"""List unknown files."""
829
from bzrlib.osutils import quotefn
830
for f in Branch.open_containing('.')[0].unknowns():
835
class cmd_ignore(Command):
836
"""Ignore a command or pattern.
838
To remove patterns from the ignore list, edit the .bzrignore file.
840
If the pattern contains a slash, it is compared to the whole path
841
from the branch root. Otherwise, it is compared to only the last
842
component of the path. To match a file only in the root directory,
845
Ignore patterns are case-insensitive on case-insensitive systems.
847
Note: wildcards must be quoted from the shell on Unix.
850
bzr ignore ./Makefile
853
# TODO: Complain if the filename is absolute
854
takes_args = ['name_pattern']
856
def run(self, name_pattern):
857
from bzrlib.atomicfile import AtomicFile
860
b, relpath = Branch.open_containing('.')
861
ifn = b.abspath('.bzrignore')
863
if os.path.exists(ifn):
866
igns = f.read().decode('utf-8')
872
# TODO: If the file already uses crlf-style termination, maybe
873
# we should use that for the newly added lines?
875
if igns and igns[-1] != '\n':
877
igns += name_pattern + '\n'
880
f = AtomicFile(ifn, 'wt')
881
f.write(igns.encode('utf-8'))
886
inv = b.working_tree().inventory
887
if inv.path2id('.bzrignore'):
888
mutter('.bzrignore is already versioned')
890
mutter('need to make new .bzrignore file versioned')
891
b.add(['.bzrignore'])
895
class cmd_ignored(Command):
896
"""List ignored files and the patterns that matched them.
898
See also: bzr ignore"""
901
tree = Branch.open_containing('.')[0].working_tree()
902
for path, file_class, kind, file_id, entry in tree.list_files():
903
if file_class != 'I':
905
## XXX: Slightly inefficient since this was already calculated
906
pat = tree.is_ignored(path)
907
print '%-50s %s' % (path, pat)
910
class cmd_lookup_revision(Command):
911
"""Lookup the revision-id from a revision-number
914
bzr lookup-revision 33
917
takes_args = ['revno']
920
def run(self, revno):
924
raise BzrCommandError("not a valid revision-number: %r" % revno)
926
print Branch.open_containing('.')[0].get_rev_id(revno)
929
class cmd_export(Command):
930
"""Export past revision to destination directory.
932
If no revision is specified this exports the last committed revision.
934
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
935
given, try to find the format with the extension. If no extension
936
is found exports to a directory (equivalent to --format=dir).
938
Root may be the top directory for tar, tgz and tbz2 formats. If none
939
is given, the top directory will be the root name of the file."""
940
# TODO: list known exporters
941
takes_args = ['dest']
942
takes_options = ['revision', 'format', 'root']
943
def run(self, dest, revision=None, format=None, root=None):
945
b = Branch.open_containing('.')[0]
947
rev_id = b.last_revision()
949
if len(revision) != 1:
950
raise BzrError('bzr export --revision takes exactly 1 argument')
951
rev_id = revision[0].in_history(b).rev_id
952
t = b.revision_tree(rev_id)
953
arg_root, ext = os.path.splitext(os.path.basename(dest))
954
if ext in ('.gz', '.bz2'):
955
new_root, new_ext = os.path.splitext(arg_root)
956
if new_ext == '.tar':
964
elif ext in (".tar.gz", ".tgz"):
966
elif ext in (".tar.bz2", ".tbz2"):
970
t.export(dest, format, root)
973
class cmd_cat(Command):
974
"""Write a file's text from a previous revision."""
976
takes_options = ['revision']
977
takes_args = ['filename']
980
def run(self, filename, revision=None):
982
raise BzrCommandError("bzr cat requires a revision number")
983
elif len(revision) != 1:
984
raise BzrCommandError("bzr cat --revision takes exactly one number")
985
b, relpath = Branch.open_containing(filename)
986
b.print_file(relpath, revision[0].in_history(b).revno)
989
class cmd_local_time_offset(Command):
990
"""Show the offset in seconds from GMT to local time."""
994
print bzrlib.osutils.local_time_offset()
998
class cmd_commit(Command):
999
"""Commit changes into a new revision.
1001
If no arguments are given, the entire tree is committed.
1003
If selected files are specified, only changes to those files are
1004
committed. If a directory is specified then the directory and everything
1005
within it is committed.
1007
A selected-file commit may fail in some cases where the committed
1008
tree would be invalid, such as trying to commit a file in a
1009
newly-added directory that is not itself committed.
1011
# TODO: Run hooks on tree to-be-committed, and after commit.
1013
# TODO: Strict commit that fails if there are unknown or deleted files.
1014
# TODO: Give better message for -s, --summary, used by tla people
1016
# XXX: verbose currently does nothing
1018
takes_args = ['selected*']
1019
takes_options = ['message', 'verbose',
1021
help='commit even if nothing has changed'),
1022
Option('file', type=str,
1024
help='file containing commit message'),
1026
aliases = ['ci', 'checkin']
1028
def run(self, message=None, file=None, verbose=True, selected_list=None,
1030
from bzrlib.errors import PointlessCommit, ConflictsInTree
1031
from bzrlib.msgeditor import edit_commit_message
1032
from bzrlib.status import show_status
1033
from cStringIO import StringIO
1035
b = Branch.open_containing('.')[0]
1036
tree = WorkingTree(b.base, b)
1038
selected_list = [tree.relpath(s) for s in selected_list]
1039
if message is None and not file:
1040
catcher = StringIO()
1041
show_status(b, specific_files=selected_list,
1043
message = edit_commit_message(catcher.getvalue())
1046
raise BzrCommandError("please specify a commit message"
1047
" with either --message or --file")
1048
elif message and file:
1049
raise BzrCommandError("please specify either --message or --file")
1053
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1056
raise BzrCommandError("empty commit message specified")
1060
specific_files=selected_list,
1061
allow_pointless=unchanged)
1062
except PointlessCommit:
1063
# FIXME: This should really happen before the file is read in;
1064
# perhaps prepare the commit; get the message; then actually commit
1065
raise BzrCommandError("no changes to commit",
1066
["use --unchanged to commit anyhow"])
1067
except ConflictsInTree:
1068
raise BzrCommandError("Conflicts detected in working tree. "
1069
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1072
class cmd_check(Command):
1073
"""Validate consistency of branch history.
1075
This command checks various invariants about the branch storage to
1076
detect data corruption or bzr bugs.
1078
takes_args = ['dir?']
1079
takes_options = ['verbose']
1081
def run(self, dir='.', verbose=False):
1082
from bzrlib.check import check
1083
check(Branch.open_containing(dir)[0], verbose)
1086
class cmd_scan_cache(Command):
1089
from bzrlib.hashcache import HashCache
1095
print '%6d stats' % c.stat_count
1096
print '%6d in hashcache' % len(c._cache)
1097
print '%6d files removed from cache' % c.removed_count
1098
print '%6d hashes updated' % c.update_count
1099
print '%6d files changed too recently to cache' % c.danger_count
1106
class cmd_upgrade(Command):
1107
"""Upgrade branch storage to current format.
1109
The check command or bzr developers may sometimes advise you to run
1112
This version of this command upgrades from the full-text storage
1113
used by bzr 0.0.8 and earlier to the weave format (v5).
1115
takes_args = ['dir?']
1117
def run(self, dir='.'):
1118
from bzrlib.upgrade import upgrade
1122
class cmd_whoami(Command):
1123
"""Show bzr user id."""
1124
takes_options = ['email']
1127
def run(self, email=False):
1129
b = bzrlib.branch.Branch.open_containing('.')[0]
1130
config = bzrlib.config.BranchConfig(b)
1131
except NotBranchError:
1132
config = bzrlib.config.GlobalConfig()
1135
print config.user_email()
1137
print config.username()
1140
class cmd_selftest(Command):
1141
"""Run internal test suite.
1143
This creates temporary test directories in the working directory,
1144
but not existing data is affected. These directories are deleted
1145
if the tests pass, or left behind to help in debugging if they
1148
If arguments are given, they are regular expressions that say
1149
which tests should run.
1151
# TODO: --list should give a list of all available tests
1153
takes_args = ['testspecs*']
1154
takes_options = ['verbose',
1155
Option('one', help='stop when one test fails'),
1158
def run(self, testspecs_list=None, verbose=False, one=False):
1160
from bzrlib.selftest import selftest
1161
# we don't want progress meters from the tests to go to the
1162
# real output; and we don't want log messages cluttering up
1164
save_ui = bzrlib.ui.ui_factory
1165
bzrlib.trace.info('running tests...')
1167
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1168
if testspecs_list is not None:
1169
pattern = '|'.join(testspecs_list)
1172
result = selftest(verbose=verbose,
1174
stop_on_failure=one)
1176
bzrlib.trace.info('tests passed')
1178
bzrlib.trace.info('tests failed')
1179
return int(not result)
1181
bzrlib.ui.ui_factory = save_ui
1185
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1186
# is bzrlib itself in a branch?
1187
bzrrev = bzrlib.get_bzr_revision()
1189
print " (bzr checkout, revision %d {%s})" % bzrrev
1190
print bzrlib.__copyright__
1191
print "http://bazaar-ng.org/"
1193
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1194
print "you may use, modify and redistribute it under the terms of the GNU"
1195
print "General Public License version 2 or later."
1198
class cmd_version(Command):
1199
"""Show version of bzr."""
1204
class cmd_rocks(Command):
1205
"""Statement of optimism."""
1209
print "it sure does!"
1212
class cmd_find_merge_base(Command):
1213
"""Find and print a base revision for merging two branches.
1215
# TODO: Options to specify revisions on either side, as if
1216
# merging only part of the history.
1217
takes_args = ['branch', 'other']
1221
def run(self, branch, other):
1222
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1224
branch1 = Branch.open_containing(branch)[0]
1225
branch2 = Branch.open_containing(other)[0]
1227
history_1 = branch1.revision_history()
1228
history_2 = branch2.revision_history()
1230
last1 = branch1.last_revision()
1231
last2 = branch2.last_revision()
1233
source = MultipleRevisionSources(branch1, branch2)
1235
base_rev_id = common_ancestor(last1, last2, source)
1237
print 'merge base is revision %s' % base_rev_id
1241
if base_revno is None:
1242
raise bzrlib.errors.UnrelatedBranches()
1244
print ' r%-6d in %s' % (base_revno, branch)
1246
other_revno = branch2.revision_id_to_revno(base_revid)
1248
print ' r%-6d in %s' % (other_revno, other)
1252
class cmd_merge(Command):
1253
"""Perform a three-way merge.
1255
The branch is the branch you will merge from. By default, it will
1256
merge the latest revision. If you specify a revision, that
1257
revision will be merged. If you specify two revisions, the first
1258
will be used as a BASE, and the second one as OTHER. Revision
1259
numbers are always relative to the specified branch.
1261
By default bzr will try to merge in all new work from the other
1262
branch, automatically determining an appropriate base. If this
1263
fails, you may need to give an explicit base.
1267
To merge the latest revision from bzr.dev
1268
bzr merge ../bzr.dev
1270
To merge changes up to and including revision 82 from bzr.dev
1271
bzr merge -r 82 ../bzr.dev
1273
To merge the changes introduced by 82, without previous changes:
1274
bzr merge -r 81..82 ../bzr.dev
1276
merge refuses to run if there are any uncommitted changes, unless
1279
takes_args = ['branch?']
1280
takes_options = ['revision', 'force', 'merge-type']
1282
def run(self, branch=None, revision=None, force=False,
1284
from bzrlib.merge import merge
1285
from bzrlib.merge_core import ApplyMerge3
1286
if merge_type is None:
1287
merge_type = ApplyMerge3
1289
branch = Branch.open_containing('.')[0].get_parent()
1291
raise BzrCommandError("No merge location known or specified.")
1293
print "Using saved location: %s" % branch
1294
if revision is None or len(revision) < 1:
1296
other = [branch, -1]
1298
if len(revision) == 1:
1300
other_branch = Branch.open_containing(branch)[0]
1301
revno = revision[0].in_history(other_branch).revno
1302
other = [branch, revno]
1304
assert len(revision) == 2
1305
if None in revision:
1306
raise BzrCommandError(
1307
"Merge doesn't permit that revision specifier.")
1308
b = Branch.open_containing(branch)[0]
1310
base = [branch, revision[0].in_history(b).revno]
1311
other = [branch, revision[1].in_history(b).revno]
1314
merge(other, base, check_clean=(not force), merge_type=merge_type)
1315
except bzrlib.errors.AmbiguousBase, e:
1316
m = ("sorry, bzr can't determine the right merge base yet\n"
1317
"candidates are:\n "
1318
+ "\n ".join(e.bases)
1320
"please specify an explicit base with -r,\n"
1321
"and (if you want) report this to the bzr developers\n")
1325
class cmd_revert(Command):
1326
"""Reverse all changes since the last commit.
1328
Only versioned files are affected. Specify filenames to revert only
1329
those files. By default, any files that are changed will be backed up
1330
first. Backup files have a '~' appended to their name.
1332
takes_options = ['revision', 'no-backup']
1333
takes_args = ['file*']
1334
aliases = ['merge-revert']
1336
def run(self, revision=None, no_backup=False, file_list=None):
1337
from bzrlib.merge import merge
1338
from bzrlib.commands import parse_spec
1340
if file_list is not None:
1341
if len(file_list) == 0:
1342
raise BzrCommandError("No files specified")
1343
if revision is None:
1345
elif len(revision) != 1:
1346
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1348
b = Branch.open_containing('.')[0]
1349
revno = revision[0].in_history(b).revno
1350
merge(('.', revno), parse_spec('.'),
1353
backup_files=not no_backup,
1354
file_list=file_list)
1356
Branch.open_containing('.')[0].set_pending_merges([])
1359
class cmd_assert_fail(Command):
1360
"""Test reporting of assertion failures"""
1363
assert False, "always fails"
1366
class cmd_help(Command):
1367
"""Show help on a command or other topic.
1369
For a list of all available commands, say 'bzr help commands'."""
1370
takes_options = ['long']
1371
takes_args = ['topic?']
1375
def run(self, topic=None, long=False):
1377
if topic is None and long:
1382
class cmd_shell_complete(Command):
1383
"""Show appropriate completions for context.
1385
For a list of all available commands, say 'bzr shell-complete'."""
1386
takes_args = ['context?']
1391
def run(self, context=None):
1392
import shellcomplete
1393
shellcomplete.shellcomplete(context)
1396
class cmd_fetch(Command):
1397
"""Copy in history from another branch but don't merge it.
1399
This is an internal method used for pull and merge."""
1401
takes_args = ['from_branch', 'to_branch']
1402
def run(self, from_branch, to_branch):
1403
from bzrlib.fetch import Fetcher
1404
from bzrlib.branch import Branch
1405
from_b = Branch(from_branch)
1406
to_b = Branch(to_branch)
1407
Fetcher(to_b, from_b)
1411
class cmd_missing(Command):
1412
"""What is missing in this branch relative to other branch.
1414
# TODO: rewrite this in terms of ancestry so that it shows only
1417
takes_args = ['remote?']
1418
aliases = ['mis', 'miss']
1419
# We don't have to add quiet to the list, because
1420
# unknown options are parsed as booleans
1421
takes_options = ['verbose', 'quiet']
1424
def run(self, remote=None, verbose=False, quiet=False):
1425
from bzrlib.errors import BzrCommandError
1426
from bzrlib.missing import show_missing
1428
if verbose and quiet:
1429
raise BzrCommandError('Cannot pass both quiet and verbose')
1431
b = Branch.open_containing('.')[0]
1432
parent = b.get_parent()
1435
raise BzrCommandError("No missing location known or specified.")
1438
print "Using last location: %s" % parent
1440
elif parent is None:
1441
# We only update parent if it did not exist, missing
1442
# should not change the parent
1443
b.set_parent(remote)
1444
br_remote = Branch.open_containing(remote)[0]
1445
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1448
class cmd_plugins(Command):
1453
import bzrlib.plugin
1454
from inspect import getdoc
1455
for plugin in bzrlib.plugin.all_plugins:
1456
if hasattr(plugin, '__path__'):
1457
print plugin.__path__[0]
1458
elif hasattr(plugin, '__file__'):
1459
print plugin.__file__
1465
print '\t', d.split('\n')[0]
1468
class cmd_testament(Command):
1469
"""Show testament (signing-form) of a revision."""
1470
takes_options = ['revision', 'long']
1471
takes_args = ['branch?']
1473
def run(self, branch='.', revision=None, long=False):
1474
from bzrlib.testament import Testament
1475
b = Branch.open_containing(branch)[0]
1478
if revision is None:
1479
rev_id = b.last_revision()
1481
rev_id = revision[0].in_history(b).rev_id
1482
t = Testament.from_revision(b, rev_id)
1484
sys.stdout.writelines(t.as_text_lines())
1486
sys.stdout.write(t.as_short_text())
1491
class cmd_annotate(Command):
1492
"""Show the origin of each line in a file.
1494
This prints out the given file with an annotation on the left side
1495
indicating which revision, author and date introduced the change.
1497
If the origin is the same for a run of consecutive lines, it is
1498
shown only at the top, unless the --all option is given.
1500
# TODO: annotate directories; showing when each file was last changed
1501
# TODO: annotate a previous version of a file
1502
# TODO: if the working copy is modified, show annotations on that
1503
# with new uncommitted lines marked
1504
aliases = ['blame', 'praise']
1505
takes_args = ['filename']
1506
takes_options = [Option('all', help='show annotations on all lines'),
1507
Option('long', help='show date in annotations'),
1511
def run(self, filename, all=False, long=False):
1512
from bzrlib.annotate import annotate_file
1513
b, relpath = Branch.open_containing(filename)
1516
tree = WorkingTree(b.base, b)
1517
tree = b.revision_tree(b.last_revision())
1518
file_id = tree.inventory.path2id(relpath)
1519
file_version = tree.inventory[file_id].revision
1520
annotate_file(b, file_version, file_id, long, all, sys.stdout)
1525
class cmd_re_sign(Command):
1526
"""Create a digital signature for an existing revision."""
1527
# TODO be able to replace existing ones.
1529
hidden = True # is this right ?
1530
takes_args = ['revision_id?']
1531
takes_options = ['revision']
1533
def run(self, revision_id=None, revision=None):
1534
import bzrlib.config as config
1535
import bzrlib.gpg as gpg
1536
if revision_id is not None and revision is not None:
1537
raise BzrCommandError('You can only supply one of revision_id or --revision')
1538
if revision_id is None and revision is None:
1539
raise BzrCommandError('You must supply either --revision or a revision_id')
1540
b = Branch.open_containing('.')[0]
1541
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1542
if revision_id is not None:
1543
b.sign_revision(revision_id, gpg_strategy)
1544
elif revision is not None:
1545
for rev in revision:
1547
raise BzrCommandError('You cannot specify a NULL revision.')
1548
revno, rev_id = rev.in_history(b)
1549
b.sign_revision(rev_id, gpg_strategy)
1552
# these get imported and then picked up by the scan for cmd_*
1553
# TODO: Some more consistent way to split command definitions across files;
1554
# we do need to load at least some information about them to know of
1556
from bzrlib.conflicts import cmd_resolve, cmd_conflicts