1
# Copyright (C) 2004, 2005, 2006 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
"""builtin bzr commands"""
23
from shutil import rmtree
28
from bzrlib.branch import Branch
29
import bzrlib.bzrdir as bzrdir
30
from bzrlib.commands import Command, display_command
31
from bzrlib.revision import common_ancestor
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError,
34
NotBranchError, DivergedBranches, NotConflicted,
35
NoSuchFile, NoWorkingTree, FileInWrongBranch,
37
from bzrlib.log import show_one_log
38
from bzrlib.merge import Merge3Merger
39
from bzrlib.option import Option
40
from bzrlib.progress import DummyProgress, ProgressPhase
41
from bzrlib.revisionspec import RevisionSpec
43
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
44
from bzrlib.transport.local import LocalTransport
46
from bzrlib.workingtree import WorkingTree
49
def tree_files(file_list, default_branch=u'.'):
51
return internal_tree_files(file_list, default_branch)
52
except FileInWrongBranch, e:
53
raise BzrCommandError("%s is not in the same branch as %s" %
54
(e.path, file_list[0]))
57
# XXX: Bad function name; should possibly also be a class method of
58
# WorkingTree rather than a function.
59
def internal_tree_files(file_list, default_branch=u'.'):
60
"""Convert command-line paths to a WorkingTree and relative paths.
62
This is typically used for command-line processors that take one or
63
more filenames, and infer the workingtree that contains them.
65
The filenames given are not required to exist.
67
:param file_list: Filenames to convert.
69
:param default_branch: Fallback tree path to use if file_list is empty or None.
71
:return: workingtree, [relative_paths]
73
if file_list is None or len(file_list) == 0:
74
return WorkingTree.open_containing(default_branch)[0], file_list
75
tree = WorkingTree.open_containing(file_list[0])[0]
77
for filename in file_list:
79
new_list.append(tree.relpath(filename))
80
except errors.PathNotChild:
81
raise FileInWrongBranch(tree.branch, filename)
85
def get_format_type(typestring):
86
"""Parse and return a format specifier."""
87
if typestring == "weave":
88
return bzrdir.BzrDirFormat6()
89
if typestring == "metadir":
90
return bzrdir.BzrDirMetaFormat1()
91
if typestring == "knit":
92
format = bzrdir.BzrDirMetaFormat1()
93
format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
95
msg = "No known bzr-dir format %s. Supported types are: weave, metadir\n" %\
97
raise BzrCommandError(msg)
100
# TODO: Make sure no commands unconditionally use the working directory as a
101
# branch. If a filename argument is used, the first of them should be used to
102
# specify the branch. (Perhaps this can be factored out into some kind of
103
# Argument class, representing a file in a branch, where the first occurrence
106
class cmd_status(Command):
107
"""Display status summary.
109
This reports on versioned and unknown files, reporting them
110
grouped by state. Possible states are:
113
Versioned in the working copy but not in the previous revision.
116
Versioned in the previous revision but removed or deleted
120
Path of this file changed from the previous revision;
121
the text may also have changed. This includes files whose
122
parent directory was renamed.
125
Text has changed since the previous revision.
128
Nothing about this file has changed since the previous revision.
129
Only shown with --all.
132
Not versioned and not matching an ignore pattern.
134
To see ignored files use 'bzr ignored'. For details in the
135
changes to file texts, use 'bzr diff'.
137
If no arguments are specified, the status of the entire working
138
directory is shown. Otherwise, only the status of the specified
139
files or directories is reported. If a directory is given, status
140
is reported for everything inside that directory.
142
If a revision argument is given, the status is calculated against
143
that revision, or between two revisions if two are provided.
146
# TODO: --no-recurse, --recurse options
148
takes_args = ['file*']
149
takes_options = ['all', 'show-ids', 'revision']
150
aliases = ['st', 'stat']
152
encoding_type = 'replace'
155
def run(self, all=False, show_ids=False, file_list=None, revision=None):
156
from bzrlib.status import show_tree_status
158
tree, file_list = tree_files(file_list)
160
show_tree_status(tree, show_unchanged=all, show_ids=show_ids,
161
specific_files=file_list, revision=revision,
165
class cmd_cat_revision(Command):
166
"""Write out metadata for a revision.
168
The revision to print can either be specified by a specific
169
revision identifier, or you can use --revision.
173
takes_args = ['revision_id?']
174
takes_options = ['revision']
177
def run(self, revision_id=None, revision=None):
179
if revision_id is not None and revision is not None:
180
raise BzrCommandError('You can only supply one of revision_id or --revision')
181
if revision_id is None and revision is None:
182
raise BzrCommandError('You must supply either --revision or a revision_id')
183
b = WorkingTree.open_containing(u'.')[0].branch
185
# TODO: jam 20060112 should cat-revision always output utf-8?
186
if revision_id is not None:
187
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
188
elif revision is not None:
191
raise BzrCommandError('You cannot specify a NULL revision.')
192
revno, rev_id = rev.in_history(b)
193
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
196
class cmd_revno(Command):
197
"""Show current revision number.
199
This is equal to the number of revisions on this branch.
202
takes_args = ['location?']
205
def run(self, location=u'.'):
206
self.outf.write(str(Branch.open_containing(location)[0].revno()))
207
self.outf.write('\n')
210
class cmd_revision_info(Command):
211
"""Show revision number and revision id for a given revision identifier.
214
takes_args = ['revision_info*']
215
takes_options = ['revision']
218
def run(self, revision=None, revision_info_list=[]):
221
if revision is not None:
222
revs.extend(revision)
223
if revision_info_list is not None:
224
for rev in revision_info_list:
225
revs.append(RevisionSpec(rev))
227
raise BzrCommandError('You must supply a revision identifier')
229
b = WorkingTree.open_containing(u'.')[0].branch
232
revinfo = rev.in_history(b)
233
if revinfo.revno is None:
234
print ' %s' % revinfo.rev_id
236
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
239
class cmd_add(Command):
240
"""Add specified files or directories.
242
In non-recursive mode, all the named items are added, regardless
243
of whether they were previously ignored. A warning is given if
244
any of the named files are already versioned.
246
In recursive mode (the default), files are treated the same way
247
but the behaviour for directories is different. Directories that
248
are already versioned do not give a warning. All directories,
249
whether already versioned or not, are searched for files or
250
subdirectories that are neither versioned or ignored, and these
251
are added. This search proceeds recursively into versioned
252
directories. If no names are given '.' is assumed.
254
Therefore simply saying 'bzr add' will version all files that
255
are currently unknown.
257
Adding a file whose parent directory is not versioned will
258
implicitly add the parent, and so on up to the root. This means
259
you should never need to explictly add a directory, they'll just
260
get added when you add a file in the directory.
262
--dry-run will show which files would be added, but not actually
265
takes_args = ['file*']
266
takes_options = ['no-recurse', 'dry-run', 'verbose']
267
encoding_type = 'replace'
269
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
272
action = bzrlib.add.AddAction(to_file=self.outf,
273
should_add=(not dry_run), should_print=(not is_quiet()))
275
added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
278
for glob in sorted(ignored.keys()):
279
match_len = len(ignored[glob])
281
for path in ignored[glob]:
282
self.outf.write("ignored %s matching \"%s\"\n"
285
self.outf.write("ignored %d file(s) matching \"%s\"\n"
287
self.outf.write("If you wish to add some of these files,"
288
" please add them by name.\n")
291
class cmd_mkdir(Command):
292
"""Create a new versioned directory.
294
This is equivalent to creating the directory and then adding it.
296
takes_args = ['dir+']
297
encoding_type = 'replace'
299
def run(self, dir_list):
302
wt, dd = WorkingTree.open_containing(d)
304
print >>self.outf, 'added', d
307
class cmd_relpath(Command):
308
"""Show path of a file relative to root"""
309
takes_args = ['filename']
313
def run(self, filename):
314
# TODO: jam 20050106 Can relpath return a munged path if
315
# sys.stdout encoding cannot represent it?
316
tree, relpath = WorkingTree.open_containing(filename)
317
self.outf.write(relpath)
318
self.outf.write('\n')
321
class cmd_inventory(Command):
322
"""Show inventory of the current working copy or a revision.
324
It is possible to limit the output to a particular entry
325
type using the --kind option. For example; --kind file.
327
takes_options = ['revision', 'show-ids', 'kind']
330
def run(self, revision=None, show_ids=False, kind=None):
331
if kind and kind not in ['file', 'directory', 'symlink']:
332
raise BzrCommandError('invalid kind specified')
333
tree = WorkingTree.open_containing(u'.')[0]
335
inv = tree.read_working_inventory()
337
if len(revision) > 1:
338
raise BzrCommandError('bzr inventory --revision takes'
339
' exactly one revision identifier')
340
inv = tree.branch.repository.get_revision_inventory(
341
revision[0].in_history(tree.branch).rev_id)
343
for path, entry in inv.entries():
344
if kind and kind != entry.kind:
347
self.outf.write('%-50s %s\n' % (path, entry.file_id))
349
self.outf.write(path)
350
self.outf.write('\n')
353
class cmd_mv(Command):
354
"""Move or rename a file.
357
bzr mv OLDNAME NEWNAME
358
bzr mv SOURCE... DESTINATION
360
If the last argument is a versioned directory, all the other names
361
are moved into it. Otherwise, there must be exactly two arguments
362
and the file is changed to a new name, which must not already exist.
364
Files cannot be moved between branches.
366
takes_args = ['names*']
367
aliases = ['move', 'rename']
369
encoding_type = 'replace'
371
def run(self, names_list):
372
if len(names_list) < 2:
373
raise BzrCommandError("missing file argument")
374
tree, rel_names = tree_files(names_list)
376
if os.path.isdir(names_list[-1]):
377
# move into existing directory
378
for pair in tree.move(rel_names[:-1], rel_names[-1]):
379
self.outf.write("%s => %s\n" % pair)
381
if len(names_list) != 2:
382
raise BzrCommandError('to mv multiple files the destination '
383
'must be a versioned directory')
384
tree.rename_one(rel_names[0], rel_names[1])
385
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
388
class cmd_pull(Command):
389
"""Turn this branch into a mirror of another branch.
391
This command only works on branches that have not diverged. Branches are
392
considered diverged if the destination branch's most recent commit is one
393
that has not been merged (directly or indirectly) into the parent.
395
If branches have diverged, you can use 'bzr merge' to integrate the changes
396
from one into the other. Once one branch has merged, the other should
397
be able to pull it again.
399
If branches have diverged, you can use 'bzr merge' to pull the text changes
400
from one into the other. Once one branch has merged, the other should
401
be able to pull it again.
403
If you want to forget your local changes and just update your branch to
404
match the remote one, use pull --overwrite.
406
If there is no default location set, the first pull will set it. After
407
that, you can omit the location to use the default. To change the
408
default, use --remember.
410
takes_options = ['remember', 'overwrite', 'revision', 'verbose']
411
takes_args = ['location?']
412
encoding_type = 'replace'
414
def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
415
# FIXME: too much stuff is in the command class
417
tree_to = WorkingTree.open_containing(u'.')[0]
418
branch_to = tree_to.branch
419
except NoWorkingTree:
421
branch_to = Branch.open_containing(u'.')[0]
422
stored_loc = branch_to.get_parent()
424
if stored_loc is None:
425
raise BzrCommandError("No pull location known or specified.")
427
self.outf.write("Using saved location: %s\n" % stored_loc)
428
location = stored_loc
430
branch_from = Branch.open(location)
432
if branch_to.get_parent() is None or remember:
433
branch_to.set_parent(branch_from.base)
438
elif len(revision) == 1:
439
rev_id = revision[0].in_history(branch_from).rev_id
441
raise BzrCommandError('bzr pull --revision takes one value.')
443
old_rh = branch_to.revision_history()
444
if tree_to is not None:
445
count = tree_to.pull(branch_from, overwrite, rev_id)
447
count = branch_to.pull(branch_from, overwrite, rev_id)
448
note('%d revision(s) pulled.' % (count,))
451
new_rh = branch_to.revision_history()
454
from bzrlib.log import show_changed_revisions
455
show_changed_revisions(branch_to, old_rh, new_rh,
459
class cmd_push(Command):
460
"""Update a mirror of this branch.
462
The target branch will not have its working tree populated because this
463
is both expensive, and is not supported on remote file systems.
465
Some smart servers or protocols *may* put the working tree in place in
468
This command only works on branches that have not diverged. Branches are
469
considered diverged if the destination branch's most recent commit is one
470
that has not been merged (directly or indirectly) by the source branch.
472
If branches have diverged, you can use 'bzr push --overwrite' to replace
473
the other branch completely, discarding its unmerged changes.
475
If you want to ensure you have the different changes in the other branch,
476
do a merge (see bzr help merge) from the other branch, and commit that.
477
After that you will be able to do a push without '--overwrite'.
479
If there is no default push location set, the first push will set it.
480
After that, you can omit the location to use the default. To change the
481
default, use --remember.
483
takes_options = ['remember', 'overwrite', 'verbose',
484
Option('create-prefix',
485
help='Create the path leading up to the branch '
486
'if it does not already exist')]
487
takes_args = ['location?']
488
encoding_type = 'replace'
490
def run(self, location=None, remember=False, overwrite=False,
491
create_prefix=False, verbose=False):
492
# FIXME: Way too big! Put this into a function called from the
494
from bzrlib.transport import get_transport
496
tree_from = WorkingTree.open_containing(u'.')[0]
497
br_from = tree_from.branch
498
stored_loc = tree_from.branch.get_push_location()
501
if stored_loc is None:
502
raise BzrCommandError("No push location known or specified.")
504
self.outf.write("Using saved location: %s" % stored_loc)
505
location = stored_loc
507
transport = get_transport(location)
508
location_url = transport.base
509
if br_from.get_push_location() is None or remember:
510
br_from.set_push_location(location_url)
512
dir_to = bzrlib.bzrdir.BzrDir.open(location_url)
513
br_to = dir_to.open_branch()
514
except NotBranchError:
516
transport = transport.clone('..')
517
if not create_prefix:
519
relurl = transport.relpath(location_url)
520
mutter('creating directory %s => %s', location_url, relurl)
521
transport.mkdir(relurl)
523
raise BzrCommandError("Parent directory of %s "
524
"does not exist." % location)
526
current = transport.base
527
needed = [(transport, transport.relpath(location_url))]
530
transport, relpath = needed[-1]
531
transport.mkdir(relpath)
534
new_transport = transport.clone('..')
535
needed.append((new_transport,
536
new_transport.relpath(transport.base)))
537
if new_transport.base == transport.base:
538
raise BzrCommandError("Could not create "
540
dir_to = br_from.bzrdir.clone(location_url)
541
br_to = dir_to.open_branch()
542
old_rh = br_to.revision_history()
545
tree_to = dir_to.open_workingtree()
546
except errors.NotLocalUrl:
547
# TODO: This should be updated for branches which don't have a
548
# working tree, as opposed to ones where we just couldn't
550
warning('This transport does not update the working '
551
'tree of: %s' % (br_to.base,))
552
count = br_to.pull(br_from, overwrite)
553
except NoWorkingTree:
554
count = br_to.pull(br_from, overwrite)
556
count = tree_to.pull(br_from, overwrite)
557
except DivergedBranches:
558
raise BzrCommandError("These branches have diverged."
559
" Try a merge then push with overwrite.")
560
note('%d revision(s) pushed.' % (count,))
563
new_rh = br_to.revision_history()
566
from bzrlib.log import show_changed_revisions
567
show_changed_revisions(br_to, old_rh, new_rh,
571
class cmd_branch(Command):
572
"""Create a new copy of a branch.
574
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
575
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
577
To retrieve the branch as of a particular revision, supply the --revision
578
parameter, as in "branch foo/bar -r 5".
580
--basis is to speed up branching from remote branches. When specified, it
581
copies all the file-contents, inventory and revision data from the basis
582
branch before copying anything from the remote branch.
584
takes_args = ['from_location', 'to_location?']
585
takes_options = ['revision', 'basis']
586
aliases = ['get', 'clone']
588
def run(self, from_location, to_location=None, revision=None, basis=None):
589
from bzrlib.transport import get_transport
592
elif len(revision) > 1:
593
raise BzrCommandError(
594
'bzr branch --revision takes exactly 1 revision value')
596
br_from = Branch.open(from_location)
598
if e.errno == errno.ENOENT:
599
raise BzrCommandError('Source location "%s" does not'
600
' exist.' % to_location)
605
if basis is not None:
606
basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
609
if len(revision) == 1 and revision[0] is not None:
610
revision_id = revision[0].in_history(br_from)[1]
612
# FIXME - wt.last_revision, fallback to branch, fall back to
613
# None or perhaps NULL_REVISION to mean copy nothing
615
revision_id = br_from.last_revision()
616
if to_location is None:
617
to_location = os.path.basename(from_location.rstrip("/\\"))
620
name = os.path.basename(to_location) + '\n'
622
to_transport = get_transport(to_location)
624
to_transport.mkdir('.')
625
except bzrlib.errors.FileExists:
626
raise BzrCommandError('Target directory "%s" already'
627
' exists.' % to_location)
628
except bzrlib.errors.NoSuchFile:
629
raise BzrCommandError('Parent of "%s" does not exist.' %
632
# preserve whatever source format we have.
633
dir = br_from.bzrdir.sprout(to_transport.base,
634
revision_id, basis_dir)
635
branch = dir.open_branch()
636
except bzrlib.errors.NoSuchRevision:
637
# TODO: jam 20060426 This only works on local paths
638
# and it would be nice if 'bzr branch' could
639
# work on a remote path
641
msg = "The branch %s has no revision %s." % (from_location, revision[0])
642
raise BzrCommandError(msg)
643
except bzrlib.errors.UnlistableBranch:
645
msg = "The branch %s cannot be used as a --basis" % (basis,)
646
raise BzrCommandError(msg)
648
branch.control_files.put_utf8('branch-name', name)
649
note('Branched %d revision(s).' % branch.revno())
654
class cmd_checkout(Command):
655
"""Create a new checkout of an existing branch.
657
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
658
the branch found in '.'. This is useful if you have removed the working tree
659
or if it was never created - i.e. if you pushed the branch to its current
662
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
663
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
665
To retrieve the branch as of a particular revision, supply the --revision
666
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
667
out of date [so you cannot commit] but it may be useful (i.e. to examine old
670
--basis is to speed up checking out from remote branches. When specified, it
671
uses the inventory and file contents from the basis branch in preference to the
672
branch being checked out. [Not implemented yet.]
674
takes_args = ['branch_location?', 'to_location?']
675
takes_options = ['revision', # , 'basis']
676
Option('lightweight',
677
help="perform a lightweight checkout. Lightweight "
678
"checkouts depend on access to the branch for "
679
"every operation. Normal checkouts can perform "
680
"common operations like diff and status without "
681
"such access, and also support local commits."
685
def run(self, branch_location=None, to_location=None, revision=None, basis=None,
689
elif len(revision) > 1:
690
raise BzrCommandError(
691
'bzr checkout --revision takes exactly 1 revision value')
692
if branch_location is None:
693
branch_location = bzrlib.osutils.getcwd()
694
to_location = branch_location
695
source = Branch.open(branch_location)
696
if len(revision) == 1 and revision[0] is not None:
697
revision_id = revision[0].in_history(source)[1]
700
if to_location is None:
701
to_location = os.path.basename(branch_location.rstrip("/\\"))
702
# if the source and to_location are the same,
703
# and there is no working tree,
704
# then reconstitute a branch
705
if (bzrlib.osutils.abspath(to_location) ==
706
bzrlib.osutils.abspath(branch_location)):
708
source.bzrdir.open_workingtree()
709
except errors.NoWorkingTree:
710
source.bzrdir.create_workingtree()
713
os.mkdir(to_location)
715
if e.errno == errno.EEXIST:
716
raise BzrCommandError('Target directory "%s" already'
717
' exists.' % to_location)
718
if e.errno == errno.ENOENT:
719
raise BzrCommandError('Parent of "%s" does not exist.' %
723
old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
724
bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
727
checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
728
bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
730
checkout_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience(
731
to_location, force_new_tree=False)
732
checkout = checkout_branch.bzrdir
733
checkout_branch.bind(source)
734
if revision_id is not None:
735
rh = checkout_branch.revision_history()
736
checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
737
checkout.create_workingtree(revision_id)
739
bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
742
class cmd_renames(Command):
743
"""Show list of renamed files.
745
# TODO: Option to show renames between two historical versions.
747
# TODO: Only show renames under dir, rather than in the whole branch.
748
takes_args = ['dir?']
751
def run(self, dir=u'.'):
752
tree = WorkingTree.open_containing(dir)[0]
753
old_inv = tree.basis_tree().inventory
754
new_inv = tree.read_working_inventory()
756
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
758
for old_name, new_name in renames:
759
self.outf.write("%s => %s\n" % (old_name, new_name))
762
class cmd_update(Command):
763
"""Update a tree to have the latest code committed to its branch.
765
This will perform a merge into the working tree, and may generate
766
conflicts. If you have any local changes, you will still
767
need to commit them after the update for the update to be complete.
769
If you want to discard your local changes, you can just do a
770
'bzr revert' instead of 'bzr commit' after the update.
772
takes_args = ['dir?']
774
def run(self, dir='.'):
775
tree = WorkingTree.open_containing(dir)[0]
778
if tree.last_revision() == tree.branch.last_revision():
779
# may be up to date, check master too.
780
master = tree.branch.get_master_branch()
781
if master is None or master.last_revision == tree.last_revision():
782
note("Tree is up to date.")
784
conflicts = tree.update()
785
note('Updated to revision %d.' %
786
(tree.branch.revision_id_to_revno(tree.last_revision()),))
795
class cmd_info(Command):
796
"""Show statistical information about a branch."""
797
takes_args = ['branch?']
798
takes_options = ['verbose']
801
def run(self, branch=None, verbose=False):
803
bzrlib.info.show_bzrdir_info(bzrdir.BzrDir.open_containing(branch)[0],
807
class cmd_remove(Command):
808
"""Make a file unversioned.
810
This makes bzr stop tracking changes to a versioned file. It does
811
not delete the working copy.
813
takes_args = ['file+']
814
takes_options = ['verbose']
817
def run(self, file_list, verbose=False):
818
tree, file_list = tree_files(file_list)
819
tree.remove(file_list, verbose=verbose)
822
class cmd_file_id(Command):
823
"""Print file_id of a particular file or directory.
825
The file_id is assigned when the file is first added and remains the
826
same through all revisions where the file exists, even when it is
830
takes_args = ['filename']
833
def run(self, filename):
834
tree, relpath = WorkingTree.open_containing(filename)
835
i = tree.inventory.path2id(relpath)
837
raise BzrError("%r is not a versioned file" % filename)
840
self.outf.write('\n')
843
class cmd_file_path(Command):
844
"""Print path of file_ids to a file or directory.
846
This prints one line for each directory down to the target,
847
starting at the branch root.
850
takes_args = ['filename']
853
def run(self, filename):
854
tree, relpath = WorkingTree.open_containing(filename)
856
fid = inv.path2id(relpath)
858
raise BzrError("%r is not a versioned file" % filename)
859
for fip in inv.get_idpath(fid):
861
self.outf.write('\n')
864
class cmd_reconcile(Command):
865
"""Reconcile bzr metadata in a branch.
867
This can correct data mismatches that may have been caused by
868
previous ghost operations or bzr upgrades. You should only
869
need to run this command if 'bzr check' or a bzr developer
870
advises you to run it.
872
If a second branch is provided, cross-branch reconciliation is
873
also attempted, which will check that data like the tree root
874
id which was not present in very early bzr versions is represented
875
correctly in both branches.
877
At the same time it is run it may recompress data resulting in
878
a potential saving in disk space or performance gain.
880
The branch *MUST* be on a listable system such as local disk or sftp.
882
takes_args = ['branch?']
884
def run(self, branch="."):
885
from bzrlib.reconcile import reconcile
886
dir = bzrlib.bzrdir.BzrDir.open(branch)
890
class cmd_revision_history(Command):
891
"""Display list of revision ids on this branch."""
896
branch = WorkingTree.open_containing(u'.')[0].branch
897
for patchid in branch.revision_history():
898
self.outf.write(patchid)
899
self.outf.write('\n')
902
class cmd_ancestry(Command):
903
"""List all revisions merged into this branch."""
908
tree = WorkingTree.open_containing(u'.')[0]
910
# FIXME. should be tree.last_revision
911
for revision_id in b.repository.get_ancestry(b.last_revision()):
912
if revision_id is None:
914
self.outf.write(revision_id)
915
self.outf.write('\n')
918
class cmd_init(Command):
919
"""Make a directory into a versioned branch.
921
Use this to create an empty branch, or before importing an
924
If there is a repository in a parent directory of the location, then
925
the history of the branch will be stored in the repository. Otherwise
926
init creates a standalone branch which carries its own history in
929
If there is already a branch at the location but it has no working tree,
930
the tree can be populated with 'bzr checkout'.
932
Recipe for importing a tree of files:
937
bzr commit -m 'imported project'
939
takes_args = ['location?']
942
help='Create a specific format rather than the'
943
' current default format. Currently this '
944
' option only accepts "metadir"',
945
type=get_format_type),
947
def run(self, location=None, format=None):
948
from bzrlib.branch import Branch
952
# The path has to exist to initialize a
953
# branch inside of it.
954
# Just using os.mkdir, since I don't
955
# believe that we want to create a bunch of
956
# locations if the user supplies an extended path
957
if not os.path.exists(location):
960
existing_bzrdir = bzrdir.BzrDir.open(location)
961
except NotBranchError:
962
# really a NotBzrDir error...
963
bzrdir.BzrDir.create_branch_convenience(location, format=format)
965
if existing_bzrdir.has_branch():
966
if existing_bzrdir.has_workingtree():
967
raise errors.AlreadyBranchError(location)
969
raise errors.BranchExistsWithoutWorkingTree(location)
971
existing_bzrdir.create_branch()
972
existing_bzrdir.create_workingtree()
975
class cmd_init_repository(Command):
976
"""Create a shared repository to hold branches.
978
New branches created under the repository directory will store their revisions
979
in the repository, not in the branch directory, if the branch format supports
985
bzr checkout --lightweight repo/trunk trunk-checkout
989
takes_args = ["location"]
990
takes_options = [Option('format',
991
help='Use a specific format rather than the'
992
' current default format. Currently this'
993
' option accepts "weave", "metadir" and "knit"',
994
type=get_format_type),
996
help='Allows branches in repository to have'
998
aliases = ["init-repo"]
999
def run(self, location, format=None, trees=False):
1000
from bzrlib.bzrdir import BzrDirMetaFormat1
1001
from bzrlib.transport import get_transport
1003
format = BzrDirMetaFormat1()
1004
transport = get_transport(location)
1005
if not transport.has('.'):
1007
newdir = format.initialize_on_transport(transport)
1008
repo = newdir.create_repository(shared=True)
1009
repo.set_make_working_trees(trees)
1012
class cmd_diff(Command):
1013
"""Show differences in working tree.
1015
If files are listed, only the changes in those files are listed.
1016
Otherwise, all changes for the tree are listed.
1023
# TODO: Allow diff across branches.
1024
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1025
# or a graphical diff.
1027
# TODO: Python difflib is not exactly the same as unidiff; should
1028
# either fix it up or prefer to use an external diff.
1030
# TODO: If a directory is given, diff everything under that.
1032
# TODO: Selected-file diff is inefficient and doesn't show you
1035
# TODO: This probably handles non-Unix newlines poorly.
1037
takes_args = ['file*']
1038
takes_options = ['revision', 'diff-options']
1039
aliases = ['di', 'dif']
1040
encoding_type = 'exact'
1043
def run(self, revision=None, file_list=None, diff_options=None):
1044
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1046
tree1, file_list = internal_tree_files(file_list)
1050
except FileInWrongBranch:
1051
if len(file_list) != 2:
1052
raise BzrCommandError("Files are in different branches")
1054
tree1, file1 = WorkingTree.open_containing(file_list[0])
1055
tree2, file2 = WorkingTree.open_containing(file_list[1])
1056
if file1 != "" or file2 != "":
1057
# FIXME diff those two files. rbc 20051123
1058
raise BzrCommandError("Files are in different branches")
1060
if revision is not None:
1061
if tree2 is not None:
1062
raise BzrCommandError("Can't specify -r with two branches")
1063
if (len(revision) == 1) or (revision[1].spec is None):
1064
return diff_cmd_helper(tree1, file_list, diff_options,
1066
elif len(revision) == 2:
1067
return diff_cmd_helper(tree1, file_list, diff_options,
1068
revision[0], revision[1])
1070
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1072
if tree2 is not None:
1073
return show_diff_trees(tree1, tree2, sys.stdout,
1074
specific_files=file_list,
1075
external_diff_options=diff_options)
1077
return diff_cmd_helper(tree1, file_list, diff_options)
1080
class cmd_deleted(Command):
1081
"""List files deleted in the working tree.
1083
# TODO: Show files deleted since a previous revision, or
1084
# between two revisions.
1085
# TODO: Much more efficient way to do this: read in new
1086
# directories with readdir, rather than stating each one. Same
1087
# level of effort but possibly much less IO. (Or possibly not,
1088
# if the directories are very large...)
1089
takes_options = ['show-ids']
1092
def run(self, show_ids=False):
1093
tree = WorkingTree.open_containing(u'.')[0]
1094
old = tree.basis_tree()
1095
for path, ie in old.inventory.iter_entries():
1096
if not tree.has_id(ie.file_id):
1097
self.outf.write(path)
1099
self.outf.write(' ')
1100
self.outf.write(ie.file_id)
1101
self.outf.write('\n')
1104
class cmd_modified(Command):
1105
"""List files modified in working tree."""
1109
from bzrlib.delta import compare_trees
1111
tree = WorkingTree.open_containing(u'.')[0]
1112
td = compare_trees(tree.basis_tree(), tree)
1114
for path, id, kind, text_modified, meta_modified in td.modified:
1115
self.outf.write(path)
1116
self.outf.write('\n')
1119
class cmd_added(Command):
1120
"""List files added in working tree."""
1124
wt = WorkingTree.open_containing(u'.')[0]
1125
basis_inv = wt.basis_tree().inventory
1128
if file_id in basis_inv:
1130
path = inv.id2path(file_id)
1131
if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
1133
self.outf.write(path)
1134
self.outf.write('\n')
1137
class cmd_root(Command):
1138
"""Show the tree root directory.
1140
The root is the nearest enclosing directory with a .bzr control
1142
takes_args = ['filename?']
1144
def run(self, filename=None):
1145
"""Print the branch root."""
1146
tree = WorkingTree.open_containing(filename)[0]
1147
self.outf.write(tree.basedir)
1148
self.outf.write('\n')
1151
class cmd_log(Command):
1152
"""Show log of a branch, file, or directory.
1154
By default show the log of the branch containing the working directory.
1156
To request a range of logs, you can use the command -r begin..end
1157
-r revision requests a specific revision, -r ..end or -r begin.. are
1163
bzr log -r -10.. http://server/branch
1166
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1168
takes_args = ['location?']
1169
takes_options = [Option('forward',
1170
help='show from oldest to newest'),
1173
help='show files changed in each revision'),
1174
'show-ids', 'revision',
1178
help='show revisions whose message matches this regexp',
1182
encoding_type = 'replace'
1185
def run(self, location=None, timezone='original',
1195
from bzrlib.log import log_formatter, show_log
1196
assert message is None or isinstance(message, basestring), \
1197
"invalid message argument %r" % message
1198
direction = (forward and 'forward') or 'reverse'
1203
# find the file id to log:
1205
dir, fp = bzrdir.BzrDir.open_containing(location)
1206
b = dir.open_branch()
1210
inv = dir.open_workingtree().inventory
1211
except (errors.NotBranchError, errors.NotLocalUrl):
1212
# either no tree, or is remote.
1213
inv = b.basis_tree().inventory
1214
file_id = inv.path2id(fp)
1217
# FIXME ? log the current subdir only RBC 20060203
1218
dir, relpath = bzrdir.BzrDir.open_containing('.')
1219
b = dir.open_branch()
1221
if revision is None:
1224
elif len(revision) == 1:
1225
rev1 = rev2 = revision[0].in_history(b).revno
1226
elif len(revision) == 2:
1227
if revision[0].spec is None:
1228
# missing begin-range means first revision
1231
rev1 = revision[0].in_history(b).revno
1233
if revision[1].spec is None:
1234
# missing end-range means last known revision
1237
rev2 = revision[1].in_history(b).revno
1239
raise BzrCommandError('bzr log --revision takes one or two values.')
1241
# By this point, the revision numbers are converted to the +ve
1242
# form if they were supplied in the -ve form, so we can do
1243
# this comparison in relative safety
1245
(rev2, rev1) = (rev1, rev2)
1247
if (log_format == None):
1248
default = bzrlib.config.BranchConfig(b).log_format()
1249
log_format = get_log_format(long=long, short=short, line=line, default=default)
1250
lf = log_formatter(log_format,
1253
show_timezone=timezone)
1259
direction=direction,
1260
start_revision=rev1,
1265
def get_log_format(long=False, short=False, line=False, default='long'):
1266
log_format = default
1270
log_format = 'short'
1276
class cmd_touching_revisions(Command):
1277
"""Return revision-ids which affected a particular file.
1279
A more user-friendly interface is "bzr log FILE"."""
1281
takes_args = ["filename"]
1282
encoding_type = 'replace'
1285
def run(self, filename):
1286
tree, relpath = WorkingTree.open_containing(filename)
1288
inv = tree.read_working_inventory()
1289
file_id = inv.path2id(relpath)
1290
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1291
self.outf.write("%6d %s\n" % (revno, what))
1294
class cmd_ls(Command):
1295
"""List files in a tree.
1297
# TODO: Take a revision or remote path and list that tree instead.
1299
takes_options = ['verbose', 'revision',
1300
Option('non-recursive',
1301
help='don\'t recurse into sub-directories'),
1303
help='Print all paths from the root of the branch.'),
1304
Option('unknown', help='Print unknown files'),
1305
Option('versioned', help='Print versioned files'),
1306
Option('ignored', help='Print ignored files'),
1308
Option('null', help='Null separate the files'),
1311
def run(self, revision=None, verbose=False,
1312
non_recursive=False, from_root=False,
1313
unknown=False, versioned=False, ignored=False,
1316
if verbose and null:
1317
raise BzrCommandError('Cannot set both --verbose and --null')
1318
all = not (unknown or versioned or ignored)
1320
selection = {'I':ignored, '?':unknown, 'V':versioned}
1322
tree, relpath = WorkingTree.open_containing(u'.')
1327
if revision is not None:
1328
tree = tree.branch.repository.revision_tree(
1329
revision[0].in_history(tree.branch).rev_id)
1331
for fp, fc, kind, fid, entry in tree.list_files():
1332
if fp.startswith(relpath):
1333
fp = fp[len(relpath):]
1334
if non_recursive and '/' in fp:
1336
if not all and not selection[fc]:
1339
kindch = entry.kind_character()
1340
self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1343
self.outf.write('\0')
1347
self.outf.write('\n')
1350
class cmd_unknowns(Command):
1351
"""List unknown files."""
1354
from bzrlib.osutils import quotefn
1355
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1356
self.outf.write(quotefn(f))
1357
self.outf.write('\n')
1360
class cmd_ignore(Command):
1361
"""Ignore a command or pattern.
1363
To remove patterns from the ignore list, edit the .bzrignore file.
1365
If the pattern contains a slash, it is compared to the whole path
1366
from the branch root. Otherwise, it is compared to only the last
1367
component of the path. To match a file only in the root directory,
1370
Ignore patterns are case-insensitive on case-insensitive systems.
1372
Note: wildcards must be quoted from the shell on Unix.
1375
bzr ignore ./Makefile
1376
bzr ignore '*.class'
1378
# TODO: Complain if the filename is absolute
1379
takes_args = ['name_pattern']
1381
def run(self, name_pattern):
1382
from bzrlib.atomicfile import AtomicFile
1385
tree, relpath = WorkingTree.open_containing(u'.')
1386
ifn = tree.abspath('.bzrignore')
1388
if os.path.exists(ifn):
1391
igns = f.read().decode('utf-8')
1397
# TODO: If the file already uses crlf-style termination, maybe
1398
# we should use that for the newly added lines?
1400
if igns and igns[-1] != '\n':
1402
igns += name_pattern + '\n'
1405
f = AtomicFile(ifn, 'wt')
1406
f.write(igns.encode('utf-8'))
1411
inv = tree.inventory
1412
if inv.path2id('.bzrignore'):
1413
mutter('.bzrignore is already versioned')
1415
mutter('need to make new .bzrignore file versioned')
1416
tree.add(['.bzrignore'])
1419
class cmd_ignored(Command):
1420
"""List ignored files and the patterns that matched them.
1422
See also: bzr ignore"""
1425
tree = WorkingTree.open_containing(u'.')[0]
1426
for path, file_class, kind, file_id, entry in tree.list_files():
1427
if file_class != 'I':
1429
## XXX: Slightly inefficient since this was already calculated
1430
pat = tree.is_ignored(path)
1431
print '%-50s %s' % (path, pat)
1434
class cmd_lookup_revision(Command):
1435
"""Lookup the revision-id from a revision-number
1438
bzr lookup-revision 33
1441
takes_args = ['revno']
1444
def run(self, revno):
1448
raise BzrCommandError("not a valid revision-number: %r" % revno)
1450
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1453
class cmd_export(Command):
1454
"""Export past revision to destination directory.
1456
If no revision is specified this exports the last committed revision.
1458
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1459
given, try to find the format with the extension. If no extension
1460
is found exports to a directory (equivalent to --format=dir).
1462
Root may be the top directory for tar, tgz and tbz2 formats. If none
1463
is given, the top directory will be the root name of the file.
1465
Note: export of tree with non-ascii filenames to zip is not supported.
1467
Supported formats Autodetected by extension
1468
----------------- -------------------------
1471
tbz2 .tar.bz2, .tbz2
1475
takes_args = ['dest']
1476
takes_options = ['revision', 'format', 'root']
1477
def run(self, dest, revision=None, format=None, root=None):
1479
from bzrlib.export import export
1480
tree = WorkingTree.open_containing(u'.')[0]
1482
if revision is None:
1483
# should be tree.last_revision FIXME
1484
rev_id = b.last_revision()
1486
if len(revision) != 1:
1487
raise BzrError('bzr export --revision takes exactly 1 argument')
1488
rev_id = revision[0].in_history(b).rev_id
1489
t = b.repository.revision_tree(rev_id)
1491
export(t, dest, format, root)
1492
except errors.NoSuchExportFormat, e:
1493
raise BzrCommandError('Unsupported export format: %s' % e.format)
1496
class cmd_cat(Command):
1497
"""Write a file's text from a previous revision."""
1499
takes_options = ['revision']
1500
takes_args = ['filename']
1503
def run(self, filename, revision=None):
1504
if revision is not None and len(revision) != 1:
1505
raise BzrCommandError("bzr cat --revision takes exactly one number")
1508
tree, relpath = WorkingTree.open_containing(filename)
1510
except NotBranchError:
1514
b, relpath = Branch.open_containing(filename)
1515
if revision is None:
1516
revision_id = b.last_revision()
1518
revision_id = revision[0].in_history(b).rev_id
1519
b.print_file(relpath, revision_id)
1522
class cmd_local_time_offset(Command):
1523
"""Show the offset in seconds from GMT to local time."""
1527
print bzrlib.osutils.local_time_offset()
1531
class cmd_commit(Command):
1532
"""Commit changes into a new revision.
1534
If no arguments are given, the entire tree is committed.
1536
If selected files are specified, only changes to those files are
1537
committed. If a directory is specified then the directory and everything
1538
within it is committed.
1540
A selected-file commit may fail in some cases where the committed
1541
tree would be invalid, such as trying to commit a file in a
1542
newly-added directory that is not itself committed.
1544
# TODO: Run hooks on tree to-be-committed, and after commit.
1546
# TODO: Strict commit that fails if there are deleted files.
1547
# (what does "deleted files" mean ??)
1549
# TODO: Give better message for -s, --summary, used by tla people
1551
# XXX: verbose currently does nothing
1553
takes_args = ['selected*']
1554
takes_options = ['message', 'verbose',
1556
help='commit even if nothing has changed'),
1557
Option('file', type=str,
1559
help='file containing commit message'),
1561
help="refuse to commit if there are unknown "
1562
"files in the working tree."),
1564
help="perform a local only commit in a bound "
1565
"branch. Such commits are not pushed to "
1566
"the master branch until a normal commit "
1570
aliases = ['ci', 'checkin']
1572
def run(self, message=None, file=None, verbose=True, selected_list=None,
1573
unchanged=False, strict=False, local=False):
1574
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
1575
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1577
from bzrlib.msgeditor import edit_commit_message, \
1578
make_commit_message_template
1579
from tempfile import TemporaryFile
1581
# TODO: Need a blackbox test for invoking the external editor; may be
1582
# slightly problematic to run this cross-platform.
1584
# TODO: do more checks that the commit will succeed before
1585
# spending the user's valuable time typing a commit message.
1587
# TODO: if the commit *does* happen to fail, then save the commit
1588
# message to a temporary file where it can be recovered
1589
tree, selected_list = tree_files(selected_list)
1590
if local and not tree.branch.get_bound_location():
1591
raise errors.LocalRequiresBoundBranch()
1592
if message is None and not file:
1593
template = make_commit_message_template(tree, selected_list)
1594
message = edit_commit_message(template)
1596
raise BzrCommandError("please specify a commit message"
1597
" with either --message or --file")
1598
elif message and file:
1599
raise BzrCommandError("please specify either --message or --file")
1602
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1605
raise BzrCommandError("empty commit message specified")
1608
reporter = ReportCommitToLog()
1610
reporter = NullCommitReporter()
1613
tree.commit(message, specific_files=selected_list,
1614
allow_pointless=unchanged, strict=strict, local=local,
1616
except PointlessCommit:
1617
# FIXME: This should really happen before the file is read in;
1618
# perhaps prepare the commit; get the message; then actually commit
1619
raise BzrCommandError("no changes to commit",
1620
["use --unchanged to commit anyhow"])
1621
except ConflictsInTree:
1622
raise BzrCommandError("Conflicts detected in working tree. "
1623
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1624
except StrictCommitFailed:
1625
raise BzrCommandError("Commit refused because there are unknown "
1626
"files in the working tree.")
1627
except errors.BoundBranchOutOfDate, e:
1628
raise BzrCommandError(str(e)
1629
+ ' Either unbind, update, or'
1630
' pass --local to commit.')
1633
class cmd_check(Command):
1634
"""Validate consistency of branch history.
1636
This command checks various invariants about the branch storage to
1637
detect data corruption or bzr bugs.
1639
takes_args = ['branch?']
1640
takes_options = ['verbose']
1642
def run(self, branch=None, verbose=False):
1643
from bzrlib.check import check
1645
tree = WorkingTree.open_containing()[0]
1646
branch = tree.branch
1648
branch = Branch.open(branch)
1649
check(branch, verbose)
1652
class cmd_scan_cache(Command):
1655
from bzrlib.hashcache import HashCache
1661
print '%6d stats' % c.stat_count
1662
print '%6d in hashcache' % len(c._cache)
1663
print '%6d files removed from cache' % c.removed_count
1664
print '%6d hashes updated' % c.update_count
1665
print '%6d files changed too recently to cache' % c.danger_count
1671
class cmd_upgrade(Command):
1672
"""Upgrade branch storage to current format.
1674
The check command or bzr developers may sometimes advise you to run
1675
this command. When the default format has changed you may also be warned
1676
during other operations to upgrade.
1678
takes_args = ['url?']
1681
help='Upgrade to a specific format rather than the'
1682
' current default format. Currently this'
1683
' option accepts "weave", "metadir" and'
1685
type=get_format_type),
1689
def run(self, url='.', format=None):
1690
from bzrlib.upgrade import upgrade
1691
upgrade(url, format)
1694
class cmd_whoami(Command):
1695
"""Show bzr user id."""
1696
takes_options = ['email']
1699
def run(self, email=False):
1701
b = WorkingTree.open_containing(u'.')[0].branch
1702
config = bzrlib.config.BranchConfig(b)
1703
except NotBranchError:
1704
config = bzrlib.config.GlobalConfig()
1707
print config.user_email()
1709
print config.username()
1712
class cmd_nick(Command):
1713
"""Print or set the branch nickname.
1715
If unset, the tree root directory name is used as the nickname
1716
To print the current nickname, execute with no argument.
1718
takes_args = ['nickname?']
1719
def run(self, nickname=None):
1720
branch = Branch.open_containing(u'.')[0]
1721
if nickname is None:
1722
self.printme(branch)
1724
branch.nick = nickname
1727
def printme(self, branch):
1731
class cmd_selftest(Command):
1732
"""Run internal test suite.
1734
This creates temporary test directories in the working directory,
1735
but not existing data is affected. These directories are deleted
1736
if the tests pass, or left behind to help in debugging if they
1737
fail and --keep-output is specified.
1739
If arguments are given, they are regular expressions that say
1740
which tests should run.
1742
If the global option '--no-plugins' is given, plugins are not loaded
1743
before running the selftests. This has two effects: features provided or
1744
modified by plugins will not be tested, and tests provided by plugins will
1749
bzr --no-plugins selftest -v
1751
# TODO: --list should give a list of all available tests
1753
# NB: this is used from the class without creating an instance, which is
1754
# why it does not have a self parameter.
1755
def get_transport_type(typestring):
1756
"""Parse and return a transport specifier."""
1757
if typestring == "sftp":
1758
from bzrlib.transport.sftp import SFTPAbsoluteServer
1759
return SFTPAbsoluteServer
1760
if typestring == "memory":
1761
from bzrlib.transport.memory import MemoryServer
1763
if typestring == "fakenfs":
1764
from bzrlib.transport.fakenfs import FakeNFSServer
1765
return FakeNFSServer
1766
msg = "No known transport type %s. Supported types are: sftp\n" %\
1768
raise BzrCommandError(msg)
1771
takes_args = ['testspecs*']
1772
takes_options = ['verbose',
1773
Option('one', help='stop when one test fails'),
1774
Option('keep-output',
1775
help='keep output directories when tests fail'),
1777
help='Use a different transport by default '
1778
'throughout the test suite.',
1779
type=get_transport_type),
1782
def run(self, testspecs_list=None, verbose=False, one=False,
1783
keep_output=False, transport=None):
1785
from bzrlib.tests import selftest
1786
# we don't want progress meters from the tests to go to the
1787
# real output; and we don't want log messages cluttering up
1789
save_ui = bzrlib.ui.ui_factory
1790
bzrlib.trace.info('running tests...')
1792
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1793
if testspecs_list is not None:
1794
pattern = '|'.join(testspecs_list)
1797
result = selftest(verbose=verbose,
1799
stop_on_failure=one,
1800
keep_output=keep_output,
1801
transport=transport)
1803
bzrlib.trace.info('tests passed')
1805
bzrlib.trace.info('tests failed')
1806
return int(not result)
1808
bzrlib.ui.ui_factory = save_ui
1811
def _get_bzr_branch():
1812
"""If bzr is run from a branch, return Branch or None"""
1813
import bzrlib.errors
1814
from bzrlib.branch import Branch
1815
from bzrlib.osutils import abspath
1816
from os.path import dirname
1819
branch = Branch.open(dirname(abspath(dirname(__file__))))
1821
except bzrlib.errors.BzrError:
1826
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1827
# is bzrlib itself in a branch?
1828
branch = _get_bzr_branch()
1830
rh = branch.revision_history()
1832
print " bzr checkout, revision %d" % (revno,)
1833
print " nick: %s" % (branch.nick,)
1835
print " revid: %s" % (rh[-1],)
1836
print bzrlib.__copyright__
1837
print "http://bazaar-ng.org/"
1839
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1840
print "you may use, modify and redistribute it under the terms of the GNU"
1841
print "General Public License version 2 or later."
1844
class cmd_version(Command):
1845
"""Show version of bzr."""
1850
class cmd_rocks(Command):
1851
"""Statement of optimism."""
1855
print "it sure does!"
1858
class cmd_find_merge_base(Command):
1859
"""Find and print a base revision for merging two branches.
1861
# TODO: Options to specify revisions on either side, as if
1862
# merging only part of the history.
1863
takes_args = ['branch', 'other']
1867
def run(self, branch, other):
1868
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1870
branch1 = Branch.open_containing(branch)[0]
1871
branch2 = Branch.open_containing(other)[0]
1873
history_1 = branch1.revision_history()
1874
history_2 = branch2.revision_history()
1876
last1 = branch1.last_revision()
1877
last2 = branch2.last_revision()
1879
source = MultipleRevisionSources(branch1.repository,
1882
base_rev_id = common_ancestor(last1, last2, source)
1884
print 'merge base is revision %s' % base_rev_id
1888
if base_revno is None:
1889
raise bzrlib.errors.UnrelatedBranches()
1891
print ' r%-6d in %s' % (base_revno, branch)
1893
other_revno = branch2.revision_id_to_revno(base_revid)
1895
print ' r%-6d in %s' % (other_revno, other)
1899
class cmd_merge(Command):
1900
"""Perform a three-way merge.
1902
The branch is the branch you will merge from. By default, it will
1903
merge the latest revision. If you specify a revision, that
1904
revision will be merged. If you specify two revisions, the first
1905
will be used as a BASE, and the second one as OTHER. Revision
1906
numbers are always relative to the specified branch.
1908
By default, bzr will try to merge in all new work from the other
1909
branch, automatically determining an appropriate base. If this
1910
fails, you may need to give an explicit base.
1912
Merge will do its best to combine the changes in two branches, but there
1913
are some kinds of problems only a human can fix. When it encounters those,
1914
it will mark a conflict. A conflict means that you need to fix something,
1915
before you should commit.
1917
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
1919
If there is no default branch set, the first merge will set it. After
1920
that, you can omit the branch to use the default. To change the
1921
default, use --remember.
1925
To merge the latest revision from bzr.dev
1926
bzr merge ../bzr.dev
1928
To merge changes up to and including revision 82 from bzr.dev
1929
bzr merge -r 82 ../bzr.dev
1931
To merge the changes introduced by 82, without previous changes:
1932
bzr merge -r 81..82 ../bzr.dev
1934
merge refuses to run if there are any uncommitted changes, unless
1937
takes_args = ['branch?']
1938
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
1939
Option('show-base', help="Show base revision text in "
1942
def run(self, branch=None, revision=None, force=False, merge_type=None,
1943
show_base=False, reprocess=False, remember=False):
1944
if merge_type is None:
1945
merge_type = Merge3Merger
1947
tree = WorkingTree.open_containing(u'.')[0]
1948
stored_loc = tree.branch.get_parent()
1950
if stored_loc is None:
1951
raise BzrCommandError("No merge branch known or specified.")
1953
print "Using saved branch: %s" % stored_loc
1956
if revision is None or len(revision) < 1:
1958
other = [branch, -1]
1959
other_branch, path = Branch.open_containing(branch)
1961
if len(revision) == 1:
1963
other_branch, path = Branch.open_containing(branch)
1964
revno = revision[0].in_history(other_branch).revno
1965
other = [branch, revno]
1967
assert len(revision) == 2
1968
if None in revision:
1969
raise BzrCommandError(
1970
"Merge doesn't permit that revision specifier.")
1971
other_branch, path = Branch.open_containing(branch)
1973
base = [branch, revision[0].in_history(other_branch).revno]
1974
other = [branch, revision[1].in_history(other_branch).revno]
1976
if tree.branch.get_parent() is None or remember:
1977
tree.branch.set_parent(other_branch.base)
1980
interesting_files = [path]
1982
interesting_files = None
1983
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1986
conflict_count = merge(other, base, check_clean=(not force),
1987
merge_type=merge_type,
1988
reprocess=reprocess,
1989
show_base=show_base,
1990
pb=pb, file_list=interesting_files)
1993
if conflict_count != 0:
1997
except bzrlib.errors.AmbiguousBase, e:
1998
m = ("sorry, bzr can't determine the right merge base yet\n"
1999
"candidates are:\n "
2000
+ "\n ".join(e.bases)
2002
"please specify an explicit base with -r,\n"
2003
"and (if you want) report this to the bzr developers\n")
2007
class cmd_remerge(Command):
2010
takes_args = ['file*']
2011
takes_options = ['merge-type', 'reprocess',
2012
Option('show-base', help="Show base revision text in "
2015
def run(self, file_list=None, merge_type=None, show_base=False,
2017
from bzrlib.merge import merge_inner, transform_tree
2018
if merge_type is None:
2019
merge_type = Merge3Merger
2020
tree, file_list = tree_files(file_list)
2023
pending_merges = tree.pending_merges()
2024
if len(pending_merges) != 1:
2025
raise BzrCommandError("Sorry, remerge only works after normal"
2026
+ " merges. Not cherrypicking or"
2028
repository = tree.branch.repository
2029
base_revision = common_ancestor(tree.branch.last_revision(),
2030
pending_merges[0], repository)
2031
base_tree = repository.revision_tree(base_revision)
2032
other_tree = repository.revision_tree(pending_merges[0])
2033
interesting_ids = None
2034
if file_list is not None:
2035
interesting_ids = set()
2036
for filename in file_list:
2037
file_id = tree.path2id(filename)
2039
raise NotVersionedError(filename)
2040
interesting_ids.add(file_id)
2041
if tree.kind(file_id) != "directory":
2044
for name, ie in tree.inventory.iter_entries(file_id):
2045
interesting_ids.add(ie.file_id)
2046
transform_tree(tree, tree.basis_tree(), interesting_ids)
2047
if file_list is None:
2048
restore_files = list(tree.iter_conflicts())
2050
restore_files = file_list
2051
for filename in restore_files:
2053
restore(tree.abspath(filename))
2054
except NotConflicted:
2056
conflicts = merge_inner(tree.branch, other_tree, base_tree,
2058
interesting_ids = interesting_ids,
2059
other_rev_id=pending_merges[0],
2060
merge_type=merge_type,
2061
show_base=show_base,
2062
reprocess=reprocess)
2070
class cmd_revert(Command):
2071
"""Reverse all changes since the last commit.
2073
Only versioned files are affected. Specify filenames to revert only
2074
those files. By default, any files that are changed will be backed up
2075
first. Backup files have a '~' appended to their name.
2077
takes_options = ['revision', 'no-backup']
2078
takes_args = ['file*']
2079
aliases = ['merge-revert']
2081
def run(self, revision=None, no_backup=False, file_list=None):
2082
from bzrlib.commands import parse_spec
2083
if file_list is not None:
2084
if len(file_list) == 0:
2085
raise BzrCommandError("No files specified")
2089
tree, file_list = tree_files(file_list)
2090
if revision is None:
2091
# FIXME should be tree.last_revision
2092
rev_id = tree.last_revision()
2093
elif len(revision) != 1:
2094
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
2096
rev_id = revision[0].in_history(tree.branch).rev_id
2097
pb = bzrlib.ui.ui_factory.nested_progress_bar()
2099
tree.revert(file_list,
2100
tree.branch.repository.revision_tree(rev_id),
2106
class cmd_assert_fail(Command):
2107
"""Test reporting of assertion failures"""
2110
assert False, "always fails"
2113
class cmd_help(Command):
2114
"""Show help on a command or other topic.
2116
For a list of all available commands, say 'bzr help commands'."""
2117
takes_options = [Option('long', 'show help on all commands')]
2118
takes_args = ['topic?']
2119
aliases = ['?', '--help', '-?', '-h']
2122
def run(self, topic=None, long=False):
2124
if topic is None and long:
2129
class cmd_shell_complete(Command):
2130
"""Show appropriate completions for context.
2132
For a list of all available commands, say 'bzr shell-complete'."""
2133
takes_args = ['context?']
2138
def run(self, context=None):
2139
import shellcomplete
2140
shellcomplete.shellcomplete(context)
2143
class cmd_fetch(Command):
2144
"""Copy in history from another branch but don't merge it.
2146
This is an internal method used for pull and merge."""
2148
takes_args = ['from_branch', 'to_branch']
2149
def run(self, from_branch, to_branch):
2150
from bzrlib.fetch import Fetcher
2151
from bzrlib.branch import Branch
2152
from_b = Branch.open(from_branch)
2153
to_b = Branch.open(to_branch)
2154
Fetcher(to_b, from_b)
2157
class cmd_missing(Command):
2158
"""Show unmerged/unpulled revisions between two branches.
2160
OTHER_BRANCH may be local or remote."""
2161
takes_args = ['other_branch?']
2162
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2164
'Display changes in the local branch only'),
2165
Option('theirs-only',
2166
'Display changes in the remote branch only'),
2175
def run(self, other_branch=None, reverse=False, mine_only=False,
2176
theirs_only=False, log_format=None, long=False, short=False, line=False,
2177
show_ids=False, verbose=False):
2178
from bzrlib.missing import find_unmerged, iter_log_data
2179
from bzrlib.log import log_formatter
2180
local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
2181
parent = local_branch.get_parent()
2182
if other_branch is None:
2183
other_branch = parent
2184
if other_branch is None:
2185
raise BzrCommandError("No missing location known or specified.")
2186
print "Using last location: " + local_branch.get_parent()
2187
remote_branch = bzrlib.branch.Branch.open(other_branch)
2188
if remote_branch.base == local_branch.base:
2189
remote_branch = local_branch
2190
local_branch.lock_read()
2192
remote_branch.lock_read()
2194
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2195
if (log_format == None):
2196
default = bzrlib.config.BranchConfig(local_branch).log_format()
2197
log_format = get_log_format(long=long, short=short, line=line, default=default)
2198
lf = log_formatter(log_format, sys.stdout,
2200
show_timezone='original')
2201
if reverse is False:
2202
local_extra.reverse()
2203
remote_extra.reverse()
2204
if local_extra and not theirs_only:
2205
print "You have %d extra revision(s):" % len(local_extra)
2206
for data in iter_log_data(local_extra, local_branch.repository,
2209
printed_local = True
2211
printed_local = False
2212
if remote_extra and not mine_only:
2213
if printed_local is True:
2215
print "You are missing %d revision(s):" % len(remote_extra)
2216
for data in iter_log_data(remote_extra, remote_branch.repository,
2219
if not remote_extra and not local_extra:
2221
print "Branches are up to date."
2225
remote_branch.unlock()
2227
local_branch.unlock()
2228
if not status_code and parent is None and other_branch is not None:
2229
local_branch.lock_write()
2231
# handle race conditions - a parent might be set while we run.
2232
if local_branch.get_parent() is None:
2233
local_branch.set_parent(remote_branch.base)
2235
local_branch.unlock()
2239
class cmd_plugins(Command):
2244
import bzrlib.plugin
2245
from inspect import getdoc
2246
for name, plugin in bzrlib.plugin.all_plugins().items():
2247
if hasattr(plugin, '__path__'):
2248
print plugin.__path__[0]
2249
elif hasattr(plugin, '__file__'):
2250
print plugin.__file__
2256
print '\t', d.split('\n')[0]
2259
class cmd_testament(Command):
2260
"""Show testament (signing-form) of a revision."""
2261
takes_options = ['revision', 'long']
2262
takes_args = ['branch?']
2264
def run(self, branch=u'.', revision=None, long=False):
2265
from bzrlib.testament import Testament
2266
b = WorkingTree.open_containing(branch)[0].branch
2269
if revision is None:
2270
rev_id = b.last_revision()
2272
rev_id = revision[0].in_history(b).rev_id
2273
t = Testament.from_revision(b.repository, rev_id)
2275
sys.stdout.writelines(t.as_text_lines())
2277
sys.stdout.write(t.as_short_text())
2282
class cmd_annotate(Command):
2283
"""Show the origin of each line in a file.
2285
This prints out the given file with an annotation on the left side
2286
indicating which revision, author and date introduced the change.
2288
If the origin is the same for a run of consecutive lines, it is
2289
shown only at the top, unless the --all option is given.
2291
# TODO: annotate directories; showing when each file was last changed
2292
# TODO: annotate a previous version of a file
2293
# TODO: if the working copy is modified, show annotations on that
2294
# with new uncommitted lines marked
2295
aliases = ['blame', 'praise']
2296
takes_args = ['filename']
2297
takes_options = [Option('all', help='show annotations on all lines'),
2298
Option('long', help='show date in annotations'),
2302
def run(self, filename, all=False, long=False):
2303
from bzrlib.annotate import annotate_file
2304
tree, relpath = WorkingTree.open_containing(filename)
2305
branch = tree.branch
2308
file_id = tree.inventory.path2id(relpath)
2309
tree = branch.repository.revision_tree(branch.last_revision())
2310
file_version = tree.inventory[file_id].revision
2311
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
2316
class cmd_re_sign(Command):
2317
"""Create a digital signature for an existing revision."""
2318
# TODO be able to replace existing ones.
2320
hidden = True # is this right ?
2321
takes_args = ['revision_id*']
2322
takes_options = ['revision']
2324
def run(self, revision_id_list=None, revision=None):
2325
import bzrlib.config as config
2326
import bzrlib.gpg as gpg
2327
if revision_id_list is not None and revision is not None:
2328
raise BzrCommandError('You can only supply one of revision_id or --revision')
2329
if revision_id_list is None and revision is None:
2330
raise BzrCommandError('You must supply either --revision or a revision_id')
2331
b = WorkingTree.open_containing(u'.')[0].branch
2332
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
2333
if revision_id_list is not None:
2334
for revision_id in revision_id_list:
2335
b.repository.sign_revision(revision_id, gpg_strategy)
2336
elif revision is not None:
2337
if len(revision) == 1:
2338
revno, rev_id = revision[0].in_history(b)
2339
b.repository.sign_revision(rev_id, gpg_strategy)
2340
elif len(revision) == 2:
2341
# are they both on rh- if so we can walk between them
2342
# might be nice to have a range helper for arbitrary
2343
# revision paths. hmm.
2344
from_revno, from_revid = revision[0].in_history(b)
2345
to_revno, to_revid = revision[1].in_history(b)
2346
if to_revid is None:
2347
to_revno = b.revno()
2348
if from_revno is None or to_revno is None:
2349
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
2350
for revno in range(from_revno, to_revno + 1):
2351
b.repository.sign_revision(b.get_rev_id(revno),
2354
raise BzrCommandError('Please supply either one revision, or a range.')
2357
class cmd_bind(Command):
2358
"""Bind the current branch to a master branch.
2360
After binding, commits must succeed on the master branch
2361
before they are executed on the local one.
2364
takes_args = ['location']
2367
def run(self, location=None):
2368
b, relpath = Branch.open_containing(u'.')
2369
b_other = Branch.open(location)
2372
except DivergedBranches:
2373
raise BzrCommandError('These branches have diverged.'
2374
' Try merging, and then bind again.')
2377
class cmd_unbind(Command):
2378
"""Bind the current branch to its parent.
2380
After unbinding, the local branch is considered independent.
2387
b, relpath = Branch.open_containing(u'.')
2389
raise BzrCommandError('Local branch is not bound')
2392
class cmd_uncommit(bzrlib.commands.Command):
2393
"""Remove the last committed revision.
2395
By supplying the --all flag, it will not only remove the entry
2396
from revision_history, but also remove all of the entries in the
2399
--verbose will print out what is being removed.
2400
--dry-run will go through all the motions, but not actually
2403
In the future, uncommit will create a changeset, which can then
2407
# TODO: jam 20060108 Add an option to allow uncommit to remove
2408
# unreferenced information in 'branch-as-repostory' branches.
2409
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
2410
# information in shared branches as well.
2411
takes_options = ['verbose', 'revision',
2412
Option('dry-run', help='Don\'t actually make changes'),
2413
Option('force', help='Say yes to all questions.')]
2414
takes_args = ['location?']
2417
def run(self, location=None,
2418
dry_run=False, verbose=False,
2419
revision=None, force=False):
2420
from bzrlib.branch import Branch
2421
from bzrlib.log import log_formatter
2423
from bzrlib.uncommit import uncommit
2425
if location is None:
2427
control, relpath = bzrdir.BzrDir.open_containing(location)
2429
tree = control.open_workingtree()
2431
except (errors.NoWorkingTree, errors.NotLocalUrl):
2433
b = control.open_branch()
2435
if revision is None:
2437
rev_id = b.last_revision()
2439
revno, rev_id = revision[0].in_history(b)
2441
print 'No revisions to uncommit.'
2443
for r in range(revno, b.revno()+1):
2444
rev_id = b.get_rev_id(r)
2445
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2446
lf.show(r, b.repository.get_revision(rev_id), None)
2449
print 'Dry-run, pretending to remove the above revisions.'
2451
val = raw_input('Press <enter> to continue')
2453
print 'The above revision(s) will be removed.'
2455
val = raw_input('Are you sure [y/N]? ')
2456
if val.lower() not in ('y', 'yes'):
2460
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
2464
class cmd_break_lock(Command):
2465
"""Break a dead lock on a repository, branch or working directory.
2467
CAUTION: Locks should only be broken when you are sure that the process
2468
holding the lock has been stopped.
2473
takes_args = ['location']
2474
takes_options = [Option('show',
2475
help="just show information on the lock, " \
2478
def run(self, location, show=False):
2479
raise NotImplementedError("sorry, break-lock is not complete yet; "
2480
"you can remove the 'held' directory manually to break the lock")
2483
# command-line interpretation helper for merge-related commands
2484
def merge(other_revision, base_revision,
2485
check_clean=True, ignore_zero=False,
2486
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2487
file_list=None, show_base=False, reprocess=False,
2488
pb=DummyProgress()):
2489
"""Merge changes into a tree.
2492
list(path, revno) Base for three-way merge.
2493
If [None, None] then a base will be automatically determined.
2495
list(path, revno) Other revision for three-way merge.
2497
Directory to merge changes into; '.' by default.
2499
If true, this_dir must have no uncommitted changes before the
2501
ignore_zero - If true, suppress the "zero conflicts" message when
2502
there are no conflicts; should be set when doing something we expect
2503
to complete perfectly.
2504
file_list - If supplied, merge only changes to selected files.
2506
All available ancestors of other_revision and base_revision are
2507
automatically pulled into the branch.
2509
The revno may be -1 to indicate the last revision on the branch, which is
2512
This function is intended for use from the command line; programmatic
2513
clients might prefer to call merge.merge_inner(), which has less magic
2516
from bzrlib.merge import Merger
2517
if this_dir is None:
2519
this_tree = WorkingTree.open_containing(this_dir)[0]
2520
if show_base and not merge_type is Merge3Merger:
2521
raise BzrCommandError("Show-base is not supported for this merge"
2522
" type. %s" % merge_type)
2523
if reprocess and not merge_type.supports_reprocess:
2524
raise BzrCommandError("Conflict reduction is not supported for merge"
2525
" type %s." % merge_type)
2526
if reprocess and show_base:
2527
raise BzrCommandError("Cannot do conflict reduction and show base.")
2529
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2530
merger.pp = ProgressPhase("Merge phase", 5, pb)
2531
merger.pp.next_phase()
2532
merger.check_basis(check_clean)
2533
merger.set_other(other_revision)
2534
merger.pp.next_phase()
2535
merger.set_base(base_revision)
2536
if merger.base_rev_id == merger.other_rev_id:
2537
note('Nothing to do.')
2539
merger.backup_files = backup_files
2540
merger.merge_type = merge_type
2541
merger.set_interesting_files(file_list)
2542
merger.show_base = show_base
2543
merger.reprocess = reprocess
2544
conflicts = merger.do_merge()
2545
if file_list is None:
2546
merger.set_pending()
2552
# these get imported and then picked up by the scan for cmd_*
2553
# TODO: Some more consistent way to split command definitions across files;
2554
# we do need to load at least some information about them to know of
2555
# aliases. ideally we would avoid loading the implementation until the
2556
# details were needed.
2557
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2558
from bzrlib.sign_my_commits import cmd_sign_my_commits
2559
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
2560
cmd_weave_plan_merge, cmd_weave_merge_text