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
self.outf.write('added ')
306
self.outf.write('\n')
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" % stored_loc)
430
location = stored_loc
432
if branch_to.get_parent() is None or remember:
433
branch_to.set_parent(location)
435
branch_from = Branch.open(location)
439
elif len(revision) == 1:
440
rev_id = revision[0].in_history(branch_from).rev_id
442
raise BzrCommandError('bzr pull --revision takes one value.')
444
old_rh = branch_to.revision_history()
445
if tree_to is not None:
446
count = tree_to.pull(branch_from, overwrite, rev_id)
448
count = branch_to.pull(branch_from, overwrite, rev_id)
449
note('%d revision(s) pulled.' % (count,))
452
new_rh = branch_to.revision_history()
455
from bzrlib.log import show_changed_revisions
456
show_changed_revisions(branch_to, old_rh, new_rh,
460
class cmd_push(Command):
461
"""Update a mirror of this branch.
463
The target branch will not have its working tree populated because this
464
is both expensive, and is not supported on remote file systems.
466
Some smart servers or protocols *may* put the working tree in place in
469
This command only works on branches that have not diverged. Branches are
470
considered diverged if the destination branch's most recent commit is one
471
that has not been merged (directly or indirectly) by the source branch.
473
If branches have diverged, you can use 'bzr push --overwrite' to replace
474
the other branch completely, discarding its unmerged changes.
476
If you want to ensure you have the different changes in the other branch,
477
do a merge (see bzr help merge) from the other branch, and commit that.
478
After that you will be able to do a push without '--overwrite'.
480
If there is no default push location set, the first push will set it.
481
After that, you can omit the location to use the default. To change the
482
default, use --remember.
484
takes_options = ['remember', 'overwrite', 'verbose',
485
Option('create-prefix',
486
help='Create the path leading up to the branch '
487
'if it does not already exist')]
488
takes_args = ['location?']
489
encoding_type = 'replace'
491
def run(self, location=None, remember=False, overwrite=False,
492
create_prefix=False, verbose=False):
493
# FIXME: Way too big! Put this into a function called from the
495
from bzrlib.transport import get_transport
497
tree_from = WorkingTree.open_containing(u'.')[0]
498
br_from = tree_from.branch
499
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
506
if br_from.get_push_location() is None or remember:
507
br_from.set_push_location(location)
509
dir_to = bzrlib.bzrdir.BzrDir.open(location)
510
br_to = dir_to.open_branch()
511
except NotBranchError:
513
transport = get_transport(location).clone('..')
514
if not create_prefix:
516
transport.mkdir(transport.relpath(location))
518
raise BzrCommandError("Parent directory of %s "
519
"does not exist." % location)
521
current = transport.base
522
needed = [(transport, transport.relpath(location))]
525
transport, relpath = needed[-1]
526
transport.mkdir(relpath)
529
new_transport = transport.clone('..')
530
needed.append((new_transport,
531
new_transport.relpath(transport.base)))
532
if new_transport.base == transport.base:
533
raise BzrCommandError("Could not create "
535
dir_to = br_from.bzrdir.clone(location)
536
br_to = dir_to.open_branch()
537
old_rh = br_to.revision_history()
540
tree_to = dir_to.open_workingtree()
541
except errors.NotLocalUrl:
542
# TODO: This should be updated for branches which don't have a
543
# working tree, as opposed to ones where we just couldn't
545
warning('This transport does not update the working '
546
'tree of: %s' % (br_to.base,))
547
count = br_to.pull(br_from, overwrite)
548
except NoWorkingTree:
549
count = br_to.pull(br_from, overwrite)
551
count = tree_to.pull(br_from, overwrite)
552
except DivergedBranches:
553
raise BzrCommandError("These branches have diverged."
554
" Try a merge then push with overwrite.")
555
note('%d revision(s) pushed.' % (count,))
558
new_rh = br_to.revision_history()
561
from bzrlib.log import show_changed_revisions
562
show_changed_revisions(br_to, old_rh, new_rh,
566
class cmd_branch(Command):
567
"""Create a new copy of a branch.
569
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
570
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
572
To retrieve the branch as of a particular revision, supply the --revision
573
parameter, as in "branch foo/bar -r 5".
575
--basis is to speed up branching from remote branches. When specified, it
576
copies all the file-contents, inventory and revision data from the basis
577
branch before copying anything from the remote branch.
579
takes_args = ['from_location', 'to_location?']
580
takes_options = ['revision', 'basis']
581
aliases = ['get', 'clone']
583
def run(self, from_location, to_location=None, revision=None, basis=None):
586
elif len(revision) > 1:
587
raise BzrCommandError(
588
'bzr branch --revision takes exactly 1 revision value')
590
br_from = Branch.open(from_location)
592
if e.errno == errno.ENOENT:
593
raise BzrCommandError('Source location "%s" does not'
594
' exist.' % to_location)
599
if basis is not None:
600
basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
603
if len(revision) == 1 and revision[0] is not None:
604
revision_id = revision[0].in_history(br_from)[1]
606
# FIXME - wt.last_revision, fallback to branch, fall back to
607
# None or perhaps NULL_REVISION to mean copy nothing
609
revision_id = br_from.last_revision()
610
if to_location is None:
611
to_location = os.path.basename(from_location.rstrip("/\\"))
614
name = os.path.basename(to_location) + '\n'
616
os.mkdir(to_location)
618
if e.errno == errno.EEXIST:
619
raise BzrCommandError('Target directory "%s" already'
620
' exists.' % to_location)
621
if e.errno == errno.ENOENT:
622
raise BzrCommandError('Parent of "%s" does not exist.' %
627
# preserve whatever source format we have.
628
dir = br_from.bzrdir.sprout(to_location, revision_id, basis_dir)
629
branch = dir.open_branch()
630
except bzrlib.errors.NoSuchRevision:
632
msg = "The branch %s has no revision %s." % (from_location, revision[0])
633
raise BzrCommandError(msg)
634
except bzrlib.errors.UnlistableBranch:
636
msg = "The branch %s cannot be used as a --basis" % (basis,)
637
raise BzrCommandError(msg)
639
branch.control_files.put_utf8('branch-name', name)
640
note('Branched %d revision(s).' % branch.revno())
645
class cmd_checkout(Command):
646
"""Create a new checkout of an existing branch.
648
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
649
the branch found in '.'. This is useful if you have removed the working tree
650
or if it was never created - i.e. if you pushed the branch to its current
653
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
654
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
656
To retrieve the branch as of a particular revision, supply the --revision
657
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
658
out of date [so you cannot commit] but it may be useful (i.e. to examine old
661
--basis is to speed up checking out from remote branches. When specified, it
662
uses the inventory and file contents from the basis branch in preference to the
663
branch being checked out. [Not implemented yet.]
665
takes_args = ['branch_location?', 'to_location?']
666
takes_options = ['revision', # , 'basis']
667
Option('lightweight',
668
help="perform a lightweight checkout. Lightweight "
669
"checkouts depend on access to the branch for "
670
"every operation. Normal checkouts can perform "
671
"common operations like diff and status without "
672
"such access, and also support local commits."
676
def run(self, branch_location=None, to_location=None, revision=None, basis=None,
680
elif len(revision) > 1:
681
raise BzrCommandError(
682
'bzr checkout --revision takes exactly 1 revision value')
683
if branch_location is None:
684
branch_location = bzrlib.osutils.getcwd()
685
to_location = branch_location
686
source = Branch.open(branch_location)
687
if len(revision) == 1 and revision[0] is not None:
688
revision_id = revision[0].in_history(source)[1]
691
if to_location is None:
692
to_location = os.path.basename(branch_location.rstrip("/\\"))
693
# if the source and to_location are the same,
694
# and there is no working tree,
695
# then reconstitute a branch
696
if (bzrlib.osutils.abspath(to_location) ==
697
bzrlib.osutils.abspath(branch_location)):
699
source.bzrdir.open_workingtree()
700
except errors.NoWorkingTree:
701
source.bzrdir.create_workingtree()
704
os.mkdir(to_location)
706
if e.errno == errno.EEXIST:
707
raise BzrCommandError('Target directory "%s" already'
708
' exists.' % to_location)
709
if e.errno == errno.ENOENT:
710
raise BzrCommandError('Parent of "%s" does not exist.' %
714
old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
715
bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
718
checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
719
bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
721
checkout_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience(
722
to_location, force_new_tree=False)
723
checkout = checkout_branch.bzrdir
724
checkout_branch.bind(source)
725
if revision_id is not None:
726
rh = checkout_branch.revision_history()
727
checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
728
checkout.create_workingtree(revision_id)
730
bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
733
class cmd_renames(Command):
734
"""Show list of renamed files.
736
# TODO: Option to show renames between two historical versions.
738
# TODO: Only show renames under dir, rather than in the whole branch.
739
takes_args = ['dir?']
742
def run(self, dir=u'.'):
743
tree = WorkingTree.open_containing(dir)[0]
744
old_inv = tree.basis_tree().inventory
745
new_inv = tree.read_working_inventory()
747
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
749
for old_name, new_name in renames:
750
self.outf.write("%s => %s\n" % (old_name, new_name))
753
class cmd_update(Command):
754
"""Update a tree to have the latest code committed to its branch.
756
This will perform a merge into the working tree, and may generate
757
conflicts. If you have any local changes, you will still
758
need to commit them after the update for the update to be complete.
760
If you want to discard your local changes, you can just do a
761
'bzr revert' instead of 'bzr commit' after the update.
763
takes_args = ['dir?']
765
def run(self, dir='.'):
766
tree = WorkingTree.open_containing(dir)[0]
769
if tree.last_revision() == tree.branch.last_revision():
770
# may be up to date, check master too.
771
master = tree.branch.get_master_branch()
772
if master is None or master.last_revision == tree.last_revision():
773
note("Tree is up to date.")
775
conflicts = tree.update()
776
note('Updated to revision %d.' %
777
(tree.branch.revision_id_to_revno(tree.last_revision()),))
786
class cmd_info(Command):
787
"""Show statistical information about a branch."""
788
takes_args = ['branch?']
789
takes_options = ['verbose']
792
def run(self, branch=None, verbose=False):
794
bzrlib.info.show_bzrdir_info(bzrdir.BzrDir.open_containing(branch)[0],
798
class cmd_remove(Command):
799
"""Make a file unversioned.
801
This makes bzr stop tracking changes to a versioned file. It does
802
not delete the working copy.
804
takes_args = ['file+']
805
takes_options = ['verbose']
808
def run(self, file_list, verbose=False):
809
tree, file_list = tree_files(file_list)
810
tree.remove(file_list, verbose=verbose)
813
class cmd_file_id(Command):
814
"""Print file_id of a particular file or directory.
816
The file_id is assigned when the file is first added and remains the
817
same through all revisions where the file exists, even when it is
821
takes_args = ['filename']
824
def run(self, filename):
825
tree, relpath = WorkingTree.open_containing(filename)
826
i = tree.inventory.path2id(relpath)
828
raise BzrError("%r is not a versioned file" % filename)
831
self.outf.write('\n')
834
class cmd_file_path(Command):
835
"""Print path of file_ids to a file or directory.
837
This prints one line for each directory down to the target,
838
starting at the branch root.
841
takes_args = ['filename']
844
def run(self, filename):
845
tree, relpath = WorkingTree.open_containing(filename)
847
fid = inv.path2id(relpath)
849
raise BzrError("%r is not a versioned file" % filename)
850
for fip in inv.get_idpath(fid):
852
self.outf.write('\n')
855
class cmd_reconcile(Command):
856
"""Reconcile bzr metadata in a branch.
858
This can correct data mismatches that may have been caused by
859
previous ghost operations or bzr upgrades. You should only
860
need to run this command if 'bzr check' or a bzr developer
861
advises you to run it.
863
If a second branch is provided, cross-branch reconciliation is
864
also attempted, which will check that data like the tree root
865
id which was not present in very early bzr versions is represented
866
correctly in both branches.
868
At the same time it is run it may recompress data resulting in
869
a potential saving in disk space or performance gain.
871
The branch *MUST* be on a listable system such as local disk or sftp.
873
takes_args = ['branch?']
875
def run(self, branch="."):
876
from bzrlib.reconcile import reconcile
877
dir = bzrlib.bzrdir.BzrDir.open(branch)
881
class cmd_revision_history(Command):
882
"""Display list of revision ids on this branch."""
887
branch = WorkingTree.open_containing(u'.')[0].branch
888
for patchid in branch.revision_history():
889
self.outf.write(patchid)
890
self.outf.write('\n')
893
class cmd_ancestry(Command):
894
"""List all revisions merged into this branch."""
899
tree = WorkingTree.open_containing(u'.')[0]
901
# FIXME. should be tree.last_revision
902
for revision_id in b.repository.get_ancestry(b.last_revision()):
903
if revision_id is None:
905
self.outf.write(revision_id)
906
self.outf.write('\n')
909
class cmd_init(Command):
910
"""Make a directory into a versioned branch.
912
Use this to create an empty branch, or before importing an
915
If there is a repository in a parent directory of the location, then
916
the history of the branch will be stored in the repository. Otherwise
917
init creates a standalone branch which carries its own history in
920
If there is already a branch at the location but it has no working tree,
921
the tree can be populated with 'bzr checkout'.
923
Recipe for importing a tree of files:
928
bzr commit -m 'imported project'
930
takes_args = ['location?']
933
help='Create a specific format rather than the'
934
' current default format. Currently this '
935
' option only accepts "metadir"',
936
type=get_format_type),
938
def run(self, location=None, format=None):
939
from bzrlib.branch import Branch
943
# The path has to exist to initialize a
944
# branch inside of it.
945
# Just using os.mkdir, since I don't
946
# believe that we want to create a bunch of
947
# locations if the user supplies an extended path
948
if not os.path.exists(location):
951
existing_bzrdir = bzrdir.BzrDir.open(location)
952
except NotBranchError:
953
# really a NotBzrDir error...
954
bzrdir.BzrDir.create_branch_convenience(location, format=format)
956
if existing_bzrdir.has_branch():
957
if existing_bzrdir.has_workingtree():
958
raise errors.AlreadyBranchError(location)
960
raise errors.BranchExistsWithoutWorkingTree(location)
962
existing_bzrdir.create_branch()
963
existing_bzrdir.create_workingtree()
966
class cmd_init_repository(Command):
967
"""Create a shared repository to hold branches.
969
New branches created under the repository directory will store their revisions
970
in the repository, not in the branch directory, if the branch format supports
976
bzr checkout --lightweight repo/trunk trunk-checkout
980
takes_args = ["location"]
981
takes_options = [Option('format',
982
help='Use a specific format rather than the'
983
' current default format. Currently this'
984
' option accepts "weave", "metadir" and "knit"',
985
type=get_format_type),
987
help='Allows branches in repository to have'
989
aliases = ["init-repo"]
990
def run(self, location, format=None, trees=False):
991
from bzrlib.bzrdir import BzrDirMetaFormat1
992
from bzrlib.transport import get_transport
994
format = BzrDirMetaFormat1()
995
transport = get_transport(location)
996
if not transport.has('.'):
998
newdir = format.initialize_on_transport(transport)
999
repo = newdir.create_repository(shared=True)
1000
repo.set_make_working_trees(trees)
1003
class cmd_diff(Command):
1004
"""Show differences in working tree.
1006
If files are listed, only the changes in those files are listed.
1007
Otherwise, all changes for the tree are listed.
1014
# TODO: Allow diff across branches.
1015
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1016
# or a graphical diff.
1018
# TODO: Python difflib is not exactly the same as unidiff; should
1019
# either fix it up or prefer to use an external diff.
1021
# TODO: If a directory is given, diff everything under that.
1023
# TODO: Selected-file diff is inefficient and doesn't show you
1026
# TODO: This probably handles non-Unix newlines poorly.
1028
takes_args = ['file*']
1029
takes_options = ['revision', 'diff-options']
1030
aliases = ['di', 'dif']
1031
encoding_type = 'exact'
1034
def run(self, revision=None, file_list=None, diff_options=None):
1035
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1037
tree1, file_list = internal_tree_files(file_list)
1041
except FileInWrongBranch:
1042
if len(file_list) != 2:
1043
raise BzrCommandError("Files are in different branches")
1045
tree1, file1 = WorkingTree.open_containing(file_list[0])
1046
tree2, file2 = WorkingTree.open_containing(file_list[1])
1047
if file1 != "" or file2 != "":
1048
# FIXME diff those two files. rbc 20051123
1049
raise BzrCommandError("Files are in different branches")
1051
if revision is not None:
1052
if tree2 is not None:
1053
raise BzrCommandError("Can't specify -r with two branches")
1054
if (len(revision) == 1) or (revision[1].spec is None):
1055
return diff_cmd_helper(tree1, file_list, diff_options,
1057
elif len(revision) == 2:
1058
return diff_cmd_helper(tree1, file_list, diff_options,
1059
revision[0], revision[1])
1061
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1063
if tree2 is not None:
1064
return show_diff_trees(tree1, tree2, sys.stdout,
1065
specific_files=file_list,
1066
external_diff_options=diff_options)
1068
return diff_cmd_helper(tree1, file_list, diff_options)
1071
class cmd_deleted(Command):
1072
"""List files deleted in the working tree.
1074
# TODO: Show files deleted since a previous revision, or
1075
# between two revisions.
1076
# TODO: Much more efficient way to do this: read in new
1077
# directories with readdir, rather than stating each one. Same
1078
# level of effort but possibly much less IO. (Or possibly not,
1079
# if the directories are very large...)
1080
takes_options = ['show-ids']
1083
def run(self, show_ids=False):
1084
tree = WorkingTree.open_containing(u'.')[0]
1085
old = tree.basis_tree()
1086
for path, ie in old.inventory.iter_entries():
1087
if not tree.has_id(ie.file_id):
1088
self.outf.write(path)
1090
self.outf.write(' ')
1091
self.outf.write(ie.file_id)
1092
self.outf.write('\n')
1095
class cmd_modified(Command):
1096
"""List files modified in working tree."""
1100
from bzrlib.delta import compare_trees
1102
tree = WorkingTree.open_containing(u'.')[0]
1103
td = compare_trees(tree.basis_tree(), tree)
1105
for path, id, kind, text_modified, meta_modified in td.modified:
1106
self.outf.write(path)
1107
self.outf.write('\n')
1110
class cmd_added(Command):
1111
"""List files added in working tree."""
1115
wt = WorkingTree.open_containing(u'.')[0]
1116
basis_inv = wt.basis_tree().inventory
1119
if file_id in basis_inv:
1121
path = inv.id2path(file_id)
1122
if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
1124
self.outf.write(path)
1125
self.outf.write('\n')
1128
class cmd_root(Command):
1129
"""Show the tree root directory.
1131
The root is the nearest enclosing directory with a .bzr control
1133
takes_args = ['filename?']
1135
def run(self, filename=None):
1136
"""Print the branch root."""
1137
tree = WorkingTree.open_containing(filename)[0]
1138
self.outf.write(tree.basedir)
1139
self.outf.write('\n')
1142
class cmd_log(Command):
1143
"""Show log of a branch, file, or directory.
1145
By default show the log of the branch containing the working directory.
1147
To request a range of logs, you can use the command -r begin..end
1148
-r revision requests a specific revision, -r ..end or -r begin.. are
1154
bzr log -r -10.. http://server/branch
1157
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1159
takes_args = ['location?']
1160
takes_options = [Option('forward',
1161
help='show from oldest to newest'),
1164
help='show files changed in each revision'),
1165
'show-ids', 'revision',
1169
help='show revisions whose message matches this regexp',
1173
encoding_type = 'replace'
1176
def run(self, location=None, timezone='original',
1186
from bzrlib.log import log_formatter, show_log
1187
assert message is None or isinstance(message, basestring), \
1188
"invalid message argument %r" % message
1189
direction = (forward and 'forward') or 'reverse'
1194
# find the file id to log:
1196
dir, fp = bzrdir.BzrDir.open_containing(location)
1197
b = dir.open_branch()
1201
inv = dir.open_workingtree().inventory
1202
except (errors.NotBranchError, errors.NotLocalUrl):
1203
# either no tree, or is remote.
1204
inv = b.basis_tree().inventory
1205
file_id = inv.path2id(fp)
1208
# FIXME ? log the current subdir only RBC 20060203
1209
dir, relpath = bzrdir.BzrDir.open_containing('.')
1210
b = dir.open_branch()
1212
if revision is None:
1215
elif len(revision) == 1:
1216
rev1 = rev2 = revision[0].in_history(b).revno
1217
elif len(revision) == 2:
1218
if revision[0].spec is None:
1219
# missing begin-range means first revision
1222
rev1 = revision[0].in_history(b).revno
1224
if revision[1].spec is None:
1225
# missing end-range means last known revision
1228
rev2 = revision[1].in_history(b).revno
1230
raise BzrCommandError('bzr log --revision takes one or two values.')
1232
# By this point, the revision numbers are converted to the +ve
1233
# form if they were supplied in the -ve form, so we can do
1234
# this comparison in relative safety
1236
(rev2, rev1) = (rev1, rev2)
1238
if (log_format == None):
1239
default = bzrlib.config.BranchConfig(b).log_format()
1240
log_format = get_log_format(long=long, short=short, line=line, default=default)
1241
lf = log_formatter(log_format,
1244
show_timezone=timezone)
1250
direction=direction,
1251
start_revision=rev1,
1256
def get_log_format(long=False, short=False, line=False, default='long'):
1257
log_format = default
1261
log_format = 'short'
1267
class cmd_touching_revisions(Command):
1268
"""Return revision-ids which affected a particular file.
1270
A more user-friendly interface is "bzr log FILE"."""
1272
takes_args = ["filename"]
1273
encoding_type = 'replace'
1276
def run(self, filename):
1277
tree, relpath = WorkingTree.open_containing(filename)
1279
inv = tree.read_working_inventory()
1280
file_id = inv.path2id(relpath)
1281
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1282
self.outf.write("%6d %s\n" % (revno, what))
1285
class cmd_ls(Command):
1286
"""List files in a tree.
1288
# TODO: Take a revision or remote path and list that tree instead.
1290
takes_options = ['verbose', 'revision',
1291
Option('non-recursive',
1292
help='don\'t recurse into sub-directories'),
1294
help='Print all paths from the root of the branch.'),
1295
Option('unknown', help='Print unknown files'),
1296
Option('versioned', help='Print versioned files'),
1297
Option('ignored', help='Print ignored files'),
1299
Option('null', help='Null separate the files'),
1302
def run(self, revision=None, verbose=False,
1303
non_recursive=False, from_root=False,
1304
unknown=False, versioned=False, ignored=False,
1307
if verbose and null:
1308
raise BzrCommandError('Cannot set both --verbose and --null')
1309
all = not (unknown or versioned or ignored)
1311
selection = {'I':ignored, '?':unknown, 'V':versioned}
1313
tree, relpath = WorkingTree.open_containing(u'.')
1318
if revision is not None:
1319
tree = tree.branch.repository.revision_tree(
1320
revision[0].in_history(tree.branch).rev_id)
1322
for fp, fc, kind, fid, entry in tree.list_files():
1323
if fp.startswith(relpath):
1324
fp = fp[len(relpath):]
1325
if non_recursive and '/' in fp:
1327
if not all and not selection[fc]:
1330
kindch = entry.kind_character()
1331
self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1334
self.outf.write('\0')
1338
self.outf.write('\n')
1341
class cmd_unknowns(Command):
1342
"""List unknown files."""
1345
from bzrlib.osutils import quotefn
1346
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1347
self.outf.write(quotefn(f))
1348
self.outf.write('\n')
1351
class cmd_ignore(Command):
1352
"""Ignore a command or pattern.
1354
To remove patterns from the ignore list, edit the .bzrignore file.
1356
If the pattern contains a slash, it is compared to the whole path
1357
from the branch root. Otherwise, it is compared to only the last
1358
component of the path. To match a file only in the root directory,
1361
Ignore patterns are case-insensitive on case-insensitive systems.
1363
Note: wildcards must be quoted from the shell on Unix.
1366
bzr ignore ./Makefile
1367
bzr ignore '*.class'
1369
# TODO: Complain if the filename is absolute
1370
takes_args = ['name_pattern']
1372
def run(self, name_pattern):
1373
from bzrlib.atomicfile import AtomicFile
1376
tree, relpath = WorkingTree.open_containing(u'.')
1377
ifn = tree.abspath('.bzrignore')
1379
if os.path.exists(ifn):
1382
igns = f.read().decode('utf-8')
1388
# TODO: If the file already uses crlf-style termination, maybe
1389
# we should use that for the newly added lines?
1391
if igns and igns[-1] != '\n':
1393
igns += name_pattern + '\n'
1396
f = AtomicFile(ifn, 'wt')
1397
f.write(igns.encode('utf-8'))
1402
inv = tree.inventory
1403
if inv.path2id('.bzrignore'):
1404
mutter('.bzrignore is already versioned')
1406
mutter('need to make new .bzrignore file versioned')
1407
tree.add(['.bzrignore'])
1410
class cmd_ignored(Command):
1411
"""List ignored files and the patterns that matched them.
1413
See also: bzr ignore"""
1416
tree = WorkingTree.open_containing(u'.')[0]
1417
for path, file_class, kind, file_id, entry in tree.list_files():
1418
if file_class != 'I':
1420
## XXX: Slightly inefficient since this was already calculated
1421
pat = tree.is_ignored(path)
1422
print '%-50s %s' % (path, pat)
1425
class cmd_lookup_revision(Command):
1426
"""Lookup the revision-id from a revision-number
1429
bzr lookup-revision 33
1432
takes_args = ['revno']
1435
def run(self, revno):
1439
raise BzrCommandError("not a valid revision-number: %r" % revno)
1441
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1444
class cmd_export(Command):
1445
"""Export past revision to destination directory.
1447
If no revision is specified this exports the last committed revision.
1449
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1450
given, try to find the format with the extension. If no extension
1451
is found exports to a directory (equivalent to --format=dir).
1453
Root may be the top directory for tar, tgz and tbz2 formats. If none
1454
is given, the top directory will be the root name of the file.
1456
Note: export of tree with non-ascii filenames to zip is not supported.
1458
Supported formats Autodetected by extension
1459
----------------- -------------------------
1462
tbz2 .tar.bz2, .tbz2
1466
takes_args = ['dest']
1467
takes_options = ['revision', 'format', 'root']
1468
def run(self, dest, revision=None, format=None, root=None):
1470
from bzrlib.export import export
1471
tree = WorkingTree.open_containing(u'.')[0]
1473
if revision is None:
1474
# should be tree.last_revision FIXME
1475
rev_id = b.last_revision()
1477
if len(revision) != 1:
1478
raise BzrError('bzr export --revision takes exactly 1 argument')
1479
rev_id = revision[0].in_history(b).rev_id
1480
t = b.repository.revision_tree(rev_id)
1482
export(t, dest, format, root)
1483
except errors.NoSuchExportFormat, e:
1484
raise BzrCommandError('Unsupported export format: %s' % e.format)
1487
class cmd_cat(Command):
1488
"""Write a file's text from a previous revision."""
1490
takes_options = ['revision']
1491
takes_args = ['filename']
1494
def run(self, filename, revision=None):
1495
if revision is not None and len(revision) != 1:
1496
raise BzrCommandError("bzr cat --revision takes exactly one number")
1499
tree, relpath = WorkingTree.open_containing(filename)
1501
except NotBranchError:
1505
b, relpath = Branch.open_containing(filename)
1506
if revision is None:
1507
revision_id = b.last_revision()
1509
revision_id = revision[0].in_history(b).rev_id
1510
b.print_file(relpath, revision_id)
1513
class cmd_local_time_offset(Command):
1514
"""Show the offset in seconds from GMT to local time."""
1518
print bzrlib.osutils.local_time_offset()
1522
class cmd_commit(Command):
1523
"""Commit changes into a new revision.
1525
If no arguments are given, the entire tree is committed.
1527
If selected files are specified, only changes to those files are
1528
committed. If a directory is specified then the directory and everything
1529
within it is committed.
1531
A selected-file commit may fail in some cases where the committed
1532
tree would be invalid, such as trying to commit a file in a
1533
newly-added directory that is not itself committed.
1535
# TODO: Run hooks on tree to-be-committed, and after commit.
1537
# TODO: Strict commit that fails if there are deleted files.
1538
# (what does "deleted files" mean ??)
1540
# TODO: Give better message for -s, --summary, used by tla people
1542
# XXX: verbose currently does nothing
1544
takes_args = ['selected*']
1545
takes_options = ['message', 'verbose',
1547
help='commit even if nothing has changed'),
1548
Option('file', type=str,
1550
help='file containing commit message'),
1552
help="refuse to commit if there are unknown "
1553
"files in the working tree."),
1555
help="perform a local only commit in a bound "
1556
"branch. Such commits are not pushed to "
1557
"the master branch until a normal commit "
1561
aliases = ['ci', 'checkin']
1563
def run(self, message=None, file=None, verbose=True, selected_list=None,
1564
unchanged=False, strict=False, local=False):
1565
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
1566
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1568
from bzrlib.msgeditor import edit_commit_message, \
1569
make_commit_message_template
1570
from tempfile import TemporaryFile
1572
# TODO: Need a blackbox test for invoking the external editor; may be
1573
# slightly problematic to run this cross-platform.
1575
# TODO: do more checks that the commit will succeed before
1576
# spending the user's valuable time typing a commit message.
1578
# TODO: if the commit *does* happen to fail, then save the commit
1579
# message to a temporary file where it can be recovered
1580
tree, selected_list = tree_files(selected_list)
1581
if local and not tree.branch.get_bound_location():
1582
raise errors.LocalRequiresBoundBranch()
1583
if message is None and not file:
1584
template = make_commit_message_template(tree, selected_list)
1585
message = edit_commit_message(template)
1587
raise BzrCommandError("please specify a commit message"
1588
" with either --message or --file")
1589
elif message and file:
1590
raise BzrCommandError("please specify either --message or --file")
1593
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1596
raise BzrCommandError("empty commit message specified")
1599
reporter = ReportCommitToLog()
1601
reporter = NullCommitReporter()
1604
tree.commit(message, specific_files=selected_list,
1605
allow_pointless=unchanged, strict=strict, local=local,
1607
except PointlessCommit:
1608
# FIXME: This should really happen before the file is read in;
1609
# perhaps prepare the commit; get the message; then actually commit
1610
raise BzrCommandError("no changes to commit",
1611
["use --unchanged to commit anyhow"])
1612
except ConflictsInTree:
1613
raise BzrCommandError("Conflicts detected in working tree. "
1614
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1615
except StrictCommitFailed:
1616
raise BzrCommandError("Commit refused because there are unknown "
1617
"files in the working tree.")
1618
except errors.BoundBranchOutOfDate, e:
1619
raise BzrCommandError(str(e)
1620
+ ' Either unbind, update, or'
1621
' pass --local to commit.')
1624
class cmd_check(Command):
1625
"""Validate consistency of branch history.
1627
This command checks various invariants about the branch storage to
1628
detect data corruption or bzr bugs.
1630
takes_args = ['branch?']
1631
takes_options = ['verbose']
1633
def run(self, branch=None, verbose=False):
1634
from bzrlib.check import check
1636
tree = WorkingTree.open_containing()[0]
1637
branch = tree.branch
1639
branch = Branch.open(branch)
1640
check(branch, verbose)
1643
class cmd_scan_cache(Command):
1646
from bzrlib.hashcache import HashCache
1652
print '%6d stats' % c.stat_count
1653
print '%6d in hashcache' % len(c._cache)
1654
print '%6d files removed from cache' % c.removed_count
1655
print '%6d hashes updated' % c.update_count
1656
print '%6d files changed too recently to cache' % c.danger_count
1662
class cmd_upgrade(Command):
1663
"""Upgrade branch storage to current format.
1665
The check command or bzr developers may sometimes advise you to run
1666
this command. When the default format has changed you may also be warned
1667
during other operations to upgrade.
1669
takes_args = ['url?']
1672
help='Upgrade to a specific format rather than the'
1673
' current default format. Currently this'
1674
' option accepts "weave", "metadir" and'
1676
type=get_format_type),
1680
def run(self, url='.', format=None):
1681
from bzrlib.upgrade import upgrade
1682
upgrade(url, format)
1685
class cmd_whoami(Command):
1686
"""Show bzr user id."""
1687
takes_options = ['email']
1690
def run(self, email=False):
1692
b = WorkingTree.open_containing(u'.')[0].branch
1693
config = bzrlib.config.BranchConfig(b)
1694
except NotBranchError:
1695
config = bzrlib.config.GlobalConfig()
1698
print config.user_email()
1700
print config.username()
1703
class cmd_nick(Command):
1704
"""Print or set the branch nickname.
1706
If unset, the tree root directory name is used as the nickname
1707
To print the current nickname, execute with no argument.
1709
takes_args = ['nickname?']
1710
def run(self, nickname=None):
1711
branch = Branch.open_containing(u'.')[0]
1712
if nickname is None:
1713
self.printme(branch)
1715
branch.nick = nickname
1718
def printme(self, branch):
1722
class cmd_selftest(Command):
1723
"""Run internal test suite.
1725
This creates temporary test directories in the working directory,
1726
but not existing data is affected. These directories are deleted
1727
if the tests pass, or left behind to help in debugging if they
1728
fail and --keep-output is specified.
1730
If arguments are given, they are regular expressions that say
1731
which tests should run.
1733
If the global option '--no-plugins' is given, plugins are not loaded
1734
before running the selftests. This has two effects: features provided or
1735
modified by plugins will not be tested, and tests provided by plugins will
1740
bzr --no-plugins selftest -v
1742
# TODO: --list should give a list of all available tests
1744
# NB: this is used from the class without creating an instance, which is
1745
# why it does not have a self parameter.
1746
def get_transport_type(typestring):
1747
"""Parse and return a transport specifier."""
1748
if typestring == "sftp":
1749
from bzrlib.transport.sftp import SFTPAbsoluteServer
1750
return SFTPAbsoluteServer
1751
if typestring == "memory":
1752
from bzrlib.transport.memory import MemoryServer
1754
if typestring == "fakenfs":
1755
from bzrlib.transport.fakenfs import FakeNFSServer
1756
return FakeNFSServer
1757
msg = "No known transport type %s. Supported types are: sftp\n" %\
1759
raise BzrCommandError(msg)
1762
takes_args = ['testspecs*']
1763
takes_options = ['verbose',
1764
Option('one', help='stop when one test fails'),
1765
Option('keep-output',
1766
help='keep output directories when tests fail'),
1768
help='Use a different transport by default '
1769
'throughout the test suite.',
1770
type=get_transport_type),
1773
def run(self, testspecs_list=None, verbose=False, one=False,
1774
keep_output=False, transport=None):
1776
from bzrlib.tests import selftest
1777
# we don't want progress meters from the tests to go to the
1778
# real output; and we don't want log messages cluttering up
1780
save_ui = bzrlib.ui.ui_factory
1781
bzrlib.trace.info('running tests...')
1783
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1784
if testspecs_list is not None:
1785
pattern = '|'.join(testspecs_list)
1788
result = selftest(verbose=verbose,
1790
stop_on_failure=one,
1791
keep_output=keep_output,
1792
transport=transport)
1794
bzrlib.trace.info('tests passed')
1796
bzrlib.trace.info('tests failed')
1797
return int(not result)
1799
bzrlib.ui.ui_factory = save_ui
1802
def _get_bzr_branch():
1803
"""If bzr is run from a branch, return Branch or None"""
1804
import bzrlib.errors
1805
from bzrlib.branch import Branch
1806
from bzrlib.osutils import abspath
1807
from os.path import dirname
1810
branch = Branch.open(dirname(abspath(dirname(__file__))))
1812
except bzrlib.errors.BzrError:
1817
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1818
# is bzrlib itself in a branch?
1819
branch = _get_bzr_branch()
1821
rh = branch.revision_history()
1823
print " bzr checkout, revision %d" % (revno,)
1824
print " nick: %s" % (branch.nick,)
1826
print " revid: %s" % (rh[-1],)
1827
print bzrlib.__copyright__
1828
print "http://bazaar-ng.org/"
1830
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1831
print "you may use, modify and redistribute it under the terms of the GNU"
1832
print "General Public License version 2 or later."
1835
class cmd_version(Command):
1836
"""Show version of bzr."""
1841
class cmd_rocks(Command):
1842
"""Statement of optimism."""
1846
print "it sure does!"
1849
class cmd_find_merge_base(Command):
1850
"""Find and print a base revision for merging two branches.
1852
# TODO: Options to specify revisions on either side, as if
1853
# merging only part of the history.
1854
takes_args = ['branch', 'other']
1858
def run(self, branch, other):
1859
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1861
branch1 = Branch.open_containing(branch)[0]
1862
branch2 = Branch.open_containing(other)[0]
1864
history_1 = branch1.revision_history()
1865
history_2 = branch2.revision_history()
1867
last1 = branch1.last_revision()
1868
last2 = branch2.last_revision()
1870
source = MultipleRevisionSources(branch1.repository,
1873
base_rev_id = common_ancestor(last1, last2, source)
1875
print 'merge base is revision %s' % base_rev_id
1879
if base_revno is None:
1880
raise bzrlib.errors.UnrelatedBranches()
1882
print ' r%-6d in %s' % (base_revno, branch)
1884
other_revno = branch2.revision_id_to_revno(base_revid)
1886
print ' r%-6d in %s' % (other_revno, other)
1890
class cmd_merge(Command):
1891
"""Perform a three-way merge.
1893
The branch is the branch you will merge from. By default, it will
1894
merge the latest revision. If you specify a revision, that
1895
revision will be merged. If you specify two revisions, the first
1896
will be used as a BASE, and the second one as OTHER. Revision
1897
numbers are always relative to the specified branch.
1899
By default, bzr will try to merge in all new work from the other
1900
branch, automatically determining an appropriate base. If this
1901
fails, you may need to give an explicit base.
1903
Merge will do its best to combine the changes in two branches, but there
1904
are some kinds of problems only a human can fix. When it encounters those,
1905
it will mark a conflict. A conflict means that you need to fix something,
1906
before you should commit.
1908
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
1910
If there is no default branch set, the first merge will set it. After
1911
that, you can omit the branch to use the default. To change the
1912
default, use --remember.
1916
To merge the latest revision from bzr.dev
1917
bzr merge ../bzr.dev
1919
To merge changes up to and including revision 82 from bzr.dev
1920
bzr merge -r 82 ../bzr.dev
1922
To merge the changes introduced by 82, without previous changes:
1923
bzr merge -r 81..82 ../bzr.dev
1925
merge refuses to run if there are any uncommitted changes, unless
1928
takes_args = ['branch?']
1929
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
1930
Option('show-base', help="Show base revision text in "
1933
def run(self, branch=None, revision=None, force=False, merge_type=None,
1934
show_base=False, reprocess=False, remember=False):
1935
if merge_type is None:
1936
merge_type = Merge3Merger
1938
tree = WorkingTree.open_containing(u'.')[0]
1939
stored_loc = tree.branch.get_parent()
1941
if stored_loc is None:
1942
raise BzrCommandError("No merge branch known or specified.")
1944
print "Using saved branch: %s" % stored_loc
1947
if tree.branch.get_parent() is None or remember:
1948
tree.branch.set_parent(branch)
1950
if revision is None or len(revision) < 1:
1952
other = [branch, -1]
1953
other_branch, path = Branch.open_containing(branch)
1955
if len(revision) == 1:
1957
other_branch, path = Branch.open_containing(branch)
1958
revno = revision[0].in_history(other_branch).revno
1959
other = [branch, revno]
1961
assert len(revision) == 2
1962
if None in revision:
1963
raise BzrCommandError(
1964
"Merge doesn't permit that revision specifier.")
1965
b, path = Branch.open_containing(branch)
1967
base = [branch, revision[0].in_history(b).revno]
1968
other = [branch, revision[1].in_history(b).revno]
1970
interesting_files = [path]
1972
interesting_files = None
1973
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1976
conflict_count = merge(other, base, check_clean=(not force),
1977
merge_type=merge_type,
1978
reprocess=reprocess,
1979
show_base=show_base,
1980
pb=pb, file_list=interesting_files)
1983
if conflict_count != 0:
1987
except bzrlib.errors.AmbiguousBase, e:
1988
m = ("sorry, bzr can't determine the right merge base yet\n"
1989
"candidates are:\n "
1990
+ "\n ".join(e.bases)
1992
"please specify an explicit base with -r,\n"
1993
"and (if you want) report this to the bzr developers\n")
1997
class cmd_remerge(Command):
2000
takes_args = ['file*']
2001
takes_options = ['merge-type', 'reprocess',
2002
Option('show-base', help="Show base revision text in "
2005
def run(self, file_list=None, merge_type=None, show_base=False,
2007
from bzrlib.merge import merge_inner, transform_tree
2008
if merge_type is None:
2009
merge_type = Merge3Merger
2010
tree, file_list = tree_files(file_list)
2013
pending_merges = tree.pending_merges()
2014
if len(pending_merges) != 1:
2015
raise BzrCommandError("Sorry, remerge only works after normal"
2016
+ " merges. Not cherrypicking or"
2018
repository = tree.branch.repository
2019
base_revision = common_ancestor(tree.branch.last_revision(),
2020
pending_merges[0], repository)
2021
base_tree = repository.revision_tree(base_revision)
2022
other_tree = repository.revision_tree(pending_merges[0])
2023
interesting_ids = None
2024
if file_list is not None:
2025
interesting_ids = set()
2026
for filename in file_list:
2027
file_id = tree.path2id(filename)
2029
raise NotVersionedError(filename)
2030
interesting_ids.add(file_id)
2031
if tree.kind(file_id) != "directory":
2034
for name, ie in tree.inventory.iter_entries(file_id):
2035
interesting_ids.add(ie.file_id)
2036
transform_tree(tree, tree.basis_tree(), interesting_ids)
2037
if file_list is None:
2038
restore_files = list(tree.iter_conflicts())
2040
restore_files = file_list
2041
for filename in restore_files:
2043
restore(tree.abspath(filename))
2044
except NotConflicted:
2046
conflicts = merge_inner(tree.branch, other_tree, base_tree,
2048
interesting_ids = interesting_ids,
2049
other_rev_id=pending_merges[0],
2050
merge_type=merge_type,
2051
show_base=show_base,
2052
reprocess=reprocess)
2060
class cmd_revert(Command):
2061
"""Reverse all changes since the last commit.
2063
Only versioned files are affected. Specify filenames to revert only
2064
those files. By default, any files that are changed will be backed up
2065
first. Backup files have a '~' appended to their name.
2067
takes_options = ['revision', 'no-backup']
2068
takes_args = ['file*']
2069
aliases = ['merge-revert']
2071
def run(self, revision=None, no_backup=False, file_list=None):
2072
from bzrlib.commands import parse_spec
2073
if file_list is not None:
2074
if len(file_list) == 0:
2075
raise BzrCommandError("No files specified")
2079
tree, file_list = tree_files(file_list)
2080
if revision is None:
2081
# FIXME should be tree.last_revision
2082
rev_id = tree.last_revision()
2083
elif len(revision) != 1:
2084
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
2086
rev_id = revision[0].in_history(tree.branch).rev_id
2087
pb = bzrlib.ui.ui_factory.nested_progress_bar()
2089
tree.revert(file_list,
2090
tree.branch.repository.revision_tree(rev_id),
2096
class cmd_assert_fail(Command):
2097
"""Test reporting of assertion failures"""
2100
assert False, "always fails"
2103
class cmd_help(Command):
2104
"""Show help on a command or other topic.
2106
For a list of all available commands, say 'bzr help commands'."""
2107
takes_options = [Option('long', 'show help on all commands')]
2108
takes_args = ['topic?']
2109
aliases = ['?', '--help', '-?', '-h']
2112
def run(self, topic=None, long=False):
2114
if topic is None and long:
2119
class cmd_shell_complete(Command):
2120
"""Show appropriate completions for context.
2122
For a list of all available commands, say 'bzr shell-complete'."""
2123
takes_args = ['context?']
2128
def run(self, context=None):
2129
import shellcomplete
2130
shellcomplete.shellcomplete(context)
2133
class cmd_fetch(Command):
2134
"""Copy in history from another branch but don't merge it.
2136
This is an internal method used for pull and merge."""
2138
takes_args = ['from_branch', 'to_branch']
2139
def run(self, from_branch, to_branch):
2140
from bzrlib.fetch import Fetcher
2141
from bzrlib.branch import Branch
2142
from_b = Branch.open(from_branch)
2143
to_b = Branch.open(to_branch)
2144
Fetcher(to_b, from_b)
2147
class cmd_missing(Command):
2148
"""Show unmerged/unpulled revisions between two branches.
2150
OTHER_BRANCH may be local or remote."""
2151
takes_args = ['other_branch?']
2152
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2154
'Display changes in the local branch only'),
2155
Option('theirs-only',
2156
'Display changes in the remote branch only'),
2165
def run(self, other_branch=None, reverse=False, mine_only=False,
2166
theirs_only=False, log_format=None, long=False, short=False, line=False,
2167
show_ids=False, verbose=False):
2168
from bzrlib.missing import find_unmerged, iter_log_data
2169
from bzrlib.log import log_formatter
2170
local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
2171
parent = local_branch.get_parent()
2172
if other_branch is None:
2173
other_branch = parent
2174
if other_branch is None:
2175
raise BzrCommandError("No missing location known or specified.")
2176
print "Using last location: " + local_branch.get_parent()
2177
remote_branch = bzrlib.branch.Branch.open(other_branch)
2178
if remote_branch.base == local_branch.base:
2179
remote_branch = local_branch
2180
local_branch.lock_read()
2182
remote_branch.lock_read()
2184
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2185
if (log_format == None):
2186
default = bzrlib.config.BranchConfig(local_branch).log_format()
2187
log_format = get_log_format(long=long, short=short, line=line, default=default)
2188
lf = log_formatter(log_format, sys.stdout,
2190
show_timezone='original')
2191
if reverse is False:
2192
local_extra.reverse()
2193
remote_extra.reverse()
2194
if local_extra and not theirs_only:
2195
print "You have %d extra revision(s):" % len(local_extra)
2196
for data in iter_log_data(local_extra, local_branch.repository,
2199
printed_local = True
2201
printed_local = False
2202
if remote_extra and not mine_only:
2203
if printed_local is True:
2205
print "You are missing %d revision(s):" % len(remote_extra)
2206
for data in iter_log_data(remote_extra, remote_branch.repository,
2209
if not remote_extra and not local_extra:
2211
print "Branches are up to date."
2215
remote_branch.unlock()
2217
local_branch.unlock()
2218
if not status_code and parent is None and other_branch is not None:
2219
local_branch.lock_write()
2221
# handle race conditions - a parent might be set while we run.
2222
if local_branch.get_parent() is None:
2223
local_branch.set_parent(other_branch)
2225
local_branch.unlock()
2229
class cmd_plugins(Command):
2234
import bzrlib.plugin
2235
from inspect import getdoc
2236
for name, plugin in bzrlib.plugin.all_plugins().items():
2237
if hasattr(plugin, '__path__'):
2238
print plugin.__path__[0]
2239
elif hasattr(plugin, '__file__'):
2240
print plugin.__file__
2246
print '\t', d.split('\n')[0]
2249
class cmd_testament(Command):
2250
"""Show testament (signing-form) of a revision."""
2251
takes_options = ['revision', 'long']
2252
takes_args = ['branch?']
2254
def run(self, branch=u'.', revision=None, long=False):
2255
from bzrlib.testament import Testament
2256
b = WorkingTree.open_containing(branch)[0].branch
2259
if revision is None:
2260
rev_id = b.last_revision()
2262
rev_id = revision[0].in_history(b).rev_id
2263
t = Testament.from_revision(b.repository, rev_id)
2265
sys.stdout.writelines(t.as_text_lines())
2267
sys.stdout.write(t.as_short_text())
2272
class cmd_annotate(Command):
2273
"""Show the origin of each line in a file.
2275
This prints out the given file with an annotation on the left side
2276
indicating which revision, author and date introduced the change.
2278
If the origin is the same for a run of consecutive lines, it is
2279
shown only at the top, unless the --all option is given.
2281
# TODO: annotate directories; showing when each file was last changed
2282
# TODO: annotate a previous version of a file
2283
# TODO: if the working copy is modified, show annotations on that
2284
# with new uncommitted lines marked
2285
aliases = ['blame', 'praise']
2286
takes_args = ['filename']
2287
takes_options = [Option('all', help='show annotations on all lines'),
2288
Option('long', help='show date in annotations'),
2292
def run(self, filename, all=False, long=False):
2293
from bzrlib.annotate import annotate_file
2294
tree, relpath = WorkingTree.open_containing(filename)
2295
branch = tree.branch
2298
file_id = tree.inventory.path2id(relpath)
2299
tree = branch.repository.revision_tree(branch.last_revision())
2300
file_version = tree.inventory[file_id].revision
2301
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
2306
class cmd_re_sign(Command):
2307
"""Create a digital signature for an existing revision."""
2308
# TODO be able to replace existing ones.
2310
hidden = True # is this right ?
2311
takes_args = ['revision_id*']
2312
takes_options = ['revision']
2314
def run(self, revision_id_list=None, revision=None):
2315
import bzrlib.config as config
2316
import bzrlib.gpg as gpg
2317
if revision_id_list is not None and revision is not None:
2318
raise BzrCommandError('You can only supply one of revision_id or --revision')
2319
if revision_id_list is None and revision is None:
2320
raise BzrCommandError('You must supply either --revision or a revision_id')
2321
b = WorkingTree.open_containing(u'.')[0].branch
2322
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
2323
if revision_id_list is not None:
2324
for revision_id in revision_id_list:
2325
b.repository.sign_revision(revision_id, gpg_strategy)
2326
elif revision is not None:
2327
if len(revision) == 1:
2328
revno, rev_id = revision[0].in_history(b)
2329
b.repository.sign_revision(rev_id, gpg_strategy)
2330
elif len(revision) == 2:
2331
# are they both on rh- if so we can walk between them
2332
# might be nice to have a range helper for arbitrary
2333
# revision paths. hmm.
2334
from_revno, from_revid = revision[0].in_history(b)
2335
to_revno, to_revid = revision[1].in_history(b)
2336
if to_revid is None:
2337
to_revno = b.revno()
2338
if from_revno is None or to_revno is None:
2339
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
2340
for revno in range(from_revno, to_revno + 1):
2341
b.repository.sign_revision(b.get_rev_id(revno),
2344
raise BzrCommandError('Please supply either one revision, or a range.')
2347
class cmd_bind(Command):
2348
"""Bind the current branch to a master branch.
2350
After binding, commits must succeed on the master branch
2351
before they are executed on the local one.
2354
takes_args = ['location']
2357
def run(self, location=None):
2358
b, relpath = Branch.open_containing(u'.')
2359
b_other = Branch.open(location)
2362
except DivergedBranches:
2363
raise BzrCommandError('These branches have diverged.'
2364
' Try merging, and then bind again.')
2367
class cmd_unbind(Command):
2368
"""Bind the current branch to its parent.
2370
After unbinding, the local branch is considered independent.
2377
b, relpath = Branch.open_containing(u'.')
2379
raise BzrCommandError('Local branch is not bound')
2382
class cmd_uncommit(bzrlib.commands.Command):
2383
"""Remove the last committed revision.
2385
By supplying the --all flag, it will not only remove the entry
2386
from revision_history, but also remove all of the entries in the
2389
--verbose will print out what is being removed.
2390
--dry-run will go through all the motions, but not actually
2393
In the future, uncommit will create a changeset, which can then
2397
# TODO: jam 20060108 Add an option to allow uncommit to remove
2398
# unreferenced information in 'branch-as-repostory' branches.
2399
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
2400
# information in shared branches as well.
2401
takes_options = ['verbose', 'revision',
2402
Option('dry-run', help='Don\'t actually make changes'),
2403
Option('force', help='Say yes to all questions.')]
2404
takes_args = ['location?']
2407
def run(self, location=None,
2408
dry_run=False, verbose=False,
2409
revision=None, force=False):
2410
from bzrlib.branch import Branch
2411
from bzrlib.log import log_formatter
2413
from bzrlib.uncommit import uncommit
2415
if location is None:
2417
control, relpath = bzrdir.BzrDir.open_containing(location)
2419
tree = control.open_workingtree()
2421
except (errors.NoWorkingTree, errors.NotLocalUrl):
2423
b = control.open_branch()
2425
if revision is None:
2427
rev_id = b.last_revision()
2429
revno, rev_id = revision[0].in_history(b)
2431
print 'No revisions to uncommit.'
2433
for r in range(revno, b.revno()+1):
2434
rev_id = b.get_rev_id(r)
2435
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2436
lf.show(r, b.repository.get_revision(rev_id), None)
2439
print 'Dry-run, pretending to remove the above revisions.'
2441
val = raw_input('Press <enter> to continue')
2443
print 'The above revision(s) will be removed.'
2445
val = raw_input('Are you sure [y/N]? ')
2446
if val.lower() not in ('y', 'yes'):
2450
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
2454
class cmd_break_lock(Command):
2455
"""Break a dead lock on a repository, branch or working directory.
2457
CAUTION: Locks should only be broken when you are sure that the process
2458
holding the lock has been stopped.
2463
takes_args = ['location']
2464
takes_options = [Option('show',
2465
help="just show information on the lock, " \
2468
def run(self, location, show=False):
2469
raise NotImplementedError("sorry, break-lock is not complete yet; "
2470
"you can remove the 'held' directory manually to break the lock")
2473
# command-line interpretation helper for merge-related commands
2474
def merge(other_revision, base_revision,
2475
check_clean=True, ignore_zero=False,
2476
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2477
file_list=None, show_base=False, reprocess=False,
2478
pb=DummyProgress()):
2479
"""Merge changes into a tree.
2482
list(path, revno) Base for three-way merge.
2483
If [None, None] then a base will be automatically determined.
2485
list(path, revno) Other revision for three-way merge.
2487
Directory to merge changes into; '.' by default.
2489
If true, this_dir must have no uncommitted changes before the
2491
ignore_zero - If true, suppress the "zero conflicts" message when
2492
there are no conflicts; should be set when doing something we expect
2493
to complete perfectly.
2494
file_list - If supplied, merge only changes to selected files.
2496
All available ancestors of other_revision and base_revision are
2497
automatically pulled into the branch.
2499
The revno may be -1 to indicate the last revision on the branch, which is
2502
This function is intended for use from the command line; programmatic
2503
clients might prefer to call merge.merge_inner(), which has less magic
2506
from bzrlib.merge import Merger
2507
if this_dir is None:
2509
this_tree = WorkingTree.open_containing(this_dir)[0]
2510
if show_base and not merge_type is Merge3Merger:
2511
raise BzrCommandError("Show-base is not supported for this merge"
2512
" type. %s" % merge_type)
2513
if reprocess and not merge_type.supports_reprocess:
2514
raise BzrCommandError("Conflict reduction is not supported for merge"
2515
" type %s." % merge_type)
2516
if reprocess and show_base:
2517
raise BzrCommandError("Cannot do conflict reduction and show base.")
2519
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2520
merger.pp = ProgressPhase("Merge phase", 5, pb)
2521
merger.pp.next_phase()
2522
merger.check_basis(check_clean)
2523
merger.set_other(other_revision)
2524
merger.pp.next_phase()
2525
merger.set_base(base_revision)
2526
if merger.base_rev_id == merger.other_rev_id:
2527
note('Nothing to do.')
2529
merger.backup_files = backup_files
2530
merger.merge_type = merge_type
2531
merger.set_interesting_files(file_list)
2532
merger.show_base = show_base
2533
merger.reprocess = reprocess
2534
conflicts = merger.do_merge()
2535
if file_list is None:
2536
merger.set_pending()
2542
# these get imported and then picked up by the scan for cmd_*
2543
# TODO: Some more consistent way to split command definitions across files;
2544
# we do need to load at least some information about them to know of
2545
# aliases. ideally we would avoid loading the implementation until the
2546
# details were needed.
2547
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2548
from bzrlib.sign_my_commits import cmd_sign_my_commits
2549
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
2550
cmd_weave_plan_merge, cmd_weave_merge_text