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
41
from bzrlib.progress import DummyProgress, ProgressPhase
42
from bzrlib.revisionspec import RevisionSpec
44
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
45
from bzrlib.transport.local import LocalTransport
47
import bzrlib.urlutils as urlutils
48
from bzrlib.workingtree import WorkingTree
51
def tree_files(file_list, default_branch=u'.'):
53
return internal_tree_files(file_list, default_branch)
54
except FileInWrongBranch, e:
55
raise BzrCommandError("%s is not in the same branch as %s" %
56
(e.path, file_list[0]))
59
# XXX: Bad function name; should possibly also be a class method of
60
# WorkingTree rather than a function.
61
def internal_tree_files(file_list, default_branch=u'.'):
62
"""Convert command-line paths to a WorkingTree and relative paths.
64
This is typically used for command-line processors that take one or
65
more filenames, and infer the workingtree that contains them.
67
The filenames given are not required to exist.
69
:param file_list: Filenames to convert.
71
:param default_branch: Fallback tree path to use if file_list is empty or None.
73
:return: workingtree, [relative_paths]
75
if file_list is None or len(file_list) == 0:
76
return WorkingTree.open_containing(default_branch)[0], file_list
77
tree = WorkingTree.open_containing(file_list[0])[0]
79
for filename in file_list:
81
new_list.append(tree.relpath(filename))
82
except errors.PathNotChild:
83
raise FileInWrongBranch(tree.branch, filename)
87
def get_format_type(typestring):
88
"""Parse and return a format specifier."""
89
if typestring == "weave":
90
return bzrdir.BzrDirFormat6()
91
if typestring == "metadir":
92
return bzrdir.BzrDirMetaFormat1()
93
if typestring == "knit":
94
format = bzrdir.BzrDirMetaFormat1()
95
format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
97
msg = "No known bzr-dir format %s. Supported types are: weave, metadir\n" %\
99
raise BzrCommandError(msg)
102
# TODO: Make sure no commands unconditionally use the working directory as a
103
# branch. If a filename argument is used, the first of them should be used to
104
# specify the branch. (Perhaps this can be factored out into some kind of
105
# Argument class, representing a file in a branch, where the first occurrence
108
class cmd_status(Command):
109
"""Display status summary.
111
This reports on versioned and unknown files, reporting them
112
grouped by state. Possible states are:
115
Versioned in the working copy but not in the previous revision.
118
Versioned in the previous revision but removed or deleted
122
Path of this file changed from the previous revision;
123
the text may also have changed. This includes files whose
124
parent directory was renamed.
127
Text has changed since the previous revision.
130
Nothing about this file has changed since the previous revision.
131
Only shown with --all.
134
Not versioned and not matching an ignore pattern.
136
To see ignored files use 'bzr ignored'. For details in the
137
changes to file texts, use 'bzr diff'.
139
If no arguments are specified, the status of the entire working
140
directory is shown. Otherwise, only the status of the specified
141
files or directories is reported. If a directory is given, status
142
is reported for everything inside that directory.
144
If a revision argument is given, the status is calculated against
145
that revision, or between two revisions if two are provided.
148
# TODO: --no-recurse, --recurse options
150
takes_args = ['file*']
151
takes_options = ['all', 'show-ids', 'revision']
152
aliases = ['st', 'stat']
154
encoding_type = 'replace'
157
def run(self, all=False, show_ids=False, file_list=None, revision=None):
158
from bzrlib.status import show_tree_status
160
tree, file_list = tree_files(file_list)
162
show_tree_status(tree, show_unchanged=all, show_ids=show_ids,
163
specific_files=file_list, revision=revision,
167
class cmd_cat_revision(Command):
168
"""Write out metadata for a revision.
170
The revision to print can either be specified by a specific
171
revision identifier, or you can use --revision.
175
takes_args = ['revision_id?']
176
takes_options = ['revision']
179
def run(self, revision_id=None, revision=None):
181
if revision_id is not None and revision is not None:
182
raise BzrCommandError('You can only supply one of revision_id or --revision')
183
if revision_id is None and revision is None:
184
raise BzrCommandError('You must supply either --revision or a revision_id')
185
b = WorkingTree.open_containing(u'.')[0].branch
187
# TODO: jam 20060112 should cat-revision always output utf-8?
188
if revision_id is not None:
189
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
190
elif revision is not None:
193
raise BzrCommandError('You cannot specify a NULL revision.')
194
revno, rev_id = rev.in_history(b)
195
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
198
class cmd_revno(Command):
199
"""Show current revision number.
201
This is equal to the number of revisions on this branch.
204
takes_args = ['location?']
207
def run(self, location=u'.'):
208
self.outf.write(str(Branch.open_containing(location)[0].revno()))
209
self.outf.write('\n')
212
class cmd_revision_info(Command):
213
"""Show revision number and revision id for a given revision identifier.
216
takes_args = ['revision_info*']
217
takes_options = ['revision']
220
def run(self, revision=None, revision_info_list=[]):
223
if revision is not None:
224
revs.extend(revision)
225
if revision_info_list is not None:
226
for rev in revision_info_list:
227
revs.append(RevisionSpec(rev))
229
raise BzrCommandError('You must supply a revision identifier')
231
b = WorkingTree.open_containing(u'.')[0].branch
234
revinfo = rev.in_history(b)
235
if revinfo.revno is None:
236
print ' %s' % revinfo.rev_id
238
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
241
class cmd_add(Command):
242
"""Add specified files or directories.
244
In non-recursive mode, all the named items are added, regardless
245
of whether they were previously ignored. A warning is given if
246
any of the named files are already versioned.
248
In recursive mode (the default), files are treated the same way
249
but the behaviour for directories is different. Directories that
250
are already versioned do not give a warning. All directories,
251
whether already versioned or not, are searched for files or
252
subdirectories that are neither versioned or ignored, and these
253
are added. This search proceeds recursively into versioned
254
directories. If no names are given '.' is assumed.
256
Therefore simply saying 'bzr add' will version all files that
257
are currently unknown.
259
Adding a file whose parent directory is not versioned will
260
implicitly add the parent, and so on up to the root. This means
261
you should never need to explictly add a directory, they'll just
262
get added when you add a file in the directory.
264
--dry-run will show which files would be added, but not actually
267
takes_args = ['file*']
268
takes_options = ['no-recurse', 'dry-run', 'verbose']
269
encoding_type = 'replace'
271
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
274
action = bzrlib.add.AddAction(to_file=self.outf,
275
should_add=(not dry_run), should_print=(not is_quiet()))
277
added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
280
for glob in sorted(ignored.keys()):
281
match_len = len(ignored[glob])
283
for path in ignored[glob]:
284
self.outf.write("ignored %s matching \"%s\"\n"
287
self.outf.write("ignored %d file(s) matching \"%s\"\n"
289
self.outf.write("If you wish to add some of these files,"
290
" please add them by name.\n")
293
class cmd_mkdir(Command):
294
"""Create a new versioned directory.
296
This is equivalent to creating the directory and then adding it.
298
takes_args = ['dir+']
299
encoding_type = 'replace'
301
def run(self, dir_list):
304
wt, dd = WorkingTree.open_containing(d)
306
print >>self.outf, 'added', d
309
class cmd_relpath(Command):
310
"""Show path of a file relative to root"""
311
takes_args = ['filename']
315
def run(self, filename):
316
# TODO: jam 20050106 Can relpath return a munged path if
317
# sys.stdout encoding cannot represent it?
318
tree, relpath = WorkingTree.open_containing(filename)
319
self.outf.write(relpath)
320
self.outf.write('\n')
323
class cmd_inventory(Command):
324
"""Show inventory of the current working copy or a revision.
326
It is possible to limit the output to a particular entry
327
type using the --kind option. For example; --kind file.
329
takes_options = ['revision', 'show-ids', 'kind']
332
def run(self, revision=None, show_ids=False, kind=None):
333
if kind and kind not in ['file', 'directory', 'symlink']:
334
raise BzrCommandError('invalid kind specified')
335
tree = WorkingTree.open_containing(u'.')[0]
337
inv = tree.read_working_inventory()
339
if len(revision) > 1:
340
raise BzrCommandError('bzr inventory --revision takes'
341
' exactly one revision identifier')
342
inv = tree.branch.repository.get_revision_inventory(
343
revision[0].in_history(tree.branch).rev_id)
345
for path, entry in inv.entries():
346
if kind and kind != entry.kind:
349
self.outf.write('%-50s %s\n' % (path, entry.file_id))
351
self.outf.write(path)
352
self.outf.write('\n')
355
class cmd_mv(Command):
356
"""Move or rename a file.
359
bzr mv OLDNAME NEWNAME
360
bzr mv SOURCE... DESTINATION
362
If the last argument is a versioned directory, all the other names
363
are moved into it. Otherwise, there must be exactly two arguments
364
and the file is changed to a new name, which must not already exist.
366
Files cannot be moved between branches.
368
takes_args = ['names*']
369
aliases = ['move', 'rename']
371
encoding_type = 'replace'
373
def run(self, names_list):
374
if len(names_list) < 2:
375
raise BzrCommandError("missing file argument")
376
tree, rel_names = tree_files(names_list)
378
if os.path.isdir(names_list[-1]):
379
# move into existing directory
380
for pair in tree.move(rel_names[:-1], rel_names[-1]):
381
self.outf.write("%s => %s\n" % pair)
383
if len(names_list) != 2:
384
raise BzrCommandError('to mv multiple files the destination '
385
'must be a versioned directory')
386
tree.rename_one(rel_names[0], rel_names[1])
387
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
390
class cmd_pull(Command):
391
"""Turn this branch into a mirror of another branch.
393
This command only works on branches that have not diverged. Branches are
394
considered diverged if the destination branch's most recent commit is one
395
that has not been merged (directly or indirectly) into the parent.
397
If branches have diverged, you can use 'bzr merge' to integrate the changes
398
from one into the other. Once one branch has merged, the other should
399
be able to pull it again.
401
If branches have diverged, you can use 'bzr merge' to pull the text changes
402
from one into the other. Once one branch has merged, the other should
403
be able to pull it again.
405
If you want to forget your local changes and just update your branch to
406
match the remote one, use pull --overwrite.
408
If there is no default location set, the first pull will set it. After
409
that, you can omit the location to use the default. To change the
410
default, use --remember.
412
takes_options = ['remember', 'overwrite', 'revision', 'verbose']
413
takes_args = ['location?']
414
encoding_type = 'replace'
416
def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
417
# FIXME: too much stuff is in the command class
419
tree_to = WorkingTree.open_containing(u'.')[0]
420
branch_to = tree_to.branch
421
except NoWorkingTree:
423
branch_to = Branch.open_containing(u'.')[0]
424
stored_loc = branch_to.get_parent()
426
if stored_loc is None:
427
raise BzrCommandError("No pull location known or specified.")
429
self.outf.write("Using saved location: %s\n"
430
% urlutils.unescape_for_display(stored_loc))
431
location = stored_loc
433
branch_from = Branch.open(location)
435
if branch_to.get_parent() is None or remember:
436
branch_to.set_parent(branch_from.base)
441
elif len(revision) == 1:
442
rev_id = revision[0].in_history(branch_from).rev_id
444
raise BzrCommandError('bzr pull --revision takes one value.')
446
old_rh = branch_to.revision_history()
447
if tree_to is not None:
448
count = tree_to.pull(branch_from, overwrite, rev_id)
450
count = branch_to.pull(branch_from, overwrite, rev_id)
451
note('%d revision(s) pulled.' % (count,))
454
new_rh = branch_to.revision_history()
457
from bzrlib.log import show_changed_revisions
458
show_changed_revisions(branch_to, old_rh, new_rh,
462
class cmd_push(Command):
463
"""Update a mirror of this branch.
465
The target branch will not have its working tree populated because this
466
is both expensive, and is not supported on remote file systems.
468
Some smart servers or protocols *may* put the working tree in place in
471
This command only works on branches that have not diverged. Branches are
472
considered diverged if the destination branch's most recent commit is one
473
that has not been merged (directly or indirectly) by the source branch.
475
If branches have diverged, you can use 'bzr push --overwrite' to replace
476
the other branch completely, discarding its unmerged changes.
478
If you want to ensure you have the different changes in the other branch,
479
do a merge (see bzr help merge) from the other branch, and commit that.
480
After that you will be able to do a push without '--overwrite'.
482
If there is no default push location set, the first push will set it.
483
After that, you can omit the location to use the default. To change the
484
default, use --remember.
486
takes_options = ['remember', 'overwrite', 'verbose',
487
Option('create-prefix',
488
help='Create the path leading up to the branch '
489
'if it does not already exist')]
490
takes_args = ['location?']
491
encoding_type = 'replace'
493
def run(self, location=None, remember=False, overwrite=False,
494
create_prefix=False, verbose=False):
495
# FIXME: Way too big! Put this into a function called from the
497
from bzrlib.transport import get_transport
499
tree_from = WorkingTree.open_containing(u'.')[0]
500
br_from = tree_from.branch
501
stored_loc = tree_from.branch.get_push_location()
504
if stored_loc is None:
505
raise BzrCommandError("No push location known or specified.")
507
self.outf.write("Using saved location: %s"
508
% urlutils.unescape_for_display(stored_loc))
509
location = stored_loc
511
transport = get_transport(location)
512
location_url = transport.base
513
if br_from.get_push_location() is None or remember:
514
br_from.set_push_location(location_url)
516
dir_to = bzrlib.bzrdir.BzrDir.open(location_url)
517
br_to = dir_to.open_branch()
518
except NotBranchError:
520
transport = transport.clone('..')
521
if not create_prefix:
523
relurl = transport.relpath(location_url)
524
mutter('creating directory %s => %s', location_url, relurl)
525
transport.mkdir(relurl)
527
raise BzrCommandError("Parent directory of %s "
528
"does not exist." % location)
530
current = transport.base
531
needed = [(transport, transport.relpath(location_url))]
534
transport, relpath = needed[-1]
535
transport.mkdir(relpath)
538
new_transport = transport.clone('..')
539
needed.append((new_transport,
540
new_transport.relpath(transport.base)))
541
if new_transport.base == transport.base:
542
raise BzrCommandError("Could not create "
544
dir_to = br_from.bzrdir.clone(location_url)
545
br_to = dir_to.open_branch()
546
old_rh = br_to.revision_history()
549
tree_to = dir_to.open_workingtree()
550
except errors.NotLocalUrl:
551
# TODO: This should be updated for branches which don't have a
552
# working tree, as opposed to ones where we just couldn't
554
warning('This transport does not update the working '
555
'tree of: %s' % (br_to.base,))
556
count = br_to.pull(br_from, overwrite)
557
except NoWorkingTree:
558
count = br_to.pull(br_from, overwrite)
560
count = tree_to.pull(br_from, overwrite)
561
except DivergedBranches:
562
raise BzrCommandError("These branches have diverged."
563
" Try a merge then push with overwrite.")
564
note('%d revision(s) pushed.' % (count,))
567
new_rh = br_to.revision_history()
570
from bzrlib.log import show_changed_revisions
571
show_changed_revisions(br_to, old_rh, new_rh,
575
class cmd_branch(Command):
576
"""Create a new copy of a branch.
578
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
579
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
581
To retrieve the branch as of a particular revision, supply the --revision
582
parameter, as in "branch foo/bar -r 5".
584
--basis is to speed up branching from remote branches. When specified, it
585
copies all the file-contents, inventory and revision data from the basis
586
branch before copying anything from the remote branch.
588
takes_args = ['from_location', 'to_location?']
589
takes_options = ['revision', 'basis']
590
aliases = ['get', 'clone']
592
def run(self, from_location, to_location=None, revision=None, basis=None):
593
from bzrlib.transport import get_transport
596
elif len(revision) > 1:
597
raise BzrCommandError(
598
'bzr branch --revision takes exactly 1 revision value')
600
br_from = Branch.open(from_location)
602
if e.errno == errno.ENOENT:
603
raise BzrCommandError('Source location "%s" does not'
604
' exist.' % to_location)
609
if basis is not None:
610
basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
613
if len(revision) == 1 and revision[0] is not None:
614
revision_id = revision[0].in_history(br_from)[1]
616
# FIXME - wt.last_revision, fallback to branch, fall back to
617
# None or perhaps NULL_REVISION to mean copy nothing
619
revision_id = br_from.last_revision()
620
if to_location is None:
621
to_location = os.path.basename(from_location.rstrip("/\\"))
624
name = os.path.basename(to_location) + '\n'
626
to_transport = get_transport(to_location)
628
to_transport.mkdir('.')
629
except bzrlib.errors.FileExists:
630
raise BzrCommandError('Target directory "%s" already'
631
' exists.' % to_location)
632
except bzrlib.errors.NoSuchFile:
633
raise BzrCommandError('Parent of "%s" does not exist.' %
636
# preserve whatever source format we have.
637
dir = br_from.bzrdir.sprout(to_transport.base,
638
revision_id, basis_dir)
639
branch = dir.open_branch()
640
except bzrlib.errors.NoSuchRevision:
641
# TODO: jam 20060426 This only works on local paths
642
# and it would be nice if 'bzr branch' could
643
# work on a remote path
645
msg = "The branch %s has no revision %s." % (from_location, revision[0])
646
raise BzrCommandError(msg)
647
except bzrlib.errors.UnlistableBranch:
649
msg = "The branch %s cannot be used as a --basis" % (basis,)
650
raise BzrCommandError(msg)
652
branch.control_files.put_utf8('branch-name', name)
653
note('Branched %d revision(s).' % branch.revno())
658
class cmd_checkout(Command):
659
"""Create a new checkout of an existing branch.
661
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
662
the branch found in '.'. This is useful if you have removed the working tree
663
or if it was never created - i.e. if you pushed the branch to its current
666
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
667
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
669
To retrieve the branch as of a particular revision, supply the --revision
670
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
671
out of date [so you cannot commit] but it may be useful (i.e. to examine old
674
--basis is to speed up checking out from remote branches. When specified, it
675
uses the inventory and file contents from the basis branch in preference to the
676
branch being checked out. [Not implemented yet.]
678
takes_args = ['branch_location?', 'to_location?']
679
takes_options = ['revision', # , 'basis']
680
Option('lightweight',
681
help="perform a lightweight checkout. Lightweight "
682
"checkouts depend on access to the branch for "
683
"every operation. Normal checkouts can perform "
684
"common operations like diff and status without "
685
"such access, and also support local commits."
689
def run(self, branch_location=None, to_location=None, revision=None, basis=None,
693
elif len(revision) > 1:
694
raise BzrCommandError(
695
'bzr checkout --revision takes exactly 1 revision value')
696
if branch_location is None:
697
branch_location = bzrlib.osutils.getcwd()
698
to_location = branch_location
699
source = Branch.open(branch_location)
700
if len(revision) == 1 and revision[0] is not None:
701
revision_id = revision[0].in_history(source)[1]
704
if to_location is None:
705
to_location = os.path.basename(branch_location.rstrip("/\\"))
706
# if the source and to_location are the same,
707
# and there is no working tree,
708
# then reconstitute a branch
709
if (bzrlib.osutils.abspath(to_location) ==
710
bzrlib.osutils.abspath(branch_location)):
712
source.bzrdir.open_workingtree()
713
except errors.NoWorkingTree:
714
source.bzrdir.create_workingtree()
717
os.mkdir(to_location)
719
if e.errno == errno.EEXIST:
720
raise BzrCommandError('Target directory "%s" already'
721
' exists.' % to_location)
722
if e.errno == errno.ENOENT:
723
raise BzrCommandError('Parent of "%s" does not exist.' %
727
old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
728
bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
731
checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
732
bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
734
checkout_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience(
735
to_location, force_new_tree=False)
736
checkout = checkout_branch.bzrdir
737
checkout_branch.bind(source)
738
if revision_id is not None:
739
rh = checkout_branch.revision_history()
740
checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
741
checkout.create_workingtree(revision_id)
743
bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
746
class cmd_renames(Command):
747
"""Show list of renamed files.
749
# TODO: Option to show renames between two historical versions.
751
# TODO: Only show renames under dir, rather than in the whole branch.
752
takes_args = ['dir?']
755
def run(self, dir=u'.'):
756
tree = WorkingTree.open_containing(dir)[0]
757
old_inv = tree.basis_tree().inventory
758
new_inv = tree.read_working_inventory()
760
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
762
for old_name, new_name in renames:
763
self.outf.write("%s => %s\n" % (old_name, new_name))
766
class cmd_update(Command):
767
"""Update a tree to have the latest code committed to its branch.
769
This will perform a merge into the working tree, and may generate
770
conflicts. If you have any local changes, you will still
771
need to commit them after the update for the update to be complete.
773
If you want to discard your local changes, you can just do a
774
'bzr revert' instead of 'bzr commit' after the update.
776
takes_args = ['dir?']
778
def run(self, dir='.'):
779
tree = WorkingTree.open_containing(dir)[0]
782
if tree.last_revision() == tree.branch.last_revision():
783
# may be up to date, check master too.
784
master = tree.branch.get_master_branch()
785
if master is None or master.last_revision == tree.last_revision():
786
note("Tree is up to date.")
788
conflicts = tree.update()
789
note('Updated to revision %d.' %
790
(tree.branch.revision_id_to_revno(tree.last_revision()),))
799
class cmd_info(Command):
800
"""Show statistical information about a branch."""
801
takes_args = ['branch?']
802
takes_options = ['verbose']
805
def run(self, branch=None, verbose=False):
807
bzrlib.info.show_bzrdir_info(bzrdir.BzrDir.open_containing(branch)[0],
811
class cmd_remove(Command):
812
"""Make a file unversioned.
814
This makes bzr stop tracking changes to a versioned file. It does
815
not delete the working copy.
817
takes_args = ['file+']
818
takes_options = ['verbose']
821
def run(self, file_list, verbose=False):
822
tree, file_list = tree_files(file_list)
823
tree.remove(file_list, verbose=verbose)
826
class cmd_file_id(Command):
827
"""Print file_id of a particular file or directory.
829
The file_id is assigned when the file is first added and remains the
830
same through all revisions where the file exists, even when it is
834
takes_args = ['filename']
837
def run(self, filename):
838
tree, relpath = WorkingTree.open_containing(filename)
839
i = tree.inventory.path2id(relpath)
841
raise BzrError("%r is not a versioned file" % filename)
844
self.outf.write('\n')
847
class cmd_file_path(Command):
848
"""Print path of file_ids to a file or directory.
850
This prints one line for each directory down to the target,
851
starting at the branch root.
854
takes_args = ['filename']
857
def run(self, filename):
858
tree, relpath = WorkingTree.open_containing(filename)
860
fid = inv.path2id(relpath)
862
raise BzrError("%r is not a versioned file" % filename)
863
for fip in inv.get_idpath(fid):
865
self.outf.write('\n')
868
class cmd_reconcile(Command):
869
"""Reconcile bzr metadata in a branch.
871
This can correct data mismatches that may have been caused by
872
previous ghost operations or bzr upgrades. You should only
873
need to run this command if 'bzr check' or a bzr developer
874
advises you to run it.
876
If a second branch is provided, cross-branch reconciliation is
877
also attempted, which will check that data like the tree root
878
id which was not present in very early bzr versions is represented
879
correctly in both branches.
881
At the same time it is run it may recompress data resulting in
882
a potential saving in disk space or performance gain.
884
The branch *MUST* be on a listable system such as local disk or sftp.
886
takes_args = ['branch?']
888
def run(self, branch="."):
889
from bzrlib.reconcile import reconcile
890
dir = bzrlib.bzrdir.BzrDir.open(branch)
894
class cmd_revision_history(Command):
895
"""Display list of revision ids on this branch."""
900
branch = WorkingTree.open_containing(u'.')[0].branch
901
for patchid in branch.revision_history():
902
self.outf.write(patchid)
903
self.outf.write('\n')
906
class cmd_ancestry(Command):
907
"""List all revisions merged into this branch."""
912
tree = WorkingTree.open_containing(u'.')[0]
914
# FIXME. should be tree.last_revision
915
for revision_id in b.repository.get_ancestry(b.last_revision()):
916
if revision_id is None:
918
self.outf.write(revision_id)
919
self.outf.write('\n')
922
class cmd_init(Command):
923
"""Make a directory into a versioned branch.
925
Use this to create an empty branch, or before importing an
928
If there is a repository in a parent directory of the location, then
929
the history of the branch will be stored in the repository. Otherwise
930
init creates a standalone branch which carries its own history in
933
If there is already a branch at the location but it has no working tree,
934
the tree can be populated with 'bzr checkout'.
936
Recipe for importing a tree of files:
941
bzr commit -m 'imported project'
943
takes_args = ['location?']
946
help='Create a specific format rather than the'
947
' current default format. Currently this '
948
' option only accepts "metadir"',
949
type=get_format_type),
951
def run(self, location=None, format=None):
952
from bzrlib.branch import Branch
956
# The path has to exist to initialize a
957
# branch inside of it.
958
# Just using os.mkdir, since I don't
959
# believe that we want to create a bunch of
960
# locations if the user supplies an extended path
961
if not os.path.exists(location):
964
existing_bzrdir = bzrdir.BzrDir.open(location)
965
except NotBranchError:
966
# really a NotBzrDir error...
967
bzrdir.BzrDir.create_branch_convenience(location, format=format)
969
if existing_bzrdir.has_branch():
970
if existing_bzrdir.has_workingtree():
971
raise errors.AlreadyBranchError(location)
973
raise errors.BranchExistsWithoutWorkingTree(location)
975
existing_bzrdir.create_branch()
976
existing_bzrdir.create_workingtree()
979
class cmd_init_repository(Command):
980
"""Create a shared repository to hold branches.
982
New branches created under the repository directory will store their revisions
983
in the repository, not in the branch directory, if the branch format supports
989
bzr checkout --lightweight repo/trunk trunk-checkout
993
takes_args = ["location"]
994
takes_options = [Option('format',
995
help='Use a specific format rather than the'
996
' current default format. Currently this'
997
' option accepts "weave", "metadir" and "knit"',
998
type=get_format_type),
1000
help='Allows branches in repository to have'
1002
aliases = ["init-repo"]
1003
def run(self, location, format=None, trees=False):
1004
from bzrlib.bzrdir import BzrDirMetaFormat1
1005
from bzrlib.transport import get_transport
1007
format = BzrDirMetaFormat1()
1008
transport = get_transport(location)
1009
if not transport.has('.'):
1011
newdir = format.initialize_on_transport(transport)
1012
repo = newdir.create_repository(shared=True)
1013
repo.set_make_working_trees(trees)
1016
class cmd_diff(Command):
1017
"""Show differences in working tree.
1019
If files are listed, only the changes in those files are listed.
1020
Otherwise, all changes for the tree are listed.
1027
# TODO: Allow diff across branches.
1028
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1029
# or a graphical diff.
1031
# TODO: Python difflib is not exactly the same as unidiff; should
1032
# either fix it up or prefer to use an external diff.
1034
# TODO: If a directory is given, diff everything under that.
1036
# TODO: Selected-file diff is inefficient and doesn't show you
1039
# TODO: This probably handles non-Unix newlines poorly.
1041
takes_args = ['file*']
1042
takes_options = ['revision', 'diff-options']
1043
aliases = ['di', 'dif']
1044
encoding_type = 'exact'
1047
def run(self, revision=None, file_list=None, diff_options=None):
1048
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1050
tree1, file_list = internal_tree_files(file_list)
1054
except FileInWrongBranch:
1055
if len(file_list) != 2:
1056
raise BzrCommandError("Files are in different branches")
1058
tree1, file1 = WorkingTree.open_containing(file_list[0])
1059
tree2, file2 = WorkingTree.open_containing(file_list[1])
1060
if file1 != "" or file2 != "":
1061
# FIXME diff those two files. rbc 20051123
1062
raise BzrCommandError("Files are in different branches")
1064
if revision is not None:
1065
if tree2 is not None:
1066
raise BzrCommandError("Can't specify -r with two branches")
1067
if (len(revision) == 1) or (revision[1].spec is None):
1068
return diff_cmd_helper(tree1, file_list, diff_options,
1070
elif len(revision) == 2:
1071
return diff_cmd_helper(tree1, file_list, diff_options,
1072
revision[0], revision[1])
1074
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1076
if tree2 is not None:
1077
return show_diff_trees(tree1, tree2, sys.stdout,
1078
specific_files=file_list,
1079
external_diff_options=diff_options)
1081
return diff_cmd_helper(tree1, file_list, diff_options)
1084
class cmd_deleted(Command):
1085
"""List files deleted in the working tree.
1087
# TODO: Show files deleted since a previous revision, or
1088
# between two revisions.
1089
# TODO: Much more efficient way to do this: read in new
1090
# directories with readdir, rather than stating each one. Same
1091
# level of effort but possibly much less IO. (Or possibly not,
1092
# if the directories are very large...)
1093
takes_options = ['show-ids']
1096
def run(self, show_ids=False):
1097
tree = WorkingTree.open_containing(u'.')[0]
1098
old = tree.basis_tree()
1099
for path, ie in old.inventory.iter_entries():
1100
if not tree.has_id(ie.file_id):
1101
self.outf.write(path)
1103
self.outf.write(' ')
1104
self.outf.write(ie.file_id)
1105
self.outf.write('\n')
1108
class cmd_modified(Command):
1109
"""List files modified in working tree."""
1113
from bzrlib.delta import compare_trees
1115
tree = WorkingTree.open_containing(u'.')[0]
1116
td = compare_trees(tree.basis_tree(), tree)
1118
for path, id, kind, text_modified, meta_modified in td.modified:
1119
self.outf.write(path)
1120
self.outf.write('\n')
1123
class cmd_added(Command):
1124
"""List files added in working tree."""
1128
wt = WorkingTree.open_containing(u'.')[0]
1129
basis_inv = wt.basis_tree().inventory
1132
if file_id in basis_inv:
1134
path = inv.id2path(file_id)
1135
if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
1137
self.outf.write(path)
1138
self.outf.write('\n')
1141
class cmd_root(Command):
1142
"""Show the tree root directory.
1144
The root is the nearest enclosing directory with a .bzr control
1146
takes_args = ['filename?']
1148
def run(self, filename=None):
1149
"""Print the branch root."""
1150
tree = WorkingTree.open_containing(filename)[0]
1151
self.outf.write(tree.basedir)
1152
self.outf.write('\n')
1155
class cmd_log(Command):
1156
"""Show log of a branch, file, or directory.
1158
By default show the log of the branch containing the working directory.
1160
To request a range of logs, you can use the command -r begin..end
1161
-r revision requests a specific revision, -r ..end or -r begin.. are
1167
bzr log -r -10.. http://server/branch
1170
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1172
takes_args = ['location?']
1173
takes_options = [Option('forward',
1174
help='show from oldest to newest'),
1177
help='show files changed in each revision'),
1178
'show-ids', 'revision',
1182
help='show revisions whose message matches this regexp',
1186
encoding_type = 'replace'
1189
def run(self, location=None, timezone='original',
1199
from bzrlib.log import log_formatter, show_log
1200
assert message is None or isinstance(message, basestring), \
1201
"invalid message argument %r" % message
1202
direction = (forward and 'forward') or 'reverse'
1207
# find the file id to log:
1209
dir, fp = bzrdir.BzrDir.open_containing(location)
1210
b = dir.open_branch()
1214
inv = dir.open_workingtree().inventory
1215
except (errors.NotBranchError, errors.NotLocalUrl):
1216
# either no tree, or is remote.
1217
inv = b.basis_tree().inventory
1218
file_id = inv.path2id(fp)
1221
# FIXME ? log the current subdir only RBC 20060203
1222
dir, relpath = bzrdir.BzrDir.open_containing('.')
1223
b = dir.open_branch()
1225
if revision is None:
1228
elif len(revision) == 1:
1229
rev1 = rev2 = revision[0].in_history(b).revno
1230
elif len(revision) == 2:
1231
if revision[0].spec is None:
1232
# missing begin-range means first revision
1235
rev1 = revision[0].in_history(b).revno
1237
if revision[1].spec is None:
1238
# missing end-range means last known revision
1241
rev2 = revision[1].in_history(b).revno
1243
raise BzrCommandError('bzr log --revision takes one or two values.')
1245
# By this point, the revision numbers are converted to the +ve
1246
# form if they were supplied in the -ve form, so we can do
1247
# this comparison in relative safety
1249
(rev2, rev1) = (rev1, rev2)
1251
if (log_format == None):
1252
default = bzrlib.config.BranchConfig(b).log_format()
1253
log_format = get_log_format(long=long, short=short, line=line, default=default)
1254
lf = log_formatter(log_format,
1257
show_timezone=timezone)
1263
direction=direction,
1264
start_revision=rev1,
1269
def get_log_format(long=False, short=False, line=False, default='long'):
1270
log_format = default
1274
log_format = 'short'
1280
class cmd_touching_revisions(Command):
1281
"""Return revision-ids which affected a particular file.
1283
A more user-friendly interface is "bzr log FILE"."""
1285
takes_args = ["filename"]
1286
encoding_type = 'replace'
1289
def run(self, filename):
1290
tree, relpath = WorkingTree.open_containing(filename)
1292
inv = tree.read_working_inventory()
1293
file_id = inv.path2id(relpath)
1294
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1295
self.outf.write("%6d %s\n" % (revno, what))
1298
class cmd_ls(Command):
1299
"""List files in a tree.
1301
# TODO: Take a revision or remote path and list that tree instead.
1303
takes_options = ['verbose', 'revision',
1304
Option('non-recursive',
1305
help='don\'t recurse into sub-directories'),
1307
help='Print all paths from the root of the branch.'),
1308
Option('unknown', help='Print unknown files'),
1309
Option('versioned', help='Print versioned files'),
1310
Option('ignored', help='Print ignored files'),
1312
Option('null', help='Null separate the files'),
1315
def run(self, revision=None, verbose=False,
1316
non_recursive=False, from_root=False,
1317
unknown=False, versioned=False, ignored=False,
1320
if verbose and null:
1321
raise BzrCommandError('Cannot set both --verbose and --null')
1322
all = not (unknown or versioned or ignored)
1324
selection = {'I':ignored, '?':unknown, 'V':versioned}
1326
tree, relpath = WorkingTree.open_containing(u'.')
1331
if revision is not None:
1332
tree = tree.branch.repository.revision_tree(
1333
revision[0].in_history(tree.branch).rev_id)
1335
for fp, fc, kind, fid, entry in tree.list_files():
1336
if fp.startswith(relpath):
1337
fp = fp[len(relpath):]
1338
if non_recursive and '/' in fp:
1340
if not all and not selection[fc]:
1343
kindch = entry.kind_character()
1344
self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1347
self.outf.write('\0')
1351
self.outf.write('\n')
1354
class cmd_unknowns(Command):
1355
"""List unknown files."""
1358
from bzrlib.osutils import quotefn
1359
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1360
self.outf.write(quotefn(f))
1361
self.outf.write('\n')
1364
class cmd_ignore(Command):
1365
"""Ignore a command or pattern.
1367
To remove patterns from the ignore list, edit the .bzrignore file.
1369
If the pattern contains a slash, it is compared to the whole path
1370
from the branch root. Otherwise, it is compared to only the last
1371
component of the path. To match a file only in the root directory,
1374
Ignore patterns are case-insensitive on case-insensitive systems.
1376
Note: wildcards must be quoted from the shell on Unix.
1379
bzr ignore ./Makefile
1380
bzr ignore '*.class'
1382
# TODO: Complain if the filename is absolute
1383
takes_args = ['name_pattern']
1385
def run(self, name_pattern):
1386
from bzrlib.atomicfile import AtomicFile
1389
tree, relpath = WorkingTree.open_containing(u'.')
1390
ifn = tree.abspath('.bzrignore')
1392
if os.path.exists(ifn):
1395
igns = f.read().decode('utf-8')
1401
# TODO: If the file already uses crlf-style termination, maybe
1402
# we should use that for the newly added lines?
1404
if igns and igns[-1] != '\n':
1406
igns += name_pattern + '\n'
1409
f = AtomicFile(ifn, 'wt')
1410
f.write(igns.encode('utf-8'))
1415
inv = tree.inventory
1416
if inv.path2id('.bzrignore'):
1417
mutter('.bzrignore is already versioned')
1419
mutter('need to make new .bzrignore file versioned')
1420
tree.add(['.bzrignore'])
1423
class cmd_ignored(Command):
1424
"""List ignored files and the patterns that matched them.
1426
See also: bzr ignore"""
1429
tree = WorkingTree.open_containing(u'.')[0]
1430
for path, file_class, kind, file_id, entry in tree.list_files():
1431
if file_class != 'I':
1433
## XXX: Slightly inefficient since this was already calculated
1434
pat = tree.is_ignored(path)
1435
print '%-50s %s' % (path, pat)
1438
class cmd_lookup_revision(Command):
1439
"""Lookup the revision-id from a revision-number
1442
bzr lookup-revision 33
1445
takes_args = ['revno']
1448
def run(self, revno):
1452
raise BzrCommandError("not a valid revision-number: %r" % revno)
1454
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1457
class cmd_export(Command):
1458
"""Export past revision to destination directory.
1460
If no revision is specified this exports the last committed revision.
1462
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1463
given, try to find the format with the extension. If no extension
1464
is found exports to a directory (equivalent to --format=dir).
1466
Root may be the top directory for tar, tgz and tbz2 formats. If none
1467
is given, the top directory will be the root name of the file.
1469
Note: export of tree with non-ascii filenames to zip is not supported.
1471
Supported formats Autodetected by extension
1472
----------------- -------------------------
1475
tbz2 .tar.bz2, .tbz2
1479
takes_args = ['dest']
1480
takes_options = ['revision', 'format', 'root']
1481
def run(self, dest, revision=None, format=None, root=None):
1483
from bzrlib.export import export
1484
tree = WorkingTree.open_containing(u'.')[0]
1486
if revision is None:
1487
# should be tree.last_revision FIXME
1488
rev_id = b.last_revision()
1490
if len(revision) != 1:
1491
raise BzrError('bzr export --revision takes exactly 1 argument')
1492
rev_id = revision[0].in_history(b).rev_id
1493
t = b.repository.revision_tree(rev_id)
1495
export(t, dest, format, root)
1496
except errors.NoSuchExportFormat, e:
1497
raise BzrCommandError('Unsupported export format: %s' % e.format)
1500
class cmd_cat(Command):
1501
"""Write a file's text from a previous revision."""
1503
takes_options = ['revision']
1504
takes_args = ['filename']
1507
def run(self, filename, revision=None):
1508
if revision is not None and len(revision) != 1:
1509
raise BzrCommandError("bzr cat --revision takes exactly one number")
1512
tree, relpath = WorkingTree.open_containing(filename)
1514
except NotBranchError:
1518
b, relpath = Branch.open_containing(filename)
1519
if revision is None:
1520
revision_id = b.last_revision()
1522
revision_id = revision[0].in_history(b).rev_id
1523
b.print_file(relpath, revision_id)
1526
class cmd_local_time_offset(Command):
1527
"""Show the offset in seconds from GMT to local time."""
1531
print bzrlib.osutils.local_time_offset()
1535
class cmd_commit(Command):
1536
"""Commit changes into a new revision.
1538
If no arguments are given, the entire tree is committed.
1540
If selected files are specified, only changes to those files are
1541
committed. If a directory is specified then the directory and everything
1542
within it is committed.
1544
A selected-file commit may fail in some cases where the committed
1545
tree would be invalid, such as trying to commit a file in a
1546
newly-added directory that is not itself committed.
1548
# TODO: Run hooks on tree to-be-committed, and after commit.
1550
# TODO: Strict commit that fails if there are deleted files.
1551
# (what does "deleted files" mean ??)
1553
# TODO: Give better message for -s, --summary, used by tla people
1555
# XXX: verbose currently does nothing
1557
takes_args = ['selected*']
1558
takes_options = ['message', 'verbose',
1560
help='commit even if nothing has changed'),
1561
Option('file', type=str,
1563
help='file containing commit message'),
1565
help="refuse to commit if there are unknown "
1566
"files in the working tree."),
1568
help="perform a local only commit in a bound "
1569
"branch. Such commits are not pushed to "
1570
"the master branch until a normal commit "
1574
aliases = ['ci', 'checkin']
1576
def run(self, message=None, file=None, verbose=True, selected_list=None,
1577
unchanged=False, strict=False, local=False):
1578
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
1579
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1581
from bzrlib.msgeditor import edit_commit_message, \
1582
make_commit_message_template
1583
from tempfile import TemporaryFile
1585
# TODO: Need a blackbox test for invoking the external editor; may be
1586
# slightly problematic to run this cross-platform.
1588
# TODO: do more checks that the commit will succeed before
1589
# spending the user's valuable time typing a commit message.
1591
# TODO: if the commit *does* happen to fail, then save the commit
1592
# message to a temporary file where it can be recovered
1593
tree, selected_list = tree_files(selected_list)
1594
if local and not tree.branch.get_bound_location():
1595
raise errors.LocalRequiresBoundBranch()
1596
if message is None and not file:
1597
template = make_commit_message_template(tree, selected_list)
1598
message = edit_commit_message(template)
1600
raise BzrCommandError("please specify a commit message"
1601
" with either --message or --file")
1602
elif message and file:
1603
raise BzrCommandError("please specify either --message or --file")
1606
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1609
raise BzrCommandError("empty commit message specified")
1612
reporter = ReportCommitToLog()
1614
reporter = NullCommitReporter()
1617
tree.commit(message, specific_files=selected_list,
1618
allow_pointless=unchanged, strict=strict, local=local,
1620
except PointlessCommit:
1621
# FIXME: This should really happen before the file is read in;
1622
# perhaps prepare the commit; get the message; then actually commit
1623
raise BzrCommandError("no changes to commit",
1624
["use --unchanged to commit anyhow"])
1625
except ConflictsInTree:
1626
raise BzrCommandError("Conflicts detected in working tree. "
1627
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1628
except StrictCommitFailed:
1629
raise BzrCommandError("Commit refused because there are unknown "
1630
"files in the working tree.")
1631
except errors.BoundBranchOutOfDate, e:
1632
raise BzrCommandError(str(e)
1633
+ ' Either unbind, update, or'
1634
' pass --local to commit.')
1637
class cmd_check(Command):
1638
"""Validate consistency of branch history.
1640
This command checks various invariants about the branch storage to
1641
detect data corruption or bzr bugs.
1643
takes_args = ['branch?']
1644
takes_options = ['verbose']
1646
def run(self, branch=None, verbose=False):
1647
from bzrlib.check import check
1649
tree = WorkingTree.open_containing()[0]
1650
branch = tree.branch
1652
branch = Branch.open(branch)
1653
check(branch, verbose)
1656
class cmd_scan_cache(Command):
1659
from bzrlib.hashcache import HashCache
1665
print '%6d stats' % c.stat_count
1666
print '%6d in hashcache' % len(c._cache)
1667
print '%6d files removed from cache' % c.removed_count
1668
print '%6d hashes updated' % c.update_count
1669
print '%6d files changed too recently to cache' % c.danger_count
1675
class cmd_upgrade(Command):
1676
"""Upgrade branch storage to current format.
1678
The check command or bzr developers may sometimes advise you to run
1679
this command. When the default format has changed you may also be warned
1680
during other operations to upgrade.
1682
takes_args = ['url?']
1685
help='Upgrade to a specific format rather than the'
1686
' current default format. Currently this'
1687
' option accepts "weave", "metadir" and'
1689
type=get_format_type),
1693
def run(self, url='.', format=None):
1694
from bzrlib.upgrade import upgrade
1695
upgrade(url, format)
1698
class cmd_whoami(Command):
1699
"""Show bzr user id."""
1700
takes_options = ['email']
1703
def run(self, email=False):
1705
b = WorkingTree.open_containing(u'.')[0].branch
1706
config = bzrlib.config.BranchConfig(b)
1707
except NotBranchError:
1708
config = bzrlib.config.GlobalConfig()
1711
print config.user_email()
1713
print config.username()
1716
class cmd_nick(Command):
1717
"""Print or set the branch nickname.
1719
If unset, the tree root directory name is used as the nickname
1720
To print the current nickname, execute with no argument.
1722
takes_args = ['nickname?']
1723
def run(self, nickname=None):
1724
branch = Branch.open_containing(u'.')[0]
1725
if nickname is None:
1726
self.printme(branch)
1728
branch.nick = nickname
1731
def printme(self, branch):
1735
class cmd_selftest(Command):
1736
"""Run internal test suite.
1738
This creates temporary test directories in the working directory,
1739
but not existing data is affected. These directories are deleted
1740
if the tests pass, or left behind to help in debugging if they
1741
fail and --keep-output is specified.
1743
If arguments are given, they are regular expressions that say
1744
which tests should run.
1746
If the global option '--no-plugins' is given, plugins are not loaded
1747
before running the selftests. This has two effects: features provided or
1748
modified by plugins will not be tested, and tests provided by plugins will
1753
bzr --no-plugins selftest -v
1755
# TODO: --list should give a list of all available tests
1757
# NB: this is used from the class without creating an instance, which is
1758
# why it does not have a self parameter.
1759
def get_transport_type(typestring):
1760
"""Parse and return a transport specifier."""
1761
if typestring == "sftp":
1762
from bzrlib.transport.sftp import SFTPAbsoluteServer
1763
return SFTPAbsoluteServer
1764
if typestring == "memory":
1765
from bzrlib.transport.memory import MemoryServer
1767
if typestring == "fakenfs":
1768
from bzrlib.transport.fakenfs import FakeNFSServer
1769
return FakeNFSServer
1770
msg = "No known transport type %s. Supported types are: sftp\n" %\
1772
raise BzrCommandError(msg)
1775
takes_args = ['testspecs*']
1776
takes_options = ['verbose',
1777
Option('one', help='stop when one test fails'),
1778
Option('keep-output',
1779
help='keep output directories when tests fail'),
1781
help='Use a different transport by default '
1782
'throughout the test suite.',
1783
type=get_transport_type),
1786
def run(self, testspecs_list=None, verbose=False, one=False,
1787
keep_output=False, transport=None):
1789
from bzrlib.tests import selftest
1790
# we don't want progress meters from the tests to go to the
1791
# real output; and we don't want log messages cluttering up
1793
save_ui = bzrlib.ui.ui_factory
1794
bzrlib.trace.info('running tests...')
1796
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1797
if testspecs_list is not None:
1798
pattern = '|'.join(testspecs_list)
1801
result = selftest(verbose=verbose,
1803
stop_on_failure=one,
1804
keep_output=keep_output,
1805
transport=transport)
1807
bzrlib.trace.info('tests passed')
1809
bzrlib.trace.info('tests failed')
1810
return int(not result)
1812
bzrlib.ui.ui_factory = save_ui
1815
def _get_bzr_branch():
1816
"""If bzr is run from a branch, return Branch or None"""
1817
import bzrlib.errors
1818
from bzrlib.branch import Branch
1819
from bzrlib.osutils import abspath
1820
from os.path import dirname
1823
branch = Branch.open(dirname(abspath(dirname(__file__))))
1825
except bzrlib.errors.BzrError:
1830
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1831
# is bzrlib itself in a branch?
1832
branch = _get_bzr_branch()
1834
rh = branch.revision_history()
1836
print " bzr checkout, revision %d" % (revno,)
1837
print " nick: %s" % (branch.nick,)
1839
print " revid: %s" % (rh[-1],)
1840
print bzrlib.__copyright__
1841
print "http://bazaar-ng.org/"
1843
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1844
print "you may use, modify and redistribute it under the terms of the GNU"
1845
print "General Public License version 2 or later."
1848
class cmd_version(Command):
1849
"""Show version of bzr."""
1854
class cmd_rocks(Command):
1855
"""Statement of optimism."""
1859
print "it sure does!"
1862
class cmd_find_merge_base(Command):
1863
"""Find and print a base revision for merging two branches.
1865
# TODO: Options to specify revisions on either side, as if
1866
# merging only part of the history.
1867
takes_args = ['branch', 'other']
1871
def run(self, branch, other):
1872
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1874
branch1 = Branch.open_containing(branch)[0]
1875
branch2 = Branch.open_containing(other)[0]
1877
history_1 = branch1.revision_history()
1878
history_2 = branch2.revision_history()
1880
last1 = branch1.last_revision()
1881
last2 = branch2.last_revision()
1883
source = MultipleRevisionSources(branch1.repository,
1886
base_rev_id = common_ancestor(last1, last2, source)
1888
print 'merge base is revision %s' % base_rev_id
1892
if base_revno is None:
1893
raise bzrlib.errors.UnrelatedBranches()
1895
print ' r%-6d in %s' % (base_revno, branch)
1897
other_revno = branch2.revision_id_to_revno(base_revid)
1899
print ' r%-6d in %s' % (other_revno, other)
1903
class cmd_merge(Command):
1904
"""Perform a three-way merge.
1906
The branch is the branch you will merge from. By default, it will
1907
merge the latest revision. If you specify a revision, that
1908
revision will be merged. If you specify two revisions, the first
1909
will be used as a BASE, and the second one as OTHER. Revision
1910
numbers are always relative to the specified branch.
1912
By default, bzr will try to merge in all new work from the other
1913
branch, automatically determining an appropriate base. If this
1914
fails, you may need to give an explicit base.
1916
Merge will do its best to combine the changes in two branches, but there
1917
are some kinds of problems only a human can fix. When it encounters those,
1918
it will mark a conflict. A conflict means that you need to fix something,
1919
before you should commit.
1921
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
1923
If there is no default branch set, the first merge will set it. After
1924
that, you can omit the branch to use the default. To change the
1925
default, use --remember.
1929
To merge the latest revision from bzr.dev
1930
bzr merge ../bzr.dev
1932
To merge changes up to and including revision 82 from bzr.dev
1933
bzr merge -r 82 ../bzr.dev
1935
To merge the changes introduced by 82, without previous changes:
1936
bzr merge -r 81..82 ../bzr.dev
1938
merge refuses to run if there are any uncommitted changes, unless
1941
takes_args = ['branch?']
1942
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
1943
Option('show-base', help="Show base revision text in "
1946
def run(self, branch=None, revision=None, force=False, merge_type=None,
1947
show_base=False, reprocess=False, remember=False):
1948
if merge_type is None:
1949
merge_type = Merge3Merger
1951
tree = WorkingTree.open_containing(u'.')[0]
1952
stored_loc = tree.branch.get_parent()
1954
if stored_loc is None:
1955
raise BzrCommandError("No merge branch known or specified.")
1957
print (u"Using saved branch: %s"
1958
% urlutils.unescape_for_display(stored_loc))
1961
if revision is None or len(revision) < 1:
1963
other = [branch, -1]
1964
other_branch, path = Branch.open_containing(branch)
1966
if len(revision) == 1:
1968
other_branch, path = Branch.open_containing(branch)
1969
revno = revision[0].in_history(other_branch).revno
1970
other = [branch, revno]
1972
assert len(revision) == 2
1973
if None in revision:
1974
raise BzrCommandError(
1975
"Merge doesn't permit that revision specifier.")
1976
other_branch, path = Branch.open_containing(branch)
1978
base = [branch, revision[0].in_history(other_branch).revno]
1979
other = [branch, revision[1].in_history(other_branch).revno]
1981
if tree.branch.get_parent() is None or remember:
1982
tree.branch.set_parent(other_branch.base)
1985
interesting_files = [path]
1987
interesting_files = None
1988
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1991
conflict_count = merge(other, base, check_clean=(not force),
1992
merge_type=merge_type,
1993
reprocess=reprocess,
1994
show_base=show_base,
1995
pb=pb, file_list=interesting_files)
1998
if conflict_count != 0:
2002
except bzrlib.errors.AmbiguousBase, e:
2003
m = ("sorry, bzr can't determine the right merge base yet\n"
2004
"candidates are:\n "
2005
+ "\n ".join(e.bases)
2007
"please specify an explicit base with -r,\n"
2008
"and (if you want) report this to the bzr developers\n")
2012
class cmd_remerge(Command):
2015
takes_args = ['file*']
2016
takes_options = ['merge-type', 'reprocess',
2017
Option('show-base', help="Show base revision text in "
2020
def run(self, file_list=None, merge_type=None, show_base=False,
2022
from bzrlib.merge import merge_inner, transform_tree
2023
if merge_type is None:
2024
merge_type = Merge3Merger
2025
tree, file_list = tree_files(file_list)
2028
pending_merges = tree.pending_merges()
2029
if len(pending_merges) != 1:
2030
raise BzrCommandError("Sorry, remerge only works after normal"
2031
+ " merges. Not cherrypicking or"
2033
repository = tree.branch.repository
2034
base_revision = common_ancestor(tree.branch.last_revision(),
2035
pending_merges[0], repository)
2036
base_tree = repository.revision_tree(base_revision)
2037
other_tree = repository.revision_tree(pending_merges[0])
2038
interesting_ids = None
2039
if file_list is not None:
2040
interesting_ids = set()
2041
for filename in file_list:
2042
file_id = tree.path2id(filename)
2044
raise NotVersionedError(filename)
2045
interesting_ids.add(file_id)
2046
if tree.kind(file_id) != "directory":
2049
for name, ie in tree.inventory.iter_entries(file_id):
2050
interesting_ids.add(ie.file_id)
2051
transform_tree(tree, tree.basis_tree(), interesting_ids)
2052
if file_list is None:
2053
restore_files = list(tree.iter_conflicts())
2055
restore_files = file_list
2056
for filename in restore_files:
2058
restore(tree.abspath(filename))
2059
except NotConflicted:
2061
conflicts = merge_inner(tree.branch, other_tree, base_tree,
2063
interesting_ids = interesting_ids,
2064
other_rev_id=pending_merges[0],
2065
merge_type=merge_type,
2066
show_base=show_base,
2067
reprocess=reprocess)
2075
class cmd_revert(Command):
2076
"""Reverse all changes since the last commit.
2078
Only versioned files are affected. Specify filenames to revert only
2079
those files. By default, any files that are changed will be backed up
2080
first. Backup files have a '~' appended to their name.
2082
takes_options = ['revision', 'no-backup']
2083
takes_args = ['file*']
2084
aliases = ['merge-revert']
2086
def run(self, revision=None, no_backup=False, file_list=None):
2087
from bzrlib.commands import parse_spec
2088
if file_list is not None:
2089
if len(file_list) == 0:
2090
raise BzrCommandError("No files specified")
2094
tree, file_list = tree_files(file_list)
2095
if revision is None:
2096
# FIXME should be tree.last_revision
2097
rev_id = tree.last_revision()
2098
elif len(revision) != 1:
2099
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
2101
rev_id = revision[0].in_history(tree.branch).rev_id
2102
pb = bzrlib.ui.ui_factory.nested_progress_bar()
2104
tree.revert(file_list,
2105
tree.branch.repository.revision_tree(rev_id),
2111
class cmd_assert_fail(Command):
2112
"""Test reporting of assertion failures"""
2115
assert False, "always fails"
2118
class cmd_help(Command):
2119
"""Show help on a command or other topic.
2121
For a list of all available commands, say 'bzr help commands'."""
2122
takes_options = [Option('long', 'show help on all commands')]
2123
takes_args = ['topic?']
2124
aliases = ['?', '--help', '-?', '-h']
2127
def run(self, topic=None, long=False):
2129
if topic is None and long:
2134
class cmd_shell_complete(Command):
2135
"""Show appropriate completions for context.
2137
For a list of all available commands, say 'bzr shell-complete'."""
2138
takes_args = ['context?']
2143
def run(self, context=None):
2144
import shellcomplete
2145
shellcomplete.shellcomplete(context)
2148
class cmd_fetch(Command):
2149
"""Copy in history from another branch but don't merge it.
2151
This is an internal method used for pull and merge."""
2153
takes_args = ['from_branch', 'to_branch']
2154
def run(self, from_branch, to_branch):
2155
from bzrlib.fetch import Fetcher
2156
from bzrlib.branch import Branch
2157
from_b = Branch.open(from_branch)
2158
to_b = Branch.open(to_branch)
2159
Fetcher(to_b, from_b)
2162
class cmd_missing(Command):
2163
"""Show unmerged/unpulled revisions between two branches.
2165
OTHER_BRANCH may be local or remote."""
2166
takes_args = ['other_branch?']
2167
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2169
'Display changes in the local branch only'),
2170
Option('theirs-only',
2171
'Display changes in the remote branch only'),
2180
def run(self, other_branch=None, reverse=False, mine_only=False,
2181
theirs_only=False, log_format=None, long=False, short=False, line=False,
2182
show_ids=False, verbose=False):
2183
from bzrlib.missing import find_unmerged, iter_log_data
2184
from bzrlib.log import log_formatter
2185
local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
2186
parent = local_branch.get_parent()
2187
if other_branch is None:
2188
other_branch = parent
2189
if other_branch is None:
2190
raise BzrCommandError("No missing location known or specified.")
2191
print "Using last location: " + local_branch.get_parent()
2192
remote_branch = bzrlib.branch.Branch.open(other_branch)
2193
if remote_branch.base == local_branch.base:
2194
remote_branch = local_branch
2195
local_branch.lock_read()
2197
remote_branch.lock_read()
2199
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2200
if (log_format == None):
2201
default = bzrlib.config.BranchConfig(local_branch).log_format()
2202
log_format = get_log_format(long=long, short=short, line=line, default=default)
2203
lf = log_formatter(log_format, sys.stdout,
2205
show_timezone='original')
2206
if reverse is False:
2207
local_extra.reverse()
2208
remote_extra.reverse()
2209
if local_extra and not theirs_only:
2210
print "You have %d extra revision(s):" % len(local_extra)
2211
for data in iter_log_data(local_extra, local_branch.repository,
2214
printed_local = True
2216
printed_local = False
2217
if remote_extra and not mine_only:
2218
if printed_local is True:
2220
print "You are missing %d revision(s):" % len(remote_extra)
2221
for data in iter_log_data(remote_extra, remote_branch.repository,
2224
if not remote_extra and not local_extra:
2226
print "Branches are up to date."
2230
remote_branch.unlock()
2232
local_branch.unlock()
2233
if not status_code and parent is None and other_branch is not None:
2234
local_branch.lock_write()
2236
# handle race conditions - a parent might be set while we run.
2237
if local_branch.get_parent() is None:
2238
local_branch.set_parent(remote_branch.base)
2240
local_branch.unlock()
2244
class cmd_plugins(Command):
2249
import bzrlib.plugin
2250
from inspect import getdoc
2251
for name, plugin in bzrlib.plugin.all_plugins().items():
2252
if hasattr(plugin, '__path__'):
2253
print plugin.__path__[0]
2254
elif hasattr(plugin, '__file__'):
2255
print plugin.__file__
2261
print '\t', d.split('\n')[0]
2264
class cmd_testament(Command):
2265
"""Show testament (signing-form) of a revision."""
2266
takes_options = ['revision', 'long']
2267
takes_args = ['branch?']
2269
def run(self, branch=u'.', revision=None, long=False):
2270
from bzrlib.testament import Testament
2271
b = WorkingTree.open_containing(branch)[0].branch
2274
if revision is None:
2275
rev_id = b.last_revision()
2277
rev_id = revision[0].in_history(b).rev_id
2278
t = Testament.from_revision(b.repository, rev_id)
2280
sys.stdout.writelines(t.as_text_lines())
2282
sys.stdout.write(t.as_short_text())
2287
class cmd_annotate(Command):
2288
"""Show the origin of each line in a file.
2290
This prints out the given file with an annotation on the left side
2291
indicating which revision, author and date introduced the change.
2293
If the origin is the same for a run of consecutive lines, it is
2294
shown only at the top, unless the --all option is given.
2296
# TODO: annotate directories; showing when each file was last changed
2297
# TODO: annotate a previous version of a file
2298
# TODO: if the working copy is modified, show annotations on that
2299
# with new uncommitted lines marked
2300
aliases = ['blame', 'praise']
2301
takes_args = ['filename']
2302
takes_options = [Option('all', help='show annotations on all lines'),
2303
Option('long', help='show date in annotations'),
2307
def run(self, filename, all=False, long=False):
2308
from bzrlib.annotate import annotate_file
2309
tree, relpath = WorkingTree.open_containing(filename)
2310
branch = tree.branch
2313
file_id = tree.inventory.path2id(relpath)
2314
tree = branch.repository.revision_tree(branch.last_revision())
2315
file_version = tree.inventory[file_id].revision
2316
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
2321
class cmd_re_sign(Command):
2322
"""Create a digital signature for an existing revision."""
2323
# TODO be able to replace existing ones.
2325
hidden = True # is this right ?
2326
takes_args = ['revision_id*']
2327
takes_options = ['revision']
2329
def run(self, revision_id_list=None, revision=None):
2330
import bzrlib.config as config
2331
import bzrlib.gpg as gpg
2332
if revision_id_list is not None and revision is not None:
2333
raise BzrCommandError('You can only supply one of revision_id or --revision')
2334
if revision_id_list is None and revision is None:
2335
raise BzrCommandError('You must supply either --revision or a revision_id')
2336
b = WorkingTree.open_containing(u'.')[0].branch
2337
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
2338
if revision_id_list is not None:
2339
for revision_id in revision_id_list:
2340
b.repository.sign_revision(revision_id, gpg_strategy)
2341
elif revision is not None:
2342
if len(revision) == 1:
2343
revno, rev_id = revision[0].in_history(b)
2344
b.repository.sign_revision(rev_id, gpg_strategy)
2345
elif len(revision) == 2:
2346
# are they both on rh- if so we can walk between them
2347
# might be nice to have a range helper for arbitrary
2348
# revision paths. hmm.
2349
from_revno, from_revid = revision[0].in_history(b)
2350
to_revno, to_revid = revision[1].in_history(b)
2351
if to_revid is None:
2352
to_revno = b.revno()
2353
if from_revno is None or to_revno is None:
2354
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
2355
for revno in range(from_revno, to_revno + 1):
2356
b.repository.sign_revision(b.get_rev_id(revno),
2359
raise BzrCommandError('Please supply either one revision, or a range.')
2362
class cmd_bind(Command):
2363
"""Bind the current branch to a master branch.
2365
After binding, commits must succeed on the master branch
2366
before they are executed on the local one.
2369
takes_args = ['location']
2372
def run(self, location=None):
2373
b, relpath = Branch.open_containing(u'.')
2374
b_other = Branch.open(location)
2377
except DivergedBranches:
2378
raise BzrCommandError('These branches have diverged.'
2379
' Try merging, and then bind again.')
2382
class cmd_unbind(Command):
2383
"""Bind the current branch to its parent.
2385
After unbinding, the local branch is considered independent.
2392
b, relpath = Branch.open_containing(u'.')
2394
raise BzrCommandError('Local branch is not bound')
2397
class cmd_uncommit(bzrlib.commands.Command):
2398
"""Remove the last committed revision.
2400
By supplying the --all flag, it will not only remove the entry
2401
from revision_history, but also remove all of the entries in the
2404
--verbose will print out what is being removed.
2405
--dry-run will go through all the motions, but not actually
2408
In the future, uncommit will create a changeset, which can then
2412
# TODO: jam 20060108 Add an option to allow uncommit to remove
2413
# unreferenced information in 'branch-as-repostory' branches.
2414
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
2415
# information in shared branches as well.
2416
takes_options = ['verbose', 'revision',
2417
Option('dry-run', help='Don\'t actually make changes'),
2418
Option('force', help='Say yes to all questions.')]
2419
takes_args = ['location?']
2422
def run(self, location=None,
2423
dry_run=False, verbose=False,
2424
revision=None, force=False):
2425
from bzrlib.branch import Branch
2426
from bzrlib.log import log_formatter
2428
from bzrlib.uncommit import uncommit
2430
if location is None:
2432
control, relpath = bzrdir.BzrDir.open_containing(location)
2434
tree = control.open_workingtree()
2436
except (errors.NoWorkingTree, errors.NotLocalUrl):
2438
b = control.open_branch()
2440
if revision is None:
2442
rev_id = b.last_revision()
2444
revno, rev_id = revision[0].in_history(b)
2446
print 'No revisions to uncommit.'
2448
for r in range(revno, b.revno()+1):
2449
rev_id = b.get_rev_id(r)
2450
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2451
lf.show(r, b.repository.get_revision(rev_id), None)
2454
print 'Dry-run, pretending to remove the above revisions.'
2456
val = raw_input('Press <enter> to continue')
2458
print 'The above revision(s) will be removed.'
2460
val = raw_input('Are you sure [y/N]? ')
2461
if val.lower() not in ('y', 'yes'):
2465
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
2469
class cmd_break_lock(Command):
2470
"""Break a dead lock on a repository, branch or working directory.
2472
CAUTION: Locks should only be broken when you are sure that the process
2473
holding the lock has been stopped.
2478
takes_args = ['location']
2479
takes_options = [Option('show',
2480
help="just show information on the lock, " \
2483
def run(self, location, show=False):
2484
raise NotImplementedError("sorry, break-lock is not complete yet; "
2485
"you can remove the 'held' directory manually to break the lock")
2488
# command-line interpretation helper for merge-related commands
2489
def merge(other_revision, base_revision,
2490
check_clean=True, ignore_zero=False,
2491
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2492
file_list=None, show_base=False, reprocess=False,
2493
pb=DummyProgress()):
2494
"""Merge changes into a tree.
2497
list(path, revno) Base for three-way merge.
2498
If [None, None] then a base will be automatically determined.
2500
list(path, revno) Other revision for three-way merge.
2502
Directory to merge changes into; '.' by default.
2504
If true, this_dir must have no uncommitted changes before the
2506
ignore_zero - If true, suppress the "zero conflicts" message when
2507
there are no conflicts; should be set when doing something we expect
2508
to complete perfectly.
2509
file_list - If supplied, merge only changes to selected files.
2511
All available ancestors of other_revision and base_revision are
2512
automatically pulled into the branch.
2514
The revno may be -1 to indicate the last revision on the branch, which is
2517
This function is intended for use from the command line; programmatic
2518
clients might prefer to call merge.merge_inner(), which has less magic
2521
from bzrlib.merge import Merger
2522
if this_dir is None:
2524
this_tree = WorkingTree.open_containing(this_dir)[0]
2525
if show_base and not merge_type is Merge3Merger:
2526
raise BzrCommandError("Show-base is not supported for this merge"
2527
" type. %s" % merge_type)
2528
if reprocess and not merge_type.supports_reprocess:
2529
raise BzrCommandError("Conflict reduction is not supported for merge"
2530
" type %s." % merge_type)
2531
if reprocess and show_base:
2532
raise BzrCommandError("Cannot do conflict reduction and show base.")
2534
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2535
merger.pp = ProgressPhase("Merge phase", 5, pb)
2536
merger.pp.next_phase()
2537
merger.check_basis(check_clean)
2538
merger.set_other(other_revision)
2539
merger.pp.next_phase()
2540
merger.set_base(base_revision)
2541
if merger.base_rev_id == merger.other_rev_id:
2542
note('Nothing to do.')
2544
merger.backup_files = backup_files
2545
merger.merge_type = merge_type
2546
merger.set_interesting_files(file_list)
2547
merger.show_base = show_base
2548
merger.reprocess = reprocess
2549
conflicts = merger.do_merge()
2550
if file_list is None:
2551
merger.set_pending()
2557
# these get imported and then picked up by the scan for cmd_*
2558
# TODO: Some more consistent way to split command definitions across files;
2559
# we do need to load at least some information about them to know of
2560
# aliases. ideally we would avoid loading the implementation until the
2561
# details were needed.
2562
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2563
from bzrlib.sign_my_commits import cmd_sign_my_commits
2564
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
2565
cmd_weave_plan_merge, cmd_weave_merge_text