1
# Copyright (C) 2004, 2005, 2006, 2007 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"""
20
from StringIO import StringIO
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
48
revision as _mod_revision,
56
from bzrlib.branch import Branch
57
from bzrlib.conflicts import ConflictList
58
from bzrlib.revisionspec import RevisionSpec
59
from bzrlib.smtp_connection import SMTPConnection
60
from bzrlib.workingtree import WorkingTree
63
from bzrlib.commands import Command, display_command
64
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
65
from bzrlib.progress import DummyProgress, ProgressPhase
66
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
69
def tree_files(file_list, default_branch=u'.'):
71
return internal_tree_files(file_list, default_branch)
72
except errors.FileInWrongBranch, e:
73
raise errors.BzrCommandError("%s is not in the same branch as %s" %
74
(e.path, file_list[0]))
77
# XXX: Bad function name; should possibly also be a class method of
78
# WorkingTree rather than a function.
79
def internal_tree_files(file_list, default_branch=u'.'):
80
"""Convert command-line paths to a WorkingTree and relative paths.
82
This is typically used for command-line processors that take one or
83
more filenames, and infer the workingtree that contains them.
85
The filenames given are not required to exist.
87
:param file_list: Filenames to convert.
89
:param default_branch: Fallback tree path to use if file_list is empty or
92
:return: workingtree, [relative_paths]
94
if file_list is None or len(file_list) == 0:
95
return WorkingTree.open_containing(default_branch)[0], file_list
96
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
98
for filename in file_list:
100
new_list.append(tree.relpath(osutils.dereference_path(filename)))
101
except errors.PathNotChild:
102
raise errors.FileInWrongBranch(tree.branch, filename)
103
return tree, new_list
106
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
107
def get_format_type(typestring):
108
"""Parse and return a format specifier."""
109
# Have to use BzrDirMetaFormat1 directly, so that
110
# RepositoryFormat.set_default_format works
111
if typestring == "default":
112
return bzrdir.BzrDirMetaFormat1()
114
return bzrdir.format_registry.make_bzrdir(typestring)
116
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
117
raise errors.BzrCommandError(msg)
120
# TODO: Make sure no commands unconditionally use the working directory as a
121
# branch. If a filename argument is used, the first of them should be used to
122
# specify the branch. (Perhaps this can be factored out into some kind of
123
# Argument class, representing a file in a branch, where the first occurrence
126
class cmd_status(Command):
127
"""Display status summary.
129
This reports on versioned and unknown files, reporting them
130
grouped by state. Possible states are:
133
Versioned in the working copy but not in the previous revision.
136
Versioned in the previous revision but removed or deleted
140
Path of this file changed from the previous revision;
141
the text may also have changed. This includes files whose
142
parent directory was renamed.
145
Text has changed since the previous revision.
148
File kind has been changed (e.g. from file to directory).
151
Not versioned and not matching an ignore pattern.
153
To see ignored files use 'bzr ignored'. For details on the
154
changes to file texts, use 'bzr diff'.
156
Note that --short or -S gives status flags for each item, similar
157
to Subversion's status command. To get output similar to svn -q,
160
If no arguments are specified, the status of the entire working
161
directory is shown. Otherwise, only the status of the specified
162
files or directories is reported. If a directory is given, status
163
is reported for everything inside that directory.
165
If a revision argument is given, the status is calculated against
166
that revision, or between two revisions if two are provided.
169
# TODO: --no-recurse, --recurse options
171
takes_args = ['file*']
172
takes_options = ['show-ids', 'revision', 'change',
173
Option('short', help='Use short status indicators.',
175
Option('versioned', help='Only show versioned files.',
178
aliases = ['st', 'stat']
180
encoding_type = 'replace'
181
_see_also = ['diff', 'revert', 'status-flags']
184
def run(self, show_ids=False, file_list=None, revision=None, short=False,
186
from bzrlib.status import show_tree_status
188
if revision and len(revision) > 2:
189
raise errors.BzrCommandError('bzr status --revision takes exactly'
190
' one or two revision specifiers')
192
tree, file_list = tree_files(file_list)
194
show_tree_status(tree, show_ids=show_ids,
195
specific_files=file_list, revision=revision,
196
to_file=self.outf, short=short, versioned=versioned)
199
class cmd_cat_revision(Command):
200
"""Write out metadata for a revision.
202
The revision to print can either be specified by a specific
203
revision identifier, or you can use --revision.
207
takes_args = ['revision_id?']
208
takes_options = ['revision']
209
# cat-revision is more for frontends so should be exact
213
def run(self, revision_id=None, revision=None):
215
revision_id = osutils.safe_revision_id(revision_id, warn=False)
216
if revision_id is not None and revision is not None:
217
raise errors.BzrCommandError('You can only supply one of'
218
' revision_id or --revision')
219
if revision_id is None and revision is None:
220
raise errors.BzrCommandError('You must supply either'
221
' --revision or a revision_id')
222
b = WorkingTree.open_containing(u'.')[0].branch
224
# TODO: jam 20060112 should cat-revision always output utf-8?
225
if revision_id is not None:
226
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
227
elif revision is not None:
230
raise errors.BzrCommandError('You cannot specify a NULL'
232
revno, rev_id = rev.in_history(b)
233
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
236
class cmd_remove_tree(Command):
237
"""Remove the working tree from a given branch/checkout.
239
Since a lightweight checkout is little more than a working tree
240
this will refuse to run against one.
242
To re-create the working tree, use "bzr checkout".
244
_see_also = ['checkout', 'working-trees']
246
takes_args = ['location?']
248
def run(self, location='.'):
249
d = bzrdir.BzrDir.open(location)
252
working = d.open_workingtree()
253
except errors.NoWorkingTree:
254
raise errors.BzrCommandError("No working tree to remove")
255
except errors.NotLocalUrl:
256
raise errors.BzrCommandError("You cannot remove the working tree of a "
259
working_path = working.bzrdir.root_transport.base
260
branch_path = working.branch.bzrdir.root_transport.base
261
if working_path != branch_path:
262
raise errors.BzrCommandError("You cannot remove the working tree from "
263
"a lightweight checkout")
265
d.destroy_workingtree()
268
class cmd_revno(Command):
269
"""Show current revision number.
271
This is equal to the number of revisions on this branch.
275
takes_args = ['location?']
278
def run(self, location=u'.'):
279
self.outf.write(str(Branch.open_containing(location)[0].revno()))
280
self.outf.write('\n')
283
class cmd_revision_info(Command):
284
"""Show revision number and revision id for a given revision identifier.
287
takes_args = ['revision_info*']
288
takes_options = ['revision']
291
def run(self, revision=None, revision_info_list=[]):
294
if revision is not None:
295
revs.extend(revision)
296
if revision_info_list is not None:
297
for rev in revision_info_list:
298
revs.append(RevisionSpec.from_string(rev))
300
b = Branch.open_containing(u'.')[0]
303
revs.append(RevisionSpec.from_string('-1'))
306
revinfo = rev.in_history(b)
307
if revinfo.revno is None:
308
dotted_map = b.get_revision_id_to_revno_map()
309
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
310
print '%s %s' % (revno, revinfo.rev_id)
312
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
315
class cmd_add(Command):
316
"""Add specified files or directories.
318
In non-recursive mode, all the named items are added, regardless
319
of whether they were previously ignored. A warning is given if
320
any of the named files are already versioned.
322
In recursive mode (the default), files are treated the same way
323
but the behaviour for directories is different. Directories that
324
are already versioned do not give a warning. All directories,
325
whether already versioned or not, are searched for files or
326
subdirectories that are neither versioned or ignored, and these
327
are added. This search proceeds recursively into versioned
328
directories. If no names are given '.' is assumed.
330
Therefore simply saying 'bzr add' will version all files that
331
are currently unknown.
333
Adding a file whose parent directory is not versioned will
334
implicitly add the parent, and so on up to the root. This means
335
you should never need to explicitly add a directory, they'll just
336
get added when you add a file in the directory.
338
--dry-run will show which files would be added, but not actually
341
--file-ids-from will try to use the file ids from the supplied path.
342
It looks up ids trying to find a matching parent directory with the
343
same filename, and then by pure path. This option is rarely needed
344
but can be useful when adding the same logical file into two
345
branches that will be merged later (without showing the two different
346
adds as a conflict). It is also useful when merging another project
347
into a subdirectory of this one.
349
takes_args = ['file*']
352
help="Don't recursively add the contents of directories."),
354
help="Show what would be done, but don't actually do anything."),
356
Option('file-ids-from',
358
help='Lookup file ids from this tree.'),
360
encoding_type = 'replace'
361
_see_also = ['remove']
363
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
368
if file_ids_from is not None:
370
base_tree, base_path = WorkingTree.open_containing(
372
except errors.NoWorkingTree:
373
base_branch, base_path = Branch.open_containing(
375
base_tree = base_branch.basis_tree()
377
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
378
to_file=self.outf, should_print=(not is_quiet()))
380
action = bzrlib.add.AddAction(to_file=self.outf,
381
should_print=(not is_quiet()))
384
base_tree.lock_read()
386
file_list = self._maybe_expand_globs(file_list)
388
tree = WorkingTree.open_containing(file_list[0])[0]
390
tree = WorkingTree.open_containing(u'.')[0]
391
added, ignored = tree.smart_add(file_list, not
392
no_recurse, action=action, save=not dry_run)
394
if base_tree is not None:
398
for glob in sorted(ignored.keys()):
399
for path in ignored[glob]:
400
self.outf.write("ignored %s matching \"%s\"\n"
404
for glob, paths in ignored.items():
405
match_len += len(paths)
406
self.outf.write("ignored %d file(s).\n" % match_len)
407
self.outf.write("If you wish to add some of these files,"
408
" please add them by name.\n")
411
class cmd_mkdir(Command):
412
"""Create a new versioned directory.
414
This is equivalent to creating the directory and then adding it.
417
takes_args = ['dir+']
418
encoding_type = 'replace'
420
def run(self, dir_list):
423
wt, dd = WorkingTree.open_containing(d)
425
self.outf.write('added %s\n' % d)
428
class cmd_relpath(Command):
429
"""Show path of a file relative to root"""
431
takes_args = ['filename']
435
def run(self, filename):
436
# TODO: jam 20050106 Can relpath return a munged path if
437
# sys.stdout encoding cannot represent it?
438
tree, relpath = WorkingTree.open_containing(filename)
439
self.outf.write(relpath)
440
self.outf.write('\n')
443
class cmd_inventory(Command):
444
"""Show inventory of the current working copy or a revision.
446
It is possible to limit the output to a particular entry
447
type using the --kind option. For example: --kind file.
449
It is also possible to restrict the list of files to a specific
450
set. For example: bzr inventory --show-ids this/file
459
help='List entries of a particular kind: file, directory, symlink.',
462
takes_args = ['file*']
465
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
466
if kind and kind not in ['file', 'directory', 'symlink']:
467
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
469
work_tree, file_list = tree_files(file_list)
470
work_tree.lock_read()
472
if revision is not None:
473
if len(revision) > 1:
474
raise errors.BzrCommandError(
475
'bzr inventory --revision takes exactly one revision'
477
revision_id = revision[0].in_history(work_tree.branch).rev_id
478
tree = work_tree.branch.repository.revision_tree(revision_id)
480
extra_trees = [work_tree]
486
if file_list is not None:
487
file_ids = tree.paths2ids(file_list, trees=extra_trees,
488
require_versioned=True)
489
# find_ids_across_trees may include some paths that don't
491
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
492
for file_id in file_ids if file_id in tree)
494
entries = tree.inventory.entries()
497
if tree is not work_tree:
500
for path, entry in entries:
501
if kind and kind != entry.kind:
504
self.outf.write('%-50s %s\n' % (path, entry.file_id))
506
self.outf.write(path)
507
self.outf.write('\n')
510
class cmd_mv(Command):
511
"""Move or rename a file.
514
bzr mv OLDNAME NEWNAME
516
bzr mv SOURCE... DESTINATION
518
If the last argument is a versioned directory, all the other names
519
are moved into it. Otherwise, there must be exactly two arguments
520
and the file is changed to a new name.
522
If OLDNAME does not exist on the filesystem but is versioned and
523
NEWNAME does exist on the filesystem but is not versioned, mv
524
assumes that the file has been manually moved and only updates
525
its internal inventory to reflect that change.
526
The same is valid when moving many SOURCE files to a DESTINATION.
528
Files cannot be moved between branches.
531
takes_args = ['names*']
532
takes_options = [Option("after", help="Move only the bzr identifier"
533
" of the file, because the file has already been moved."),
535
aliases = ['move', 'rename']
536
encoding_type = 'replace'
538
def run(self, names_list, after=False):
539
if names_list is None:
542
if len(names_list) < 2:
543
raise errors.BzrCommandError("missing file argument")
544
tree, rel_names = tree_files(names_list)
546
if os.path.isdir(names_list[-1]):
547
# move into existing directory
548
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
549
self.outf.write("%s => %s\n" % pair)
551
if len(names_list) != 2:
552
raise errors.BzrCommandError('to mv multiple files the'
553
' destination must be a versioned'
555
tree.rename_one(rel_names[0], rel_names[1], after=after)
556
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
559
class cmd_pull(Command):
560
"""Turn this branch into a mirror of another branch.
562
This command only works on branches that have not diverged. Branches are
563
considered diverged if the destination branch's most recent commit is one
564
that has not been merged (directly or indirectly) into the parent.
566
If branches have diverged, you can use 'bzr merge' to integrate the changes
567
from one into the other. Once one branch has merged, the other should
568
be able to pull it again.
570
If you want to forget your local changes and just update your branch to
571
match the remote one, use pull --overwrite.
573
If there is no default location set, the first pull will set it. After
574
that, you can omit the location to use the default. To change the
575
default, use --remember. The value will only be saved if the remote
576
location can be accessed.
579
_see_also = ['push', 'update', 'status-flags']
580
takes_options = ['remember', 'overwrite', 'revision',
581
custom_help('verbose',
582
help='Show logs of pulled revisions.'),
584
help='Branch to pull into, '
585
'rather than the one containing the working directory.',
590
takes_args = ['location?']
591
encoding_type = 'replace'
593
def run(self, location=None, remember=False, overwrite=False,
594
revision=None, verbose=False,
596
# FIXME: too much stuff is in the command class
599
if directory is None:
602
tree_to = WorkingTree.open_containing(directory)[0]
603
branch_to = tree_to.branch
604
except errors.NoWorkingTree:
606
branch_to = Branch.open_containing(directory)[0]
608
possible_transports = []
609
if location is not None:
610
mergeable, location_transport = _get_mergeable_helper(location)
611
possible_transports.append(location_transport)
613
stored_loc = branch_to.get_parent()
615
if stored_loc is None:
616
raise errors.BzrCommandError("No pull location known or"
619
display_url = urlutils.unescape_for_display(stored_loc,
621
self.outf.write("Using saved location: %s\n" % display_url)
622
location = stored_loc
623
location_transport = transport.get_transport(
624
location, possible_transports=possible_transports)
626
if mergeable is not None:
627
if revision is not None:
628
raise errors.BzrCommandError(
629
'Cannot use -r with merge directives or bundles')
630
mergeable.install_revisions(branch_to.repository)
631
base_revision_id, revision_id, verified = \
632
mergeable.get_merge_request(branch_to.repository)
633
branch_from = branch_to
635
branch_from = Branch.open_from_transport(location_transport)
637
if branch_to.get_parent() is None or remember:
638
branch_to.set_parent(branch_from.base)
640
if revision is not None:
641
if len(revision) == 1:
642
revision_id = revision[0].in_history(branch_from).rev_id
644
raise errors.BzrCommandError(
645
'bzr pull --revision takes one value.')
648
old_rh = branch_to.revision_history()
649
if tree_to is not None:
650
change_reporter = delta._ChangeReporter(
651
unversioned_filter=tree_to.is_ignored)
652
result = tree_to.pull(branch_from, overwrite, revision_id,
654
possible_transports=possible_transports)
656
result = branch_to.pull(branch_from, overwrite, revision_id)
658
result.report(self.outf)
660
new_rh = branch_to.revision_history()
661
log.show_changed_revisions(branch_to, old_rh, new_rh,
665
class cmd_push(Command):
666
"""Update a mirror of this branch.
668
The target branch will not have its working tree populated because this
669
is both expensive, and is not supported on remote file systems.
671
Some smart servers or protocols *may* put the working tree in place in
674
This command only works on branches that have not diverged. Branches are
675
considered diverged if the destination branch's most recent commit is one
676
that has not been merged (directly or indirectly) by the source branch.
678
If branches have diverged, you can use 'bzr push --overwrite' to replace
679
the other branch completely, discarding its unmerged changes.
681
If you want to ensure you have the different changes in the other branch,
682
do a merge (see bzr help merge) from the other branch, and commit that.
683
After that you will be able to do a push without '--overwrite'.
685
If there is no default push location set, the first push will set it.
686
After that, you can omit the location to use the default. To change the
687
default, use --remember. The value will only be saved if the remote
688
location can be accessed.
691
_see_also = ['pull', 'update', 'working-trees']
692
takes_options = ['remember', 'overwrite', 'verbose',
693
Option('create-prefix',
694
help='Create the path leading up to the branch '
695
'if it does not already exist.'),
697
help='Branch to push from, '
698
'rather than the one containing the working directory.',
702
Option('use-existing-dir',
703
help='By default push will fail if the target'
704
' directory exists, but does not already'
705
' have a control directory. This flag will'
706
' allow push to proceed.'),
708
takes_args = ['location?']
709
encoding_type = 'replace'
711
def run(self, location=None, remember=False, overwrite=False,
712
create_prefix=False, verbose=False,
713
use_existing_dir=False,
715
# FIXME: Way too big! Put this into a function called from the
717
if directory is None:
719
br_from = Branch.open_containing(directory)[0]
720
stored_loc = br_from.get_push_location()
722
if stored_loc is None:
723
raise errors.BzrCommandError("No push location known or specified.")
725
display_url = urlutils.unescape_for_display(stored_loc,
727
self.outf.write("Using saved location: %s\n" % display_url)
728
location = stored_loc
730
to_transport = transport.get_transport(location)
732
br_to = repository_to = dir_to = None
734
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
735
except errors.NotBranchError:
736
pass # Didn't find anything
738
# If we can open a branch, use its direct repository, otherwise see
739
# if there is a repository without a branch.
741
br_to = dir_to.open_branch()
742
except errors.NotBranchError:
743
# Didn't find a branch, can we find a repository?
745
repository_to = dir_to.find_repository()
746
except errors.NoRepositoryPresent:
749
# Found a branch, so we must have found a repository
750
repository_to = br_to.repository
755
# The destination doesn't exist; create it.
756
# XXX: Refactor the create_prefix/no_create_prefix code into a
757
# common helper function
759
to_transport.mkdir('.')
760
except errors.FileExists:
761
if not use_existing_dir:
762
raise errors.BzrCommandError("Target directory %s"
763
" already exists, but does not have a valid .bzr"
764
" directory. Supply --use-existing-dir to push"
765
" there anyway." % location)
766
except errors.NoSuchFile:
767
if not create_prefix:
768
raise errors.BzrCommandError("Parent directory of %s"
770
"\nYou may supply --create-prefix to create all"
771
" leading parent directories."
773
_create_prefix(to_transport)
775
# Now the target directory exists, but doesn't have a .bzr
776
# directory. So we need to create it, along with any work to create
777
# all of the dependent branches, etc.
778
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
779
revision_id=br_from.last_revision())
780
br_to = dir_to.open_branch()
781
# TODO: Some more useful message about what was copied
782
note('Created new branch.')
783
# We successfully created the target, remember it
784
if br_from.get_push_location() is None or remember:
785
br_from.set_push_location(br_to.base)
786
elif repository_to is None:
787
# we have a bzrdir but no branch or repository
788
# XXX: Figure out what to do other than complain.
789
raise errors.BzrCommandError("At %s you have a valid .bzr control"
790
" directory, but not a branch or repository. This is an"
791
" unsupported configuration. Please move the target directory"
792
" out of the way and try again."
795
# We have a repository but no branch, copy the revisions, and then
797
last_revision_id = br_from.last_revision()
798
repository_to.fetch(br_from.repository,
799
revision_id=last_revision_id)
800
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
801
note('Created new branch.')
802
if br_from.get_push_location() is None or remember:
803
br_from.set_push_location(br_to.base)
804
else: # We have a valid to branch
805
# We were able to connect to the remote location, so remember it
806
# we don't need to successfully push because of possible divergence.
807
if br_from.get_push_location() is None or remember:
808
br_from.set_push_location(br_to.base)
810
old_rh = br_to.revision_history()
813
tree_to = dir_to.open_workingtree()
814
except errors.NotLocalUrl:
815
warning("This transport does not update the working "
816
"tree of: %s. See 'bzr help working-trees' for "
817
"more information." % br_to.base)
818
push_result = br_from.push(br_to, overwrite)
819
except errors.NoWorkingTree:
820
push_result = br_from.push(br_to, overwrite)
824
push_result = br_from.push(tree_to.branch, overwrite)
828
except errors.DivergedBranches:
829
raise errors.BzrCommandError('These branches have diverged.'
830
' Try using "merge" and then "push".')
831
if push_result is not None:
832
push_result.report(self.outf)
834
new_rh = br_to.revision_history()
837
from bzrlib.log import show_changed_revisions
838
show_changed_revisions(br_to, old_rh, new_rh,
841
# we probably did a clone rather than a push, so a message was
846
class cmd_branch(Command):
847
"""Create a new copy of a branch.
849
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
850
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
851
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
852
is derived from the FROM_LOCATION by stripping a leading scheme or drive
853
identifier, if any. For example, "branch lp:foo-bar" will attempt to
856
To retrieve the branch as of a particular revision, supply the --revision
857
parameter, as in "branch foo/bar -r 5".
860
_see_also = ['checkout']
861
takes_args = ['from_location', 'to_location?']
862
takes_options = ['revision']
863
aliases = ['get', 'clone']
865
def run(self, from_location, to_location=None, revision=None):
866
from bzrlib.tag import _merge_tags_if_possible
869
elif len(revision) > 1:
870
raise errors.BzrCommandError(
871
'bzr branch --revision takes exactly 1 revision value')
873
br_from = Branch.open(from_location)
876
if len(revision) == 1 and revision[0] is not None:
877
revision_id = revision[0].in_history(br_from)[1]
879
# FIXME - wt.last_revision, fallback to branch, fall back to
880
# None or perhaps NULL_REVISION to mean copy nothing
882
revision_id = br_from.last_revision()
883
if to_location is None:
884
to_location = urlutils.derive_to_location(from_location)
887
name = os.path.basename(to_location) + '\n'
889
to_transport = transport.get_transport(to_location)
891
to_transport.mkdir('.')
892
except errors.FileExists:
893
raise errors.BzrCommandError('Target directory "%s" already'
894
' exists.' % to_location)
895
except errors.NoSuchFile:
896
raise errors.BzrCommandError('Parent of "%s" does not exist.'
899
# preserve whatever source format we have.
900
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
901
possible_transports=[to_transport])
902
branch = dir.open_branch()
903
except errors.NoSuchRevision:
904
to_transport.delete_tree('.')
905
msg = "The branch %s has no revision %s." % (from_location, revision[0])
906
raise errors.BzrCommandError(msg)
908
branch.control_files.put_utf8('branch-name', name)
909
_merge_tags_if_possible(br_from, branch)
910
note('Branched %d revision(s).' % branch.revno())
915
class cmd_checkout(Command):
916
"""Create a new checkout of an existing branch.
918
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
919
the branch found in '.'. This is useful if you have removed the working tree
920
or if it was never created - i.e. if you pushed the branch to its current
923
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
924
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
925
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
926
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
927
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
930
To retrieve the branch as of a particular revision, supply the --revision
931
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
932
out of date [so you cannot commit] but it may be useful (i.e. to examine old
936
_see_also = ['checkouts', 'branch']
937
takes_args = ['branch_location?', 'to_location?']
938
takes_options = ['revision',
939
Option('lightweight',
940
help="Perform a lightweight checkout. Lightweight "
941
"checkouts depend on access to the branch for "
942
"every operation. Normal checkouts can perform "
943
"common operations like diff and status without "
944
"such access, and also support local commits."
949
def run(self, branch_location=None, to_location=None, revision=None,
953
elif len(revision) > 1:
954
raise errors.BzrCommandError(
955
'bzr checkout --revision takes exactly 1 revision value')
956
if branch_location is None:
957
branch_location = osutils.getcwd()
958
to_location = branch_location
959
source = Branch.open(branch_location)
960
if len(revision) == 1 and revision[0] is not None:
961
revision_id = _mod_revision.ensure_null(
962
revision[0].in_history(source)[1])
965
if to_location is None:
966
to_location = urlutils.derive_to_location(branch_location)
967
# if the source and to_location are the same,
968
# and there is no working tree,
969
# then reconstitute a branch
970
if (osutils.abspath(to_location) ==
971
osutils.abspath(branch_location)):
973
source.bzrdir.open_workingtree()
974
except errors.NoWorkingTree:
975
source.bzrdir.create_workingtree(revision_id)
977
source.create_checkout(to_location, revision_id, lightweight)
980
class cmd_renames(Command):
981
"""Show list of renamed files.
983
# TODO: Option to show renames between two historical versions.
985
# TODO: Only show renames under dir, rather than in the whole branch.
986
_see_also = ['status']
987
takes_args = ['dir?']
990
def run(self, dir=u'.'):
991
tree = WorkingTree.open_containing(dir)[0]
994
new_inv = tree.inventory
995
old_tree = tree.basis_tree()
998
old_inv = old_tree.inventory
999
renames = list(_mod_tree.find_renames(old_inv, new_inv))
1001
for old_name, new_name in renames:
1002
self.outf.write("%s => %s\n" % (old_name, new_name))
1009
class cmd_update(Command):
1010
"""Update a tree to have the latest code committed to its branch.
1012
This will perform a merge into the working tree, and may generate
1013
conflicts. If you have any local changes, you will still
1014
need to commit them after the update for the update to be complete.
1016
If you want to discard your local changes, you can just do a
1017
'bzr revert' instead of 'bzr commit' after the update.
1020
_see_also = ['pull', 'working-trees', 'status-flags']
1021
takes_args = ['dir?']
1024
def run(self, dir='.'):
1025
tree = WorkingTree.open_containing(dir)[0]
1026
possible_transports = []
1027
master = tree.branch.get_master_branch(
1028
possible_transports=possible_transports)
1029
if master is not None:
1032
tree.lock_tree_write()
1034
existing_pending_merges = tree.get_parent_ids()[1:]
1035
last_rev = _mod_revision.ensure_null(tree.last_revision())
1036
if last_rev == _mod_revision.ensure_null(
1037
tree.branch.last_revision()):
1038
# may be up to date, check master too.
1039
if master is None or last_rev == _mod_revision.ensure_null(
1040
master.last_revision()):
1041
revno = tree.branch.revision_id_to_revno(last_rev)
1042
note("Tree is up to date at revision %d." % (revno,))
1044
conflicts = tree.update(
1045
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1046
possible_transports=possible_transports)
1047
revno = tree.branch.revision_id_to_revno(
1048
_mod_revision.ensure_null(tree.last_revision()))
1049
note('Updated to revision %d.' % (revno,))
1050
if tree.get_parent_ids()[1:] != existing_pending_merges:
1051
note('Your local commits will now show as pending merges with '
1052
"'bzr status', and can be committed with 'bzr commit'.")
1061
class cmd_info(Command):
1062
"""Show information about a working tree, branch or repository.
1064
This command will show all known locations and formats associated to the
1065
tree, branch or repository. Statistical information is included with
1068
Branches and working trees will also report any missing revisions.
1070
_see_also = ['revno', 'working-trees', 'repositories']
1071
takes_args = ['location?']
1072
takes_options = ['verbose']
1075
def run(self, location=None, verbose=False):
1080
from bzrlib.info import show_bzrdir_info
1081
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1082
verbose=noise_level)
1085
class cmd_remove(Command):
1086
"""Remove files or directories.
1088
This makes bzr stop tracking changes to the specified files and
1089
delete them if they can easily be recovered using revert.
1091
You can specify one or more files, and/or --new. If you specify --new,
1092
only 'added' files will be removed. If you specify both, then new files
1093
in the specified directories will be removed. If the directories are
1094
also new, they will also be removed.
1096
takes_args = ['file*']
1097
takes_options = ['verbose',
1098
Option('new', help='Remove newly-added files.'),
1099
RegistryOption.from_kwargs('file-deletion-strategy',
1100
'The file deletion mode to be used.',
1101
title='Deletion Strategy', value_switches=True, enum_switch=False,
1102
safe='Only delete files if they can be'
1103
' safely recovered (default).',
1104
keep="Don't delete any files.",
1105
force='Delete all the specified files, even if they can not be '
1106
'recovered and even if they are non-empty directories.')]
1108
encoding_type = 'replace'
1110
def run(self, file_list, verbose=False, new=False,
1111
file_deletion_strategy='safe'):
1112
tree, file_list = tree_files(file_list)
1114
if file_list is not None:
1115
file_list = [f for f in file_list]
1117
raise errors.BzrCommandError('Specify one or more files to'
1118
' remove, or use --new.')
1121
added = tree.changes_from(tree.basis_tree(),
1122
specific_files=file_list).added
1123
file_list = sorted([f[0] for f in added], reverse=True)
1124
if len(file_list) == 0:
1125
raise errors.BzrCommandError('No matching files.')
1126
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1127
keep_files=file_deletion_strategy=='keep',
1128
force=file_deletion_strategy=='force')
1131
class cmd_file_id(Command):
1132
"""Print file_id of a particular file or directory.
1134
The file_id is assigned when the file is first added and remains the
1135
same through all revisions where the file exists, even when it is
1140
_see_also = ['inventory', 'ls']
1141
takes_args = ['filename']
1144
def run(self, filename):
1145
tree, relpath = WorkingTree.open_containing(filename)
1146
i = tree.path2id(relpath)
1148
raise errors.NotVersionedError(filename)
1150
self.outf.write(i + '\n')
1153
class cmd_file_path(Command):
1154
"""Print path of file_ids to a file or directory.
1156
This prints one line for each directory down to the target,
1157
starting at the branch root.
1161
takes_args = ['filename']
1164
def run(self, filename):
1165
tree, relpath = WorkingTree.open_containing(filename)
1166
fid = tree.path2id(relpath)
1168
raise errors.NotVersionedError(filename)
1169
segments = osutils.splitpath(relpath)
1170
for pos in range(1, len(segments) + 1):
1171
path = osutils.joinpath(segments[:pos])
1172
self.outf.write("%s\n" % tree.path2id(path))
1175
class cmd_reconcile(Command):
1176
"""Reconcile bzr metadata in a branch.
1178
This can correct data mismatches that may have been caused by
1179
previous ghost operations or bzr upgrades. You should only
1180
need to run this command if 'bzr check' or a bzr developer
1181
advises you to run it.
1183
If a second branch is provided, cross-branch reconciliation is
1184
also attempted, which will check that data like the tree root
1185
id which was not present in very early bzr versions is represented
1186
correctly in both branches.
1188
At the same time it is run it may recompress data resulting in
1189
a potential saving in disk space or performance gain.
1191
The branch *MUST* be on a listable system such as local disk or sftp.
1194
_see_also = ['check']
1195
takes_args = ['branch?']
1197
def run(self, branch="."):
1198
from bzrlib.reconcile import reconcile
1199
dir = bzrdir.BzrDir.open(branch)
1203
class cmd_revision_history(Command):
1204
"""Display the list of revision ids on a branch."""
1207
takes_args = ['location?']
1212
def run(self, location="."):
1213
branch = Branch.open_containing(location)[0]
1214
for revid in branch.revision_history():
1215
self.outf.write(revid)
1216
self.outf.write('\n')
1219
class cmd_ancestry(Command):
1220
"""List all revisions merged into this branch."""
1222
_see_also = ['log', 'revision-history']
1223
takes_args = ['location?']
1228
def run(self, location="."):
1230
wt = WorkingTree.open_containing(location)[0]
1231
except errors.NoWorkingTree:
1232
b = Branch.open(location)
1233
last_revision = b.last_revision()
1236
last_revision = wt.last_revision()
1238
revision_ids = b.repository.get_ancestry(last_revision)
1239
assert revision_ids[0] is None
1241
for revision_id in revision_ids:
1242
self.outf.write(revision_id + '\n')
1245
class cmd_init(Command):
1246
"""Make a directory into a versioned branch.
1248
Use this to create an empty branch, or before importing an
1251
If there is a repository in a parent directory of the location, then
1252
the history of the branch will be stored in the repository. Otherwise
1253
init creates a standalone branch which carries its own history
1254
in the .bzr directory.
1256
If there is already a branch at the location but it has no working tree,
1257
the tree can be populated with 'bzr checkout'.
1259
Recipe for importing a tree of files::
1265
bzr commit -m 'imported project'
1268
_see_also = ['init-repository', 'branch', 'checkout']
1269
takes_args = ['location?']
1271
Option('create-prefix',
1272
help='Create the path leading up to the branch '
1273
'if it does not already exist.'),
1274
RegistryOption('format',
1275
help='Specify a format for this branch. '
1276
'See "help formats".',
1277
registry=bzrdir.format_registry,
1278
converter=bzrdir.format_registry.make_bzrdir,
1279
value_switches=True,
1280
title="Branch Format",
1282
Option('append-revisions-only',
1283
help='Never change revnos or the existing log.'
1284
' Append revisions to it only.')
1286
def run(self, location=None, format=None, append_revisions_only=False,
1287
create_prefix=False):
1289
format = bzrdir.format_registry.make_bzrdir('default')
1290
if location is None:
1293
to_transport = transport.get_transport(location)
1295
# The path has to exist to initialize a
1296
# branch inside of it.
1297
# Just using os.mkdir, since I don't
1298
# believe that we want to create a bunch of
1299
# locations if the user supplies an extended path
1301
to_transport.ensure_base()
1302
except errors.NoSuchFile:
1303
if not create_prefix:
1304
raise errors.BzrCommandError("Parent directory of %s"
1306
"\nYou may supply --create-prefix to create all"
1307
" leading parent directories."
1309
_create_prefix(to_transport)
1312
existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1313
except errors.NotBranchError:
1314
# really a NotBzrDir error...
1315
create_branch = bzrdir.BzrDir.create_branch_convenience
1316
branch = create_branch(to_transport.base, format=format,
1317
possible_transports=[to_transport])
1319
from bzrlib.transport.local import LocalTransport
1320
if existing_bzrdir.has_branch():
1321
if (isinstance(to_transport, LocalTransport)
1322
and not existing_bzrdir.has_workingtree()):
1323
raise errors.BranchExistsWithoutWorkingTree(location)
1324
raise errors.AlreadyBranchError(location)
1326
branch = existing_bzrdir.create_branch()
1327
existing_bzrdir.create_workingtree()
1328
if append_revisions_only:
1330
branch.set_append_revisions_only(True)
1331
except errors.UpgradeRequired:
1332
raise errors.BzrCommandError('This branch format cannot be set'
1333
' to append-revisions-only. Try --experimental-branch6')
1336
class cmd_init_repository(Command):
1337
"""Create a shared repository to hold branches.
1339
New branches created under the repository directory will store their
1340
revisions in the repository, not in the branch directory.
1342
If the --no-trees option is used then the branches in the repository
1343
will not have working trees by default.
1346
Create a shared repositories holding just branches::
1348
bzr init-repo --no-trees repo
1351
Make a lightweight checkout elsewhere::
1353
bzr checkout --lightweight repo/trunk trunk-checkout
1358
_see_also = ['init', 'branch', 'checkout', 'repositories']
1359
takes_args = ["location"]
1360
takes_options = [RegistryOption('format',
1361
help='Specify a format for this repository. See'
1362
' "bzr help formats" for details.',
1363
registry=bzrdir.format_registry,
1364
converter=bzrdir.format_registry.make_bzrdir,
1365
value_switches=True, title='Repository format'),
1367
help='Branches in the repository will default to'
1368
' not having a working tree.'),
1370
aliases = ["init-repo"]
1372
def run(self, location, format=None, no_trees=False):
1374
format = bzrdir.format_registry.make_bzrdir('default')
1376
if location is None:
1379
to_transport = transport.get_transport(location)
1380
to_transport.ensure_base()
1382
newdir = format.initialize_on_transport(to_transport)
1383
repo = newdir.create_repository(shared=True)
1384
repo.set_make_working_trees(not no_trees)
1387
class cmd_diff(Command):
1388
"""Show differences in the working tree or between revisions.
1390
If files are listed, only the changes in those files are listed.
1391
Otherwise, all changes for the tree are listed.
1393
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1394
produces patches suitable for "patch -p1".
1397
Shows the difference in the working tree versus the last commit::
1401
Difference between the working tree and revision 1::
1405
Difference between revision 2 and revision 1::
1409
Same as 'bzr diff' but prefix paths with old/ and new/::
1411
bzr diff --prefix old/:new/
1413
Show the differences between the two working trees::
1415
bzr diff bzr.mine bzr.dev
1417
Show just the differences for 'foo.c'::
1421
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1422
# or a graphical diff.
1424
# TODO: Python difflib is not exactly the same as unidiff; should
1425
# either fix it up or prefer to use an external diff.
1427
# TODO: Selected-file diff is inefficient and doesn't show you
1430
# TODO: This probably handles non-Unix newlines poorly.
1432
_see_also = ['status']
1433
takes_args = ['file*']
1435
Option('diff-options', type=str,
1436
help='Pass these options to the external diff program.'),
1437
Option('prefix', type=str,
1439
help='Set prefixes added to old and new filenames, as '
1440
'two values separated by a colon. (eg "old/:new/").'),
1444
aliases = ['di', 'dif']
1445
encoding_type = 'exact'
1448
def run(self, revision=None, file_list=None, diff_options=None,
1450
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1452
if (prefix is None) or (prefix == '0'):
1460
old_label, new_label = prefix.split(":")
1462
raise errors.BzrCommandError(
1463
'--prefix expects two values separated by a colon'
1464
' (eg "old/:new/")')
1466
if revision and len(revision) > 2:
1467
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1468
' one or two revision specifiers')
1471
tree1, file_list = internal_tree_files(file_list)
1475
except errors.FileInWrongBranch:
1476
if len(file_list) != 2:
1477
raise errors.BzrCommandError("Files are in different branches")
1479
tree1, file1 = WorkingTree.open_containing(file_list[0])
1480
tree2, file2 = WorkingTree.open_containing(file_list[1])
1481
if file1 != "" or file2 != "":
1482
# FIXME diff those two files. rbc 20051123
1483
raise errors.BzrCommandError("Files are in different branches")
1485
except errors.NotBranchError:
1486
if (revision is not None and len(revision) == 2
1487
and not revision[0].needs_branch()
1488
and not revision[1].needs_branch()):
1489
# If both revision specs include a branch, we can
1490
# diff them without needing a local working tree
1491
tree1, tree2 = None, None
1495
if tree2 is not None:
1496
if revision is not None:
1497
# FIXME: but there should be a clean way to diff between
1498
# non-default versions of two trees, it's not hard to do
1500
raise errors.BzrCommandError(
1501
"Sorry, diffing arbitrary revisions across branches "
1502
"is not implemented yet")
1503
return show_diff_trees(tree1, tree2, sys.stdout,
1504
specific_files=file_list,
1505
external_diff_options=diff_options,
1506
old_label=old_label, new_label=new_label)
1508
return diff_cmd_helper(tree1, file_list, diff_options,
1509
revision_specs=revision,
1510
old_label=old_label, new_label=new_label)
1513
class cmd_deleted(Command):
1514
"""List files deleted in the working tree.
1516
# TODO: Show files deleted since a previous revision, or
1517
# between two revisions.
1518
# TODO: Much more efficient way to do this: read in new
1519
# directories with readdir, rather than stating each one. Same
1520
# level of effort but possibly much less IO. (Or possibly not,
1521
# if the directories are very large...)
1522
_see_also = ['status', 'ls']
1523
takes_options = ['show-ids']
1526
def run(self, show_ids=False):
1527
tree = WorkingTree.open_containing(u'.')[0]
1530
old = tree.basis_tree()
1533
for path, ie in old.inventory.iter_entries():
1534
if not tree.has_id(ie.file_id):
1535
self.outf.write(path)
1537
self.outf.write(' ')
1538
self.outf.write(ie.file_id)
1539
self.outf.write('\n')
1546
class cmd_modified(Command):
1547
"""List files modified in working tree.
1551
_see_also = ['status', 'ls']
1555
tree = WorkingTree.open_containing(u'.')[0]
1556
td = tree.changes_from(tree.basis_tree())
1557
for path, id, kind, text_modified, meta_modified in td.modified:
1558
self.outf.write(path + '\n')
1561
class cmd_added(Command):
1562
"""List files added in working tree.
1566
_see_also = ['status', 'ls']
1570
wt = WorkingTree.open_containing(u'.')[0]
1573
basis = wt.basis_tree()
1576
basis_inv = basis.inventory
1579
if file_id in basis_inv:
1581
if inv.is_root(file_id) and len(basis_inv) == 0:
1583
path = inv.id2path(file_id)
1584
if not os.access(osutils.abspath(path), os.F_OK):
1586
self.outf.write(path + '\n')
1593
class cmd_root(Command):
1594
"""Show the tree root directory.
1596
The root is the nearest enclosing directory with a .bzr control
1599
takes_args = ['filename?']
1601
def run(self, filename=None):
1602
"""Print the branch root."""
1603
tree = WorkingTree.open_containing(filename)[0]
1604
self.outf.write(tree.basedir + '\n')
1607
def _parse_limit(limitstring):
1609
return int(limitstring)
1611
msg = "The limit argument must be an integer."
1612
raise errors.BzrCommandError(msg)
1615
class cmd_log(Command):
1616
"""Show log of a branch, file, or directory.
1618
By default show the log of the branch containing the working directory.
1620
To request a range of logs, you can use the command -r begin..end
1621
-r revision requests a specific revision, -r ..end or -r begin.. are
1625
Log the current branch::
1633
Log the last 10 revisions of a branch::
1635
bzr log -r -10.. http://server/branch
1638
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1640
takes_args = ['location?']
1643
help='Show from oldest to newest.'),
1646
help='Display timezone as local, original, or utc.'),
1647
custom_help('verbose',
1648
help='Show files changed in each revision.'),
1654
help='Show revisions whose message matches this '
1655
'regular expression.',
1658
help='Limit the output to the first N revisions.',
1662
encoding_type = 'replace'
1665
def run(self, location=None, timezone='original',
1673
from bzrlib.log import show_log
1674
assert message is None or isinstance(message, basestring), \
1675
"invalid message argument %r" % message
1676
direction = (forward and 'forward') or 'reverse'
1681
# find the file id to log:
1683
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1687
tree = b.basis_tree()
1688
file_id = tree.path2id(fp)
1690
raise errors.BzrCommandError(
1691
"Path does not have any revision history: %s" %
1695
# FIXME ? log the current subdir only RBC 20060203
1696
if revision is not None \
1697
and len(revision) > 0 and revision[0].get_branch():
1698
location = revision[0].get_branch()
1701
dir, relpath = bzrdir.BzrDir.open_containing(location)
1702
b = dir.open_branch()
1706
if revision is None:
1709
elif len(revision) == 1:
1710
rev1 = rev2 = revision[0].in_history(b)
1711
elif len(revision) == 2:
1712
if revision[1].get_branch() != revision[0].get_branch():
1713
# b is taken from revision[0].get_branch(), and
1714
# show_log will use its revision_history. Having
1715
# different branches will lead to weird behaviors.
1716
raise errors.BzrCommandError(
1717
"Log doesn't accept two revisions in different"
1719
rev1 = revision[0].in_history(b)
1720
rev2 = revision[1].in_history(b)
1722
raise errors.BzrCommandError(
1723
'bzr log --revision takes one or two values.')
1725
if log_format is None:
1726
log_format = log.log_formatter_registry.get_default(b)
1728
lf = log_format(show_ids=show_ids, to_file=self.outf,
1729
show_timezone=timezone)
1735
direction=direction,
1736
start_revision=rev1,
1744
def get_log_format(long=False, short=False, line=False, default='long'):
1745
log_format = default
1749
log_format = 'short'
1755
class cmd_touching_revisions(Command):
1756
"""Return revision-ids which affected a particular file.
1758
A more user-friendly interface is "bzr log FILE".
1762
takes_args = ["filename"]
1765
def run(self, filename):
1766
tree, relpath = WorkingTree.open_containing(filename)
1768
file_id = tree.path2id(relpath)
1769
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1770
self.outf.write("%6d %s\n" % (revno, what))
1773
class cmd_ls(Command):
1774
"""List files in a tree.
1777
_see_also = ['status', 'cat']
1778
takes_args = ['path?']
1779
# TODO: Take a revision or remote path and list that tree instead.
1783
Option('non-recursive',
1784
help='Don\'t recurse into subdirectories.'),
1786
help='Print paths relative to the root of the branch.'),
1787
Option('unknown', help='Print unknown files.'),
1788
Option('versioned', help='Print versioned files.'),
1789
Option('ignored', help='Print ignored files.'),
1791
help='Write an ascii NUL (\\0) separator '
1792
'between files rather than a newline.'),
1794
help='List entries of a particular kind: file, directory, symlink.',
1799
def run(self, revision=None, verbose=False,
1800
non_recursive=False, from_root=False,
1801
unknown=False, versioned=False, ignored=False,
1802
null=False, kind=None, show_ids=False, path=None):
1804
if kind and kind not in ('file', 'directory', 'symlink'):
1805
raise errors.BzrCommandError('invalid kind specified')
1807
if verbose and null:
1808
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1809
all = not (unknown or versioned or ignored)
1811
selection = {'I':ignored, '?':unknown, 'V':versioned}
1818
raise errors.BzrCommandError('cannot specify both --from-root'
1822
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1828
if revision is not None:
1829
tree = branch.repository.revision_tree(
1830
revision[0].in_history(branch).rev_id)
1832
tree = branch.basis_tree()
1836
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1837
if fp.startswith(relpath):
1838
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1839
if non_recursive and '/' in fp:
1841
if not all and not selection[fc]:
1843
if kind is not None and fkind != kind:
1846
kindch = entry.kind_character()
1847
outstring = '%-8s %s%s' % (fc, fp, kindch)
1848
if show_ids and fid is not None:
1849
outstring = "%-50s %s" % (outstring, fid)
1850
self.outf.write(outstring + '\n')
1852
self.outf.write(fp + '\0')
1855
self.outf.write(fid)
1856
self.outf.write('\0')
1864
self.outf.write('%-50s %s\n' % (fp, my_id))
1866
self.outf.write(fp + '\n')
1871
class cmd_unknowns(Command):
1872
"""List unknown files.
1880
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1881
self.outf.write(osutils.quotefn(f) + '\n')
1884
class cmd_ignore(Command):
1885
"""Ignore specified files or patterns.
1887
To remove patterns from the ignore list, edit the .bzrignore file.
1889
Trailing slashes on patterns are ignored.
1890
If the pattern contains a slash or is a regular expression, it is compared
1891
to the whole path from the branch root. Otherwise, it is compared to only
1892
the last component of the path. To match a file only in the root
1893
directory, prepend './'.
1895
Ignore patterns specifying absolute paths are not allowed.
1897
Ignore patterns may include globbing wildcards such as::
1899
? - Matches any single character except '/'
1900
* - Matches 0 or more characters except '/'
1901
/**/ - Matches 0 or more directories in a path
1902
[a-z] - Matches a single character from within a group of characters
1904
Ignore patterns may also be Python regular expressions.
1905
Regular expression ignore patterns are identified by a 'RE:' prefix
1906
followed by the regular expression. Regular expression ignore patterns
1907
may not include named or numbered groups.
1909
Note: ignore patterns containing shell wildcards must be quoted from
1913
Ignore the top level Makefile::
1915
bzr ignore ./Makefile
1917
Ignore class files in all directories::
1919
bzr ignore '*.class'
1921
Ignore .o files under the lib directory::
1923
bzr ignore 'lib/**/*.o'
1925
Ignore .o files under the lib directory::
1927
bzr ignore 'RE:lib/.*\.o'
1930
_see_also = ['status', 'ignored']
1931
takes_args = ['name_pattern*']
1933
Option('old-default-rules',
1934
help='Write out the ignore rules bzr < 0.9 always used.')
1937
def run(self, name_pattern_list=None, old_default_rules=None):
1938
from bzrlib.atomicfile import AtomicFile
1939
if old_default_rules is not None:
1940
# dump the rules and exit
1941
for pattern in ignores.OLD_DEFAULTS:
1944
if not name_pattern_list:
1945
raise errors.BzrCommandError("ignore requires at least one "
1946
"NAME_PATTERN or --old-default-rules")
1947
name_pattern_list = [globbing.normalize_pattern(p)
1948
for p in name_pattern_list]
1949
for name_pattern in name_pattern_list:
1950
if (name_pattern[0] == '/' or
1951
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1952
raise errors.BzrCommandError(
1953
"NAME_PATTERN should not be an absolute path")
1954
tree, relpath = WorkingTree.open_containing(u'.')
1955
ifn = tree.abspath('.bzrignore')
1956
if os.path.exists(ifn):
1959
igns = f.read().decode('utf-8')
1965
# TODO: If the file already uses crlf-style termination, maybe
1966
# we should use that for the newly added lines?
1968
if igns and igns[-1] != '\n':
1970
for name_pattern in name_pattern_list:
1971
igns += name_pattern + '\n'
1973
f = AtomicFile(ifn, 'wb')
1975
f.write(igns.encode('utf-8'))
1980
if not tree.path2id('.bzrignore'):
1981
tree.add(['.bzrignore'])
1983
ignored = globbing.Globster(name_pattern_list)
1986
for entry in tree.list_files():
1990
if ignored.match(filename):
1991
matches.append(filename.encode('utf-8'))
1993
if len(matches) > 0:
1994
print "Warning: the following files are version controlled and" \
1995
" match your ignore pattern:\n%s" % ("\n".join(matches),)
1997
class cmd_ignored(Command):
1998
"""List ignored files and the patterns that matched them.
2001
_see_also = ['ignore']
2004
tree = WorkingTree.open_containing(u'.')[0]
2007
for path, file_class, kind, file_id, entry in tree.list_files():
2008
if file_class != 'I':
2010
## XXX: Slightly inefficient since this was already calculated
2011
pat = tree.is_ignored(path)
2012
print '%-50s %s' % (path, pat)
2017
class cmd_lookup_revision(Command):
2018
"""Lookup the revision-id from a revision-number
2021
bzr lookup-revision 33
2024
takes_args = ['revno']
2027
def run(self, revno):
2031
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2033
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2036
class cmd_export(Command):
2037
"""Export current or past revision to a destination directory or archive.
2039
If no revision is specified this exports the last committed revision.
2041
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2042
given, try to find the format with the extension. If no extension
2043
is found exports to a directory (equivalent to --format=dir).
2045
If root is supplied, it will be used as the root directory inside
2046
container formats (tar, zip, etc). If it is not supplied it will default
2047
to the exported filename. The root option has no effect for 'dir' format.
2049
If branch is omitted then the branch containing the current working
2050
directory will be used.
2052
Note: Export of tree with non-ASCII filenames to zip is not supported.
2054
================= =========================
2055
Supported formats Autodetected by extension
2056
================= =========================
2059
tbz2 .tar.bz2, .tbz2
2062
================= =========================
2064
takes_args = ['dest', 'branch?']
2067
help="Type of file to export to.",
2072
help="Name of the root directory inside the exported file."),
2074
def run(self, dest, branch=None, revision=None, format=None, root=None):
2075
from bzrlib.export import export
2078
tree = WorkingTree.open_containing(u'.')[0]
2081
b = Branch.open(branch)
2083
if revision is None:
2084
# should be tree.last_revision FIXME
2085
rev_id = b.last_revision()
2087
if len(revision) != 1:
2088
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2089
rev_id = revision[0].in_history(b).rev_id
2090
t = b.repository.revision_tree(rev_id)
2092
export(t, dest, format, root)
2093
except errors.NoSuchExportFormat, e:
2094
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2097
class cmd_cat(Command):
2098
"""Write the contents of a file as of a given revision to standard output.
2100
If no revision is nominated, the last revision is used.
2102
Note: Take care to redirect standard output when using this command on a
2108
Option('name-from-revision', help='The path name in the old tree.'),
2111
takes_args = ['filename']
2112
encoding_type = 'exact'
2115
def run(self, filename, revision=None, name_from_revision=False):
2116
if revision is not None and len(revision) != 1:
2117
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2122
tree, b, relpath = \
2123
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2124
except errors.NotBranchError:
2127
if revision is not None and revision[0].get_branch() is not None:
2128
b = Branch.open(revision[0].get_branch())
2130
tree = b.basis_tree()
2131
if revision is None:
2132
revision_id = b.last_revision()
2134
revision_id = revision[0].in_history(b).rev_id
2136
cur_file_id = tree.path2id(relpath)
2137
rev_tree = b.repository.revision_tree(revision_id)
2138
old_file_id = rev_tree.path2id(relpath)
2140
if name_from_revision:
2141
if old_file_id is None:
2142
raise errors.BzrCommandError("%r is not present in revision %s"
2143
% (filename, revision_id))
2145
rev_tree.print_file(old_file_id)
2146
elif cur_file_id is not None:
2147
rev_tree.print_file(cur_file_id)
2148
elif old_file_id is not None:
2149
rev_tree.print_file(old_file_id)
2151
raise errors.BzrCommandError("%r is not present in revision %s" %
2152
(filename, revision_id))
2155
class cmd_local_time_offset(Command):
2156
"""Show the offset in seconds from GMT to local time."""
2160
print osutils.local_time_offset()
2164
class cmd_commit(Command):
2165
"""Commit changes into a new revision.
2167
If no arguments are given, the entire tree is committed.
2169
If selected files are specified, only changes to those files are
2170
committed. If a directory is specified then the directory and everything
2171
within it is committed.
2173
If author of the change is not the same person as the committer, you can
2174
specify the author's name using the --author option. The name should be
2175
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2177
A selected-file commit may fail in some cases where the committed
2178
tree would be invalid. Consider::
2183
bzr commit foo -m "committing foo"
2184
bzr mv foo/bar foo/baz
2187
bzr commit foo/bar -m "committing bar but not baz"
2189
In the example above, the last commit will fail by design. This gives
2190
the user the opportunity to decide whether they want to commit the
2191
rename at the same time, separately first, or not at all. (As a general
2192
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2194
Note: A selected-file commit after a merge is not yet supported.
2196
# TODO: Run hooks on tree to-be-committed, and after commit.
2198
# TODO: Strict commit that fails if there are deleted files.
2199
# (what does "deleted files" mean ??)
2201
# TODO: Give better message for -s, --summary, used by tla people
2203
# XXX: verbose currently does nothing
2205
_see_also = ['bugs', 'uncommit']
2206
takes_args = ['selected*']
2208
Option('message', type=unicode,
2210
help="Description of the new revision."),
2213
help='Commit even if nothing has changed.'),
2214
Option('file', type=str,
2217
help='Take commit message from this file.'),
2219
help="Refuse to commit if there are unknown "
2220
"files in the working tree."),
2221
ListOption('fixes', type=str,
2222
help="Mark a bug as being fixed by this revision."),
2223
Option('author', type=str,
2224
help="Set the author's name, if it's different "
2225
"from the committer."),
2227
help="Perform a local commit in a bound "
2228
"branch. Local commits are not pushed to "
2229
"the master branch until a normal commit "
2233
help='When no message is supplied, show the diff along'
2234
' with the status summary in the message editor.'),
2236
aliases = ['ci', 'checkin']
2238
def _get_bug_fix_properties(self, fixes, branch):
2240
# Configure the properties for bug fixing attributes.
2241
for fixed_bug in fixes:
2242
tokens = fixed_bug.split(':')
2243
if len(tokens) != 2:
2244
raise errors.BzrCommandError(
2245
"Invalid bug %s. Must be in the form of 'tag:id'. "
2246
"Commit refused." % fixed_bug)
2247
tag, bug_id = tokens
2249
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2250
except errors.UnknownBugTrackerAbbreviation:
2251
raise errors.BzrCommandError(
2252
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2253
except errors.MalformedBugIdentifier:
2254
raise errors.BzrCommandError(
2255
"Invalid bug identifier for %s. Commit refused."
2257
properties.append('%s fixed' % bug_url)
2258
return '\n'.join(properties)
2260
def run(self, message=None, file=None, verbose=False, selected_list=None,
2261
unchanged=False, strict=False, local=False, fixes=None,
2262
author=None, show_diff=False):
2263
from bzrlib.commit import (
2267
from bzrlib.errors import (
2272
from bzrlib.msgeditor import (
2273
edit_commit_message_encoded,
2274
make_commit_message_template_encoded
2277
# TODO: Need a blackbox test for invoking the external editor; may be
2278
# slightly problematic to run this cross-platform.
2280
# TODO: do more checks that the commit will succeed before
2281
# spending the user's valuable time typing a commit message.
2285
tree, selected_list = tree_files(selected_list)
2286
if selected_list == ['']:
2287
# workaround - commit of root of tree should be exactly the same
2288
# as just default commit in that tree, and succeed even though
2289
# selected-file merge commit is not done yet
2294
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2296
properties['bugs'] = bug_property
2298
if local and not tree.branch.get_bound_location():
2299
raise errors.LocalRequiresBoundBranch()
2301
def get_message(commit_obj):
2302
"""Callback to get commit message"""
2303
my_message = message
2304
if my_message is None and not file:
2305
t = make_commit_message_template_encoded(tree,
2306
selected_list, diff=show_diff,
2307
output_encoding=bzrlib.user_encoding)
2308
my_message = edit_commit_message_encoded(t)
2309
if my_message is None:
2310
raise errors.BzrCommandError("please specify a commit"
2311
" message with either --message or --file")
2312
elif my_message and file:
2313
raise errors.BzrCommandError(
2314
"please specify either --message or --file")
2316
my_message = codecs.open(file, 'rt',
2317
bzrlib.user_encoding).read()
2318
if my_message == "":
2319
raise errors.BzrCommandError("empty commit message specified")
2323
tree.commit(message_callback=get_message,
2324
specific_files=selected_list,
2325
allow_pointless=unchanged, strict=strict, local=local,
2326
reporter=None, verbose=verbose, revprops=properties,
2328
except PointlessCommit:
2329
# FIXME: This should really happen before the file is read in;
2330
# perhaps prepare the commit; get the message; then actually commit
2331
raise errors.BzrCommandError("no changes to commit."
2332
" use --unchanged to commit anyhow")
2333
except ConflictsInTree:
2334
raise errors.BzrCommandError('Conflicts detected in working '
2335
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2337
except StrictCommitFailed:
2338
raise errors.BzrCommandError("Commit refused because there are"
2339
" unknown files in the working tree.")
2340
except errors.BoundBranchOutOfDate, e:
2341
raise errors.BzrCommandError(str(e) + "\n"
2342
'To commit to master branch, run update and then commit.\n'
2343
'You can also pass --local to commit to continue working '
2347
class cmd_check(Command):
2348
"""Validate consistency of branch history.
2350
This command checks various invariants about the branch storage to
2351
detect data corruption or bzr bugs.
2354
_see_also = ['reconcile']
2355
takes_args = ['branch?']
2356
takes_options = ['verbose']
2358
def run(self, branch=None, verbose=False):
2359
from bzrlib.check import check
2361
tree = WorkingTree.open_containing()[0]
2362
branch = tree.branch
2364
branch = Branch.open(branch)
2365
check(branch, verbose)
2368
class cmd_upgrade(Command):
2369
"""Upgrade branch storage to current format.
2371
The check command or bzr developers may sometimes advise you to run
2372
this command. When the default format has changed you may also be warned
2373
during other operations to upgrade.
2376
_see_also = ['check']
2377
takes_args = ['url?']
2379
RegistryOption('format',
2380
help='Upgrade to a specific format. See "bzr help'
2381
' formats" for details.',
2382
registry=bzrdir.format_registry,
2383
converter=bzrdir.format_registry.make_bzrdir,
2384
value_switches=True, title='Branch format'),
2387
def run(self, url='.', format=None):
2388
from bzrlib.upgrade import upgrade
2390
format = bzrdir.format_registry.make_bzrdir('default')
2391
upgrade(url, format)
2394
class cmd_whoami(Command):
2395
"""Show or set bzr user id.
2398
Show the email of the current user::
2402
Set the current user::
2404
bzr whoami 'Frank Chu <fchu@example.com>'
2406
takes_options = [ Option('email',
2407
help='Display email address only.'),
2409
help='Set identity for the current branch instead of '
2412
takes_args = ['name?']
2413
encoding_type = 'replace'
2416
def run(self, email=False, branch=False, name=None):
2418
# use branch if we're inside one; otherwise global config
2420
c = Branch.open_containing('.')[0].get_config()
2421
except errors.NotBranchError:
2422
c = config.GlobalConfig()
2424
self.outf.write(c.user_email() + '\n')
2426
self.outf.write(c.username() + '\n')
2429
# display a warning if an email address isn't included in the given name.
2431
config.extract_email_address(name)
2432
except errors.NoEmailInUsername, e:
2433
warning('"%s" does not seem to contain an email address. '
2434
'This is allowed, but not recommended.', name)
2436
# use global config unless --branch given
2438
c = Branch.open_containing('.')[0].get_config()
2440
c = config.GlobalConfig()
2441
c.set_user_option('email', name)
2444
class cmd_nick(Command):
2445
"""Print or set the branch nickname.
2447
If unset, the tree root directory name is used as the nickname
2448
To print the current nickname, execute with no argument.
2451
_see_also = ['info']
2452
takes_args = ['nickname?']
2453
def run(self, nickname=None):
2454
branch = Branch.open_containing(u'.')[0]
2455
if nickname is None:
2456
self.printme(branch)
2458
branch.nick = nickname
2461
def printme(self, branch):
2465
class cmd_selftest(Command):
2466
"""Run internal test suite.
2468
If arguments are given, they are regular expressions that say which tests
2469
should run. Tests matching any expression are run, and other tests are
2472
Alternatively if --first is given, matching tests are run first and then
2473
all other tests are run. This is useful if you have been working in a
2474
particular area, but want to make sure nothing else was broken.
2476
If --exclude is given, tests that match that regular expression are
2477
excluded, regardless of whether they match --first or not.
2479
To help catch accidential dependencies between tests, the --randomize
2480
option is useful. In most cases, the argument used is the word 'now'.
2481
Note that the seed used for the random number generator is displayed
2482
when this option is used. The seed can be explicitly passed as the
2483
argument to this option if required. This enables reproduction of the
2484
actual ordering used if and when an order sensitive problem is encountered.
2486
If --list-only is given, the tests that would be run are listed. This is
2487
useful when combined with --first, --exclude and/or --randomize to
2488
understand their impact. The test harness reports "Listed nn tests in ..."
2489
instead of "Ran nn tests in ..." when list mode is enabled.
2491
If the global option '--no-plugins' is given, plugins are not loaded
2492
before running the selftests. This has two effects: features provided or
2493
modified by plugins will not be tested, and tests provided by plugins will
2496
Tests that need working space on disk use a common temporary directory,
2497
typically inside $TMPDIR or /tmp.
2500
Run only tests relating to 'ignore'::
2504
Disable plugins and list tests as they're run::
2506
bzr --no-plugins selftest -v
2508
# NB: this is used from the class without creating an instance, which is
2509
# why it does not have a self parameter.
2510
def get_transport_type(typestring):
2511
"""Parse and return a transport specifier."""
2512
if typestring == "sftp":
2513
from bzrlib.transport.sftp import SFTPAbsoluteServer
2514
return SFTPAbsoluteServer
2515
if typestring == "memory":
2516
from bzrlib.transport.memory import MemoryServer
2518
if typestring == "fakenfs":
2519
from bzrlib.transport.fakenfs import FakeNFSServer
2520
return FakeNFSServer
2521
msg = "No known transport type %s. Supported types are: sftp\n" %\
2523
raise errors.BzrCommandError(msg)
2526
takes_args = ['testspecs*']
2527
takes_options = ['verbose',
2529
help='Stop when one test fails.',
2533
help='Use a different transport by default '
2534
'throughout the test suite.',
2535
type=get_transport_type),
2537
help='Run the benchmarks rather than selftests.'),
2538
Option('lsprof-timed',
2539
help='Generate lsprof output for benchmarked'
2540
' sections of code.'),
2541
Option('cache-dir', type=str,
2542
help='Cache intermediate benchmark output in this '
2545
help='Run all tests, but run specified tests first.',
2549
help='List the tests instead of running them.'),
2550
Option('randomize', type=str, argname="SEED",
2551
help='Randomize the order of tests using the given'
2552
' seed or "now" for the current time.'),
2553
Option('exclude', type=str, argname="PATTERN",
2555
help='Exclude tests that match this regular'
2557
Option('strict', help='Fail on missing dependencies or '
2560
encoding_type = 'replace'
2562
def run(self, testspecs_list=None, verbose=False, one=False,
2563
transport=None, benchmark=None,
2564
lsprof_timed=None, cache_dir=None,
2565
first=False, list_only=False,
2566
randomize=None, exclude=None, strict=False):
2568
from bzrlib.tests import selftest
2569
import bzrlib.benchmarks as benchmarks
2570
from bzrlib.benchmarks import tree_creator
2572
if cache_dir is not None:
2573
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2575
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2576
print ' %s (%s python%s)' % (
2578
bzrlib.version_string,
2579
'.'.join(map(str, sys.version_info)),
2582
if testspecs_list is not None:
2583
pattern = '|'.join(testspecs_list)
2587
test_suite_factory = benchmarks.test_suite
2588
# Unless user explicitly asks for quiet, be verbose in benchmarks
2589
verbose = not is_quiet()
2590
# TODO: should possibly lock the history file...
2591
benchfile = open(".perf_history", "at", buffering=1)
2593
test_suite_factory = None
2596
result = selftest(verbose=verbose,
2598
stop_on_failure=one,
2599
transport=transport,
2600
test_suite_factory=test_suite_factory,
2601
lsprof_timed=lsprof_timed,
2602
bench_history=benchfile,
2603
matching_tests_first=first,
2604
list_only=list_only,
2605
random_seed=randomize,
2606
exclude_pattern=exclude,
2610
if benchfile is not None:
2613
info('tests passed')
2615
info('tests failed')
2616
return int(not result)
2619
class cmd_version(Command):
2620
"""Show version of bzr."""
2622
encoding_type = 'replace'
2626
from bzrlib.version import show_version
2627
show_version(to_file=self.outf)
2630
class cmd_rocks(Command):
2631
"""Statement of optimism."""
2637
print "It sure does!"
2640
class cmd_find_merge_base(Command):
2641
"""Find and print a base revision for merging two branches."""
2642
# TODO: Options to specify revisions on either side, as if
2643
# merging only part of the history.
2644
takes_args = ['branch', 'other']
2648
def run(self, branch, other):
2649
from bzrlib.revision import ensure_null, MultipleRevisionSources
2651
branch1 = Branch.open_containing(branch)[0]
2652
branch2 = Branch.open_containing(other)[0]
2654
last1 = ensure_null(branch1.last_revision())
2655
last2 = ensure_null(branch2.last_revision())
2657
graph = branch1.repository.get_graph(branch2.repository)
2658
base_rev_id = graph.find_unique_lca(last1, last2)
2660
print 'merge base is revision %s' % base_rev_id
2663
class cmd_merge(Command):
2664
"""Perform a three-way merge.
2666
The branch is the branch you will merge from. By default, it will merge
2667
the latest revision. If you specify a revision, that revision will be
2668
merged. If you specify two revisions, the first will be used as a BASE,
2669
and the second one as OTHER. Revision numbers are always relative to the
2672
By default, bzr will try to merge in all new work from the other
2673
branch, automatically determining an appropriate base. If this
2674
fails, you may need to give an explicit base.
2676
Merge will do its best to combine the changes in two branches, but there
2677
are some kinds of problems only a human can fix. When it encounters those,
2678
it will mark a conflict. A conflict means that you need to fix something,
2679
before you should commit.
2681
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2683
If there is no default branch set, the first merge will set it. After
2684
that, you can omit the branch to use the default. To change the
2685
default, use --remember. The value will only be saved if the remote
2686
location can be accessed.
2688
The results of the merge are placed into the destination working
2689
directory, where they can be reviewed (with bzr diff), tested, and then
2690
committed to record the result of the merge.
2692
merge refuses to run if there are any uncommitted changes, unless
2696
To merge the latest revision from bzr.dev::
2698
bzr merge ../bzr.dev
2700
To merge changes up to and including revision 82 from bzr.dev::
2702
bzr merge -r 82 ../bzr.dev
2704
To merge the changes introduced by 82, without previous changes::
2706
bzr merge -r 81..82 ../bzr.dev
2709
_see_also = ['update', 'remerge', 'status-flags']
2710
takes_args = ['branch?']
2714
help='Merge even if the destination tree has uncommitted changes.'),
2718
Option('show-base', help="Show base revision text in "
2720
Option('uncommitted', help='Apply uncommitted changes'
2721
' from a working copy, instead of branch changes.'),
2722
Option('pull', help='If the destination is already'
2723
' completely merged into the source, pull from the'
2724
' source rather than merging. When this happens,'
2725
' you do not need to commit the result.'),
2727
help='Branch to merge into, '
2728
'rather than the one containing the working directory.',
2734
def run(self, branch=None, revision=None, force=False, merge_type=None,
2735
show_base=False, reprocess=False, remember=False,
2736
uncommitted=False, pull=False,
2739
from bzrlib.tag import _merge_tags_if_possible
2740
# This is actually a branch (or merge-directive) *location*.
2744
if merge_type is None:
2745
merge_type = _mod_merge.Merge3Merger
2747
if directory is None: directory = u'.'
2748
possible_transports = []
2750
allow_pending = True
2751
verified = 'inapplicable'
2752
tree = WorkingTree.open_containing(directory)[0]
2753
change_reporter = delta._ChangeReporter(
2754
unversioned_filter=tree.is_ignored)
2757
pb = ui.ui_factory.nested_progress_bar()
2758
cleanups.append(pb.finished)
2760
cleanups.append(tree.unlock)
2761
if location is not None:
2762
mergeable, other_transport = _get_mergeable_helper(location)
2765
raise errors.BzrCommandError('Cannot use --uncommitted'
2766
' with bundles or merge directives.')
2768
if revision is not None:
2769
raise errors.BzrCommandError(
2770
'Cannot use -r with merge directives or bundles')
2771
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2773
possible_transports.append(other_transport)
2775
if merger is None and uncommitted:
2776
if revision is not None and len(revision) > 0:
2777
raise errors.BzrCommandError('Cannot use --uncommitted and'
2778
' --revision at the same time.')
2779
location = self._select_branch_location(tree, location)[0]
2780
other_tree, other_path = WorkingTree.open_containing(location)
2781
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2783
allow_pending = False
2786
merger, allow_pending = self._get_merger_from_branch(tree,
2787
location, revision, remember, possible_transports, pb)
2789
merger.merge_type = merge_type
2790
merger.reprocess = reprocess
2791
merger.show_base = show_base
2792
merger.change_reporter = change_reporter
2793
self.sanity_check_merger(merger)
2794
if (merger.base_rev_id == merger.other_rev_id and
2795
merger.other_rev_id != None):
2796
note('Nothing to do.')
2799
if merger.interesting_files is not None:
2800
raise BzrCommandError('Cannot pull individual files')
2801
if (merger.base_rev_id == tree.last_revision()):
2802
result = tree.pull(merger.other_branch, False,
2803
merger.other_rev_id)
2804
result.report(self.outf)
2806
merger.check_basis(not force)
2807
conflict_count = merger.do_merge()
2809
merger.set_pending()
2810
if verified == 'failed':
2811
warning('Preview patch does not match changes')
2812
if conflict_count != 0:
2817
for cleanup in reversed(cleanups):
2820
def sanity_check_merger(self, merger):
2821
if (merger.show_base and
2822
not merger.merge_type is _mod_merge.Merge3Merger):
2823
raise errors.BzrCommandError("Show-base is not supported for this"
2824
" merge type. %s" % merger.merge_type)
2825
if merger.reprocess and not merger.merge_type.supports_reprocess:
2826
raise errors.BzrCommandError("Conflict reduction is not supported"
2827
" for merge type %s." %
2829
if merger.reprocess and merger.show_base:
2830
raise errors.BzrCommandError("Cannot do conflict reduction and"
2833
def _get_merger_from_branch(self, tree, location, revision, remember,
2834
possible_transports, pb):
2835
"""Produce a merger from a location, assuming it refers to a branch."""
2836
from bzrlib.tag import _merge_tags_if_possible
2837
assert revision is None or len(revision) < 3
2838
# find the branch locations
2839
other_loc, location = self._select_branch_location(tree, location,
2841
if revision is not None and len(revision) == 2:
2842
base_loc, location = self._select_branch_location(tree, location,
2845
base_loc = other_loc
2847
other_branch, other_path = Branch.open_containing(other_loc,
2848
possible_transports)
2849
if base_loc == other_loc:
2850
base_branch = other_branch
2852
base_branch, base_path = Branch.open_containing(base_loc,
2853
possible_transports)
2854
# Find the revision ids
2855
if revision is None or len(revision) < 1 or revision[-1] is None:
2856
other_revision_id = _mod_revision.ensure_null(
2857
other_branch.last_revision())
2859
other_revision_id = \
2860
_mod_revision.ensure_null(
2861
revision[-1].in_history(other_branch).rev_id)
2862
if (revision is not None and len(revision) == 2
2863
and revision[0] is not None):
2864
base_revision_id = \
2865
_mod_revision.ensure_null(
2866
revision[0].in_history(base_branch).rev_id)
2868
base_revision_id = None
2869
# Remember where we merge from
2870
if ((tree.branch.get_parent() is None or remember) and
2871
other_branch is not None):
2872
tree.branch.set_parent(other_branch.base)
2873
_merge_tags_if_possible(other_branch, tree.branch)
2874
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
2875
other_revision_id, base_revision_id, other_branch, base_branch)
2876
if other_path != '':
2877
allow_pending = False
2878
merger.interesting_files = [other_path]
2880
allow_pending = True
2881
return merger, allow_pending
2883
def _select_branch_location(self, tree, location, revision=None,
2885
"""Select a branch location, according to possible inputs.
2887
If provided, branches from ``revision`` are preferred. (Both
2888
``revision`` and ``index`` must be supplied.)
2890
Otherwise, the ``location`` parameter is used. If it is None, then the
2891
``parent`` location is used, and a note is printed.
2893
:param tree: The working tree to select a branch for merging into
2894
:param location: The location entered by the user
2895
:param revision: The revision parameter to the command
2896
:param index: The index to use for the revision parameter. Negative
2897
indices are permitted.
2898
:return: (selected_location, default_location). The default location
2899
will be the user-entered location, if any, or else the remembered
2902
if (revision is not None and index is not None
2903
and revision[index] is not None):
2904
branch = revision[index].get_branch()
2905
if branch is not None:
2906
return branch, location
2907
location = self._get_remembered_parent(tree, location, 'Merging from')
2908
return location, location
2910
# TODO: move up to common parent; this isn't merge-specific anymore.
2911
def _get_remembered_parent(self, tree, supplied_location, verb_string):
2912
"""Use tree.branch's parent if none was supplied.
2914
Report if the remembered location was used.
2916
if supplied_location is not None:
2917
return supplied_location
2918
stored_location = tree.branch.get_parent()
2919
mutter("%s", stored_location)
2920
if stored_location is None:
2921
raise errors.BzrCommandError("No location specified or remembered")
2922
display_url = urlutils.unescape_for_display(stored_location,
2924
self.outf.write("%s remembered location %s\n" % (verb_string,
2926
return stored_location
2929
class cmd_remerge(Command):
2932
Use this if you want to try a different merge technique while resolving
2933
conflicts. Some merge techniques are better than others, and remerge
2934
lets you try different ones on different files.
2936
The options for remerge have the same meaning and defaults as the ones for
2937
merge. The difference is that remerge can (only) be run when there is a
2938
pending merge, and it lets you specify particular files.
2941
Re-do the merge of all conflicted files, and show the base text in
2942
conflict regions, in addition to the usual THIS and OTHER texts::
2944
bzr remerge --show-base
2946
Re-do the merge of "foobar", using the weave merge algorithm, with
2947
additional processing to reduce the size of conflict regions::
2949
bzr remerge --merge-type weave --reprocess foobar
2951
takes_args = ['file*']
2956
help="Show base revision text in conflicts."),
2959
def run(self, file_list=None, merge_type=None, show_base=False,
2961
if merge_type is None:
2962
merge_type = _mod_merge.Merge3Merger
2963
tree, file_list = tree_files(file_list)
2966
parents = tree.get_parent_ids()
2967
if len(parents) != 2:
2968
raise errors.BzrCommandError("Sorry, remerge only works after normal"
2969
" merges. Not cherrypicking or"
2971
repository = tree.branch.repository
2972
graph = repository.get_graph()
2973
base_revision = graph.find_unique_lca(parents[0], parents[1])
2974
base_tree = repository.revision_tree(base_revision)
2975
other_tree = repository.revision_tree(parents[1])
2976
interesting_ids = None
2978
conflicts = tree.conflicts()
2979
if file_list is not None:
2980
interesting_ids = set()
2981
for filename in file_list:
2982
file_id = tree.path2id(filename)
2984
raise errors.NotVersionedError(filename)
2985
interesting_ids.add(file_id)
2986
if tree.kind(file_id) != "directory":
2989
for name, ie in tree.inventory.iter_entries(file_id):
2990
interesting_ids.add(ie.file_id)
2991
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2993
# Remerge only supports resolving contents conflicts
2994
allowed_conflicts = ('text conflict', 'contents conflict')
2995
restore_files = [c.path for c in conflicts
2996
if c.typestring in allowed_conflicts]
2997
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
2998
tree.set_conflicts(ConflictList(new_conflicts))
2999
if file_list is not None:
3000
restore_files = file_list
3001
for filename in restore_files:
3003
restore(tree.abspath(filename))
3004
except errors.NotConflicted:
3006
# Disable pending merges, because the file texts we are remerging
3007
# have not had those merges performed. If we use the wrong parents
3008
# list, we imply that the working tree text has seen and rejected
3009
# all the changes from the other tree, when in fact those changes
3010
# have not yet been seen.
3011
tree.set_parent_ids(parents[:1])
3013
conflicts = _mod_merge.merge_inner(
3014
tree.branch, other_tree, base_tree,
3016
interesting_ids=interesting_ids,
3017
other_rev_id=parents[1],
3018
merge_type=merge_type,
3019
show_base=show_base,
3020
reprocess=reprocess)
3022
tree.set_parent_ids(parents)
3031
class cmd_revert(Command):
3032
"""Revert files to a previous revision.
3034
Giving a list of files will revert only those files. Otherwise, all files
3035
will be reverted. If the revision is not specified with '--revision', the
3036
last committed revision is used.
3038
To remove only some changes, without reverting to a prior version, use
3039
merge instead. For example, "merge . --r-2..-3" will remove the changes
3040
introduced by -2, without affecting the changes introduced by -1. Or
3041
to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3043
By default, any files that have been manually changed will be backed up
3044
first. (Files changed only by merge are not backed up.) Backup files have
3045
'.~#~' appended to their name, where # is a number.
3047
When you provide files, you can use their current pathname or the pathname
3048
from the target revision. So you can use revert to "undelete" a file by
3049
name. If you name a directory, all the contents of that directory will be
3052
Any files that have been newly added since that revision will be deleted,
3053
with a backup kept if appropriate. Directories containing unknown files
3054
will not be deleted.
3057
_see_also = ['cat', 'export']
3060
Option('no-backup', "Do not save backups of reverted files."),
3062
takes_args = ['file*']
3064
def run(self, revision=None, no_backup=False, file_list=None):
3065
if file_list is not None:
3066
if len(file_list) == 0:
3067
raise errors.BzrCommandError("No files specified")
3069
tree, file_list = tree_files(file_list)
3070
if revision is None:
3071
# FIXME should be tree.last_revision
3072
rev_id = tree.last_revision()
3073
elif len(revision) != 1:
3074
raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
3076
rev_id = revision[0].in_history(tree.branch).rev_id
3077
pb = ui.ui_factory.nested_progress_bar()
3079
tree.revert(file_list,
3080
tree.branch.repository.revision_tree(rev_id),
3081
not no_backup, pb, report_changes=True)
3086
class cmd_assert_fail(Command):
3087
"""Test reporting of assertion failures"""
3088
# intended just for use in testing
3093
raise AssertionError("always fails")
3096
class cmd_help(Command):
3097
"""Show help on a command or other topic.
3100
_see_also = ['topics']
3102
Option('long', 'Show help on all commands.'),
3104
takes_args = ['topic?']
3105
aliases = ['?', '--help', '-?', '-h']
3108
def run(self, topic=None, long=False):
3110
if topic is None and long:
3112
bzrlib.help.help(topic)
3115
class cmd_shell_complete(Command):
3116
"""Show appropriate completions for context.
3118
For a list of all available commands, say 'bzr shell-complete'.
3120
takes_args = ['context?']
3125
def run(self, context=None):
3126
import shellcomplete
3127
shellcomplete.shellcomplete(context)
3130
class cmd_fetch(Command):
3131
"""Copy in history from another branch but don't merge it.
3133
This is an internal method used for pull and merge.
3136
takes_args = ['from_branch', 'to_branch']
3137
def run(self, from_branch, to_branch):
3138
from bzrlib.fetch import Fetcher
3139
from_b = Branch.open(from_branch)
3140
to_b = Branch.open(to_branch)
3141
Fetcher(to_b, from_b)
3144
class cmd_missing(Command):
3145
"""Show unmerged/unpulled revisions between two branches.
3147
OTHER_BRANCH may be local or remote.
3150
_see_also = ['merge', 'pull']
3151
takes_args = ['other_branch?']
3153
Option('reverse', 'Reverse the order of revisions.'),
3155
'Display changes in the local branch only.'),
3156
Option('this' , 'Same as --mine-only.'),
3157
Option('theirs-only',
3158
'Display changes in the remote branch only.'),
3159
Option('other', 'Same as --theirs-only.'),
3164
encoding_type = 'replace'
3167
def run(self, other_branch=None, reverse=False, mine_only=False,
3168
theirs_only=False, log_format=None, long=False, short=False, line=False,
3169
show_ids=False, verbose=False, this=False, other=False):
3170
from bzrlib.missing import find_unmerged, iter_log_revisions
3171
from bzrlib.log import log_formatter
3178
local_branch = Branch.open_containing(u".")[0]
3179
parent = local_branch.get_parent()
3180
if other_branch is None:
3181
other_branch = parent
3182
if other_branch is None:
3183
raise errors.BzrCommandError("No peer location known"
3185
display_url = urlutils.unescape_for_display(parent,
3187
self.outf.write("Using last location: " + display_url + "\n")
3189
remote_branch = Branch.open(other_branch)
3190
if remote_branch.base == local_branch.base:
3191
remote_branch = local_branch
3192
local_branch.lock_read()
3194
remote_branch.lock_read()
3196
local_extra, remote_extra = find_unmerged(local_branch,
3198
if log_format is None:
3199
registry = log.log_formatter_registry
3200
log_format = registry.get_default(local_branch)
3201
lf = log_format(to_file=self.outf,
3203
show_timezone='original')
3204
if reverse is False:
3205
local_extra.reverse()
3206
remote_extra.reverse()
3207
if local_extra and not theirs_only:
3208
self.outf.write("You have %d extra revision(s):\n" %
3210
for revision in iter_log_revisions(local_extra,
3211
local_branch.repository,
3213
lf.log_revision(revision)
3214
printed_local = True
3216
printed_local = False
3217
if remote_extra and not mine_only:
3218
if printed_local is True:
3219
self.outf.write("\n\n\n")
3220
self.outf.write("You are missing %d revision(s):\n" %
3222
for revision in iter_log_revisions(remote_extra,
3223
remote_branch.repository,
3225
lf.log_revision(revision)
3226
if not remote_extra and not local_extra:
3228
self.outf.write("Branches are up to date.\n")
3232
remote_branch.unlock()
3234
local_branch.unlock()
3235
if not status_code and parent is None and other_branch is not None:
3236
local_branch.lock_write()
3238
# handle race conditions - a parent might be set while we run.
3239
if local_branch.get_parent() is None:
3240
local_branch.set_parent(remote_branch.base)
3242
local_branch.unlock()
3246
class cmd_pack(Command):
3247
"""Compress the data within a repository."""
3249
_see_also = ['repositories']
3250
takes_args = ['branch_or_repo?']
3252
def run(self, branch_or_repo='.'):
3253
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3255
branch = dir.open_branch()
3256
repository = branch.repository
3257
except errors.NotBranchError:
3258
repository = dir.open_repository()
3262
class cmd_plugins(Command):
3263
"""List the installed plugins.
3265
This command displays the list of installed plugins including the
3266
path where each one is located and a short description of each.
3268
A plugin is an external component for Bazaar that extends the
3269
revision control system, by adding or replacing code in Bazaar.
3270
Plugins can do a variety of things, including overriding commands,
3271
adding new commands, providing additional network transports and
3272
customizing log output.
3274
See the Bazaar web site, http://bazaar-vcs.org, for further
3275
information on plugins including where to find them and how to
3276
install them. Instructions are also provided there on how to
3277
write new plugins using the Python programming language.
3282
import bzrlib.plugin
3283
from inspect import getdoc
3284
for name, plugin in bzrlib.plugin.plugins().items():
3285
print plugin.path(), "[%s]" % plugin.__version__
3286
d = getdoc(plugin.module)
3288
print '\t', d.split('\n')[0]
3291
class cmd_testament(Command):
3292
"""Show testament (signing-form) of a revision."""
3295
Option('long', help='Produce long-format testament.'),
3297
help='Produce a strict-format testament.')]
3298
takes_args = ['branch?']
3300
def run(self, branch=u'.', revision=None, long=False, strict=False):
3301
from bzrlib.testament import Testament, StrictTestament
3303
testament_class = StrictTestament
3305
testament_class = Testament
3306
b = WorkingTree.open_containing(branch)[0].branch
3309
if revision is None:
3310
rev_id = b.last_revision()
3312
rev_id = revision[0].in_history(b).rev_id
3313
t = testament_class.from_revision(b.repository, rev_id)
3315
sys.stdout.writelines(t.as_text_lines())
3317
sys.stdout.write(t.as_short_text())
3322
class cmd_annotate(Command):
3323
"""Show the origin of each line in a file.
3325
This prints out the given file with an annotation on the left side
3326
indicating which revision, author and date introduced the change.
3328
If the origin is the same for a run of consecutive lines, it is
3329
shown only at the top, unless the --all option is given.
3331
# TODO: annotate directories; showing when each file was last changed
3332
# TODO: if the working copy is modified, show annotations on that
3333
# with new uncommitted lines marked
3334
aliases = ['ann', 'blame', 'praise']
3335
takes_args = ['filename']
3336
takes_options = [Option('all', help='Show annotations on all lines.'),
3337
Option('long', help='Show commit date in annotations.'),
3341
encoding_type = 'exact'
3344
def run(self, filename, all=False, long=False, revision=None,
3346
from bzrlib.annotate import annotate_file
3347
tree, relpath = WorkingTree.open_containing(filename)
3348
branch = tree.branch
3351
if revision is None:
3352
revision_id = branch.last_revision()
3353
elif len(revision) != 1:
3354
raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3356
revision_id = revision[0].in_history(branch).rev_id
3357
file_id = tree.path2id(relpath)
3359
raise errors.NotVersionedError(filename)
3360
tree = branch.repository.revision_tree(revision_id)
3361
file_version = tree.inventory[file_id].revision
3362
annotate_file(branch, file_version, file_id, long, all, self.outf,
3368
class cmd_re_sign(Command):
3369
"""Create a digital signature for an existing revision."""
3370
# TODO be able to replace existing ones.
3372
hidden = True # is this right ?
3373
takes_args = ['revision_id*']
3374
takes_options = ['revision']
3376
def run(self, revision_id_list=None, revision=None):
3377
import bzrlib.gpg as gpg
3378
if revision_id_list is not None and revision is not None:
3379
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3380
if revision_id_list is None and revision is None:
3381
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3382
b = WorkingTree.open_containing(u'.')[0].branch
3383
gpg_strategy = gpg.GPGStrategy(b.get_config())
3384
if revision_id_list is not None:
3385
for revision_id in revision_id_list:
3386
b.repository.sign_revision(revision_id, gpg_strategy)
3387
elif revision is not None:
3388
if len(revision) == 1:
3389
revno, rev_id = revision[0].in_history(b)
3390
b.repository.sign_revision(rev_id, gpg_strategy)
3391
elif len(revision) == 2:
3392
# are they both on rh- if so we can walk between them
3393
# might be nice to have a range helper for arbitrary
3394
# revision paths. hmm.
3395
from_revno, from_revid = revision[0].in_history(b)
3396
to_revno, to_revid = revision[1].in_history(b)
3397
if to_revid is None:
3398
to_revno = b.revno()
3399
if from_revno is None or to_revno is None:
3400
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3401
for revno in range(from_revno, to_revno + 1):
3402
b.repository.sign_revision(b.get_rev_id(revno),
3405
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3408
class cmd_bind(Command):
3409
"""Convert the current branch into a checkout of the supplied branch.
3411
Once converted into a checkout, commits must succeed on the master branch
3412
before they will be applied to the local branch.
3415
_see_also = ['checkouts', 'unbind']
3416
takes_args = ['location?']
3419
def run(self, location=None):
3420
b, relpath = Branch.open_containing(u'.')
3421
if location is None:
3423
location = b.get_old_bound_location()
3424
except errors.UpgradeRequired:
3425
raise errors.BzrCommandError('No location supplied. '
3426
'This format does not remember old locations.')
3428
if location is None:
3429
raise errors.BzrCommandError('No location supplied and no '
3430
'previous location known')
3431
b_other = Branch.open(location)
3434
except errors.DivergedBranches:
3435
raise errors.BzrCommandError('These branches have diverged.'
3436
' Try merging, and then bind again.')
3439
class cmd_unbind(Command):
3440
"""Convert the current checkout into a regular branch.
3442
After unbinding, the local branch is considered independent and subsequent
3443
commits will be local only.
3446
_see_also = ['checkouts', 'bind']
3451
b, relpath = Branch.open_containing(u'.')
3453
raise errors.BzrCommandError('Local branch is not bound')
3456
class cmd_uncommit(Command):
3457
"""Remove the last committed revision.
3459
--verbose will print out what is being removed.
3460
--dry-run will go through all the motions, but not actually
3463
If --revision is specified, uncommit revisions to leave the branch at the
3464
specified revision. For example, "bzr uncommit -r 15" will leave the
3465
branch at revision 15.
3467
In the future, uncommit will create a revision bundle, which can then
3471
# TODO: jam 20060108 Add an option to allow uncommit to remove
3472
# unreferenced information in 'branch-as-repository' branches.
3473
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3474
# information in shared branches as well.
3475
_see_also = ['commit']
3476
takes_options = ['verbose', 'revision',
3477
Option('dry-run', help='Don\'t actually make changes.'),
3478
Option('force', help='Say yes to all questions.')]
3479
takes_args = ['location?']
3482
def run(self, location=None,
3483
dry_run=False, verbose=False,
3484
revision=None, force=False):
3485
from bzrlib.log import log_formatter, show_log
3487
from bzrlib.uncommit import uncommit
3489
if location is None:
3491
control, relpath = bzrdir.BzrDir.open_containing(location)
3493
tree = control.open_workingtree()
3495
except (errors.NoWorkingTree, errors.NotLocalUrl):
3497
b = control.open_branch()
3500
if revision is None:
3503
# 'bzr uncommit -r 10' actually means uncommit
3504
# so that the final tree is at revno 10.
3505
# but bzrlib.uncommit.uncommit() actually uncommits
3506
# the revisions that are supplied.
3507
# So we need to offset it by one
3508
revno = revision[0].in_history(b).revno+1
3510
if revno <= b.revno():
3511
rev_id = b.get_rev_id(revno)
3513
self.outf.write('No revisions to uncommit.\n')
3516
lf = log_formatter('short',
3518
show_timezone='original')
3523
direction='forward',
3524
start_revision=revno,
3525
end_revision=b.revno())
3528
print 'Dry-run, pretending to remove the above revisions.'
3530
val = raw_input('Press <enter> to continue')
3532
print 'The above revision(s) will be removed.'
3534
val = raw_input('Are you sure [y/N]? ')
3535
if val.lower() not in ('y', 'yes'):
3539
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3543
class cmd_break_lock(Command):
3544
"""Break a dead lock on a repository, branch or working directory.
3546
CAUTION: Locks should only be broken when you are sure that the process
3547
holding the lock has been stopped.
3549
You can get information on what locks are open via the 'bzr info' command.
3554
takes_args = ['location?']
3556
def run(self, location=None, show=False):
3557
if location is None:
3559
control, relpath = bzrdir.BzrDir.open_containing(location)
3561
control.break_lock()
3562
except NotImplementedError:
3566
class cmd_wait_until_signalled(Command):
3567
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3569
This just prints a line to signal when it is ready, then blocks on stdin.
3575
sys.stdout.write("running\n")
3577
sys.stdin.readline()
3580
class cmd_serve(Command):
3581
"""Run the bzr server."""
3583
aliases = ['server']
3587
help='Serve on stdin/out for use from inetd or sshd.'),
3589
help='Listen for connections on nominated port of the form '
3590
'[hostname:]portnumber. Passing 0 as the port number will '
3591
'result in a dynamically allocated port. The default port is '
3595
help='Serve contents of this directory.',
3597
Option('allow-writes',
3598
help='By default the server is a readonly server. Supplying '
3599
'--allow-writes enables write access to the contents of '
3600
'the served directory and below.'
3604
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3605
from bzrlib.smart import medium, server
3606
from bzrlib.transport import get_transport
3607
from bzrlib.transport.chroot import ChrootServer
3608
from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
3609
if directory is None:
3610
directory = os.getcwd()
3611
url = urlutils.local_path_to_url(directory)
3612
if not allow_writes:
3613
url = 'readonly+' + url
3614
chroot_server = ChrootServer(get_transport(url))
3615
chroot_server.setUp()
3616
t = get_transport(chroot_server.get_url())
3618
smart_server = medium.SmartServerPipeStreamMedium(
3619
sys.stdin, sys.stdout, t)
3621
host = BZR_DEFAULT_INTERFACE
3623
port = BZR_DEFAULT_PORT
3626
host, port = port.split(':')
3628
smart_server = server.SmartTCPServer(t, host=host, port=port)
3629
print 'listening on port: ', smart_server.port
3631
# for the duration of this server, no UI output is permitted.
3632
# note that this may cause problems with blackbox tests. This should
3633
# be changed with care though, as we dont want to use bandwidth sending
3634
# progress over stderr to smart server clients!
3635
old_factory = ui.ui_factory
3637
ui.ui_factory = ui.SilentUIFactory()
3638
smart_server.serve()
3640
ui.ui_factory = old_factory
3643
class cmd_join(Command):
3644
"""Combine a subtree into its containing tree.
3646
This command is for experimental use only. It requires the target tree
3647
to be in dirstate-with-subtree format, which cannot be converted into
3650
The TREE argument should be an independent tree, inside another tree, but
3651
not part of it. (Such trees can be produced by "bzr split", but also by
3652
running "bzr branch" with the target inside a tree.)
3654
The result is a combined tree, with the subtree no longer an independant
3655
part. This is marked as a merge of the subtree into the containing tree,
3656
and all history is preserved.
3658
If --reference is specified, the subtree retains its independence. It can
3659
be branched by itself, and can be part of multiple projects at the same
3660
time. But operations performed in the containing tree, such as commit
3661
and merge, will recurse into the subtree.
3664
_see_also = ['split']
3665
takes_args = ['tree']
3667
Option('reference', help='Join by reference.'),
3671
def run(self, tree, reference=False):
3672
sub_tree = WorkingTree.open(tree)
3673
parent_dir = osutils.dirname(sub_tree.basedir)
3674
containing_tree = WorkingTree.open_containing(parent_dir)[0]
3675
repo = containing_tree.branch.repository
3676
if not repo.supports_rich_root():
3677
raise errors.BzrCommandError(
3678
"Can't join trees because %s doesn't support rich root data.\n"
3679
"You can use bzr upgrade on the repository."
3683
containing_tree.add_reference(sub_tree)
3684
except errors.BadReferenceTarget, e:
3685
# XXX: Would be better to just raise a nicely printable
3686
# exception from the real origin. Also below. mbp 20070306
3687
raise errors.BzrCommandError("Cannot join %s. %s" %
3691
containing_tree.subsume(sub_tree)
3692
except errors.BadSubsumeSource, e:
3693
raise errors.BzrCommandError("Cannot join %s. %s" %
3697
class cmd_split(Command):
3698
"""Split a tree into two trees.
3700
This command is for experimental use only. It requires the target tree
3701
to be in dirstate-with-subtree format, which cannot be converted into
3704
The TREE argument should be a subdirectory of a working tree. That
3705
subdirectory will be converted into an independent tree, with its own
3706
branch. Commits in the top-level tree will not apply to the new subtree.
3707
If you want that behavior, do "bzr join --reference TREE".
3710
_see_also = ['join']
3711
takes_args = ['tree']
3715
def run(self, tree):
3716
containing_tree, subdir = WorkingTree.open_containing(tree)
3717
sub_id = containing_tree.path2id(subdir)
3719
raise errors.NotVersionedError(subdir)
3721
containing_tree.extract(sub_id)
3722
except errors.RootNotRich:
3723
raise errors.UpgradeRequired(containing_tree.branch.base)
3727
class cmd_merge_directive(Command):
3728
"""Generate a merge directive for auto-merge tools.
3730
A directive requests a merge to be performed, and also provides all the
3731
information necessary to do so. This means it must either include a
3732
revision bundle, or the location of a branch containing the desired
3735
A submit branch (the location to merge into) must be supplied the first
3736
time the command is issued. After it has been supplied once, it will
3737
be remembered as the default.
3739
A public branch is optional if a revision bundle is supplied, but required
3740
if --diff or --plain is specified. It will be remembered as the default
3741
after the first use.
3744
takes_args = ['submit_branch?', 'public_branch?']
3748
_see_also = ['send']
3751
RegistryOption.from_kwargs('patch-type',
3752
'The type of patch to include in the directive.',
3754
value_switches=True,
3756
bundle='Bazaar revision bundle (default).',
3757
diff='Normal unified diff.',
3758
plain='No patch, just directive.'),
3759
Option('sign', help='GPG-sign the directive.'), 'revision',
3760
Option('mail-to', type=str,
3761
help='Instead of printing the directive, email to this address.'),
3762
Option('message', type=str, short_name='m',
3763
help='Message to use when committing this merge.')
3766
encoding_type = 'exact'
3768
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
3769
sign=False, revision=None, mail_to=None, message=None):
3770
from bzrlib.revision import ensure_null, NULL_REVISION
3771
include_patch, include_bundle = {
3772
'plain': (False, False),
3773
'diff': (True, False),
3774
'bundle': (True, True),
3776
branch = Branch.open('.')
3777
stored_submit_branch = branch.get_submit_branch()
3778
if submit_branch is None:
3779
submit_branch = stored_submit_branch
3781
if stored_submit_branch is None:
3782
branch.set_submit_branch(submit_branch)
3783
if submit_branch is None:
3784
submit_branch = branch.get_parent()
3785
if submit_branch is None:
3786
raise errors.BzrCommandError('No submit branch specified or known')
3788
stored_public_branch = branch.get_public_branch()
3789
if public_branch is None:
3790
public_branch = stored_public_branch
3791
elif stored_public_branch is None:
3792
branch.set_public_branch(public_branch)
3793
if not include_bundle and public_branch is None:
3794
raise errors.BzrCommandError('No public branch specified or'
3796
base_revision_id = None
3797
if revision is not None:
3798
if len(revision) > 2:
3799
raise errors.BzrCommandError('bzr merge-directive takes '
3800
'at most two one revision identifiers')
3801
revision_id = revision[-1].in_history(branch).rev_id
3802
if len(revision) == 2:
3803
base_revision_id = revision[0].in_history(branch).rev_id
3804
base_revision_id = ensure_null(base_revision_id)
3806
revision_id = branch.last_revision()
3807
revision_id = ensure_null(revision_id)
3808
if revision_id == NULL_REVISION:
3809
raise errors.BzrCommandError('No revisions to bundle.')
3810
directive = merge_directive.MergeDirective2.from_objects(
3811
branch.repository, revision_id, time.time(),
3812
osutils.local_time_offset(), submit_branch,
3813
public_branch=public_branch, include_patch=include_patch,
3814
include_bundle=include_bundle, message=message,
3815
base_revision_id=base_revision_id)
3818
self.outf.write(directive.to_signed(branch))
3820
self.outf.writelines(directive.to_lines())
3822
message = directive.to_email(mail_to, branch, sign)
3823
s = SMTPConnection(branch.get_config())
3824
s.send_email(message)
3827
class cmd_send(Command):
3828
"""Mail or create a merge-directive for submiting changes.
3830
A merge directive provides many things needed for requesting merges:
3832
* A machine-readable description of the merge to perform
3834
* An optional patch that is a preview of the changes requested
3836
* An optional bundle of revision data, so that the changes can be applied
3837
directly from the merge directive, without retrieving data from a
3840
If --no-bundle is specified, then public_branch is needed (and must be
3841
up-to-date), so that the receiver can perform the merge using the
3842
public_branch. The public_branch is always included if known, so that
3843
people can check it later.
3845
The submit branch defaults to the parent, but can be overridden. Both
3846
submit branch and public branch will be remembered if supplied.
3848
If a public_branch is known for the submit_branch, that public submit
3849
branch is used in the merge instructions. This means that a local mirror
3850
can be used as your actual submit branch, once you have set public_branch
3853
Mail is sent using your preferred mail program. This should be transparent
3854
on Windows (it uses MAPI). On *nix, it requires the xdg-email utility. If
3855
the preferred client can't be found (or used), your editor will be used.
3857
To use a specific mail program, set the mail_client configuration option.
3858
(For Thunderbird 1.5, this works around some bugs.) Supported values for
3859
specific clients are "evolution", "kmail", "mutt", and "thunderbird";
3860
generic options are "default", "editor", "mapi", and "xdg-email".
3862
If mail is being sent, a to address is required. This can be supplied
3863
either on the commandline, or by setting the submit_to configuration
3866
Two formats are currently supported: "4" uses revision bundle format 4 and
3867
merge directive format 2. It is significantly faster and smaller than
3868
older formats. It is compatible with Bazaar 0.19 and later. It is the
3869
default. "0.9" uses revision bundle format 0.9 and merge directive
3870
format 1. It is compatible with Bazaar 0.12 - 0.18.
3873
encoding_type = 'exact'
3875
_see_also = ['merge']
3877
takes_args = ['submit_branch?', 'public_branch?']
3881
help='Do not include a bundle in the merge directive.'),
3882
Option('no-patch', help='Do not include a preview patch in the merge'
3885
help='Remember submit and public branch.'),
3887
help='Branch to generate the submission from, '
3888
'rather than the one containing the working directory.',
3891
Option('output', short_name='o', help='Write directive to this file.',
3893
Option('mail-to', help='Mail the request to this address.',
3897
RegistryOption.from_kwargs('format',
3898
'Use the specified output format.',
3899
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
3900
'0.9': 'Bundle format 0.9, Merge Directive 1',})
3903
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
3904
no_patch=False, revision=None, remember=False, output=None,
3905
format='4', mail_to=None, message=None, **kwargs):
3906
return self._run(submit_branch, revision, public_branch, remember,
3907
format, no_bundle, no_patch, output,
3908
kwargs.get('from', '.'), mail_to, message)
3910
def _run(self, submit_branch, revision, public_branch, remember, format,
3911
no_bundle, no_patch, output, from_, mail_to, message):
3912
from bzrlib.revision import ensure_null, NULL_REVISION
3914
outfile = StringIO()
3918
outfile = open(output, 'wb')
3920
branch = Branch.open_containing(from_)[0]
3922
config = branch.get_config()
3924
mail_to = config.get_user_option('submit_to')
3926
raise errors.BzrCommandError('No mail-to address'
3928
mail_client = config.get_mail_client()
3929
if remember and submit_branch is None:
3930
raise errors.BzrCommandError(
3931
'--remember requires a branch to be specified.')
3932
stored_submit_branch = branch.get_submit_branch()
3933
remembered_submit_branch = False
3934
if submit_branch is None:
3935
submit_branch = stored_submit_branch
3936
remembered_submit_branch = True
3938
if stored_submit_branch is None or remember:
3939
branch.set_submit_branch(submit_branch)
3940
if submit_branch is None:
3941
submit_branch = branch.get_parent()
3942
remembered_submit_branch = True
3943
if submit_branch is None:
3944
raise errors.BzrCommandError('No submit branch known or'
3946
if remembered_submit_branch:
3947
note('Using saved location: %s', submit_branch)
3949
stored_public_branch = branch.get_public_branch()
3950
if public_branch is None:
3951
public_branch = stored_public_branch
3952
elif stored_public_branch is None or remember:
3953
branch.set_public_branch(public_branch)
3954
if no_bundle and public_branch is None:
3955
raise errors.BzrCommandError('No public branch specified or'
3957
base_revision_id = None
3959
if revision is not None:
3960
if len(revision) > 2:
3961
raise errors.BzrCommandError('bzr send takes '
3962
'at most two one revision identifiers')
3963
revision_id = revision[-1].in_history(branch).rev_id
3964
if len(revision) == 2:
3965
base_revision_id = revision[0].in_history(branch).rev_id
3966
if revision_id is None:
3967
revision_id = branch.last_revision()
3968
if revision_id == NULL_REVISION:
3969
raise errors.BzrCommandError('No revisions to submit.')
3971
directive = merge_directive.MergeDirective2.from_objects(
3972
branch.repository, revision_id, time.time(),
3973
osutils.local_time_offset(), submit_branch,
3974
public_branch=public_branch, include_patch=not no_patch,
3975
include_bundle=not no_bundle, message=message,
3976
base_revision_id=base_revision_id)
3977
elif format == '0.9':
3980
patch_type = 'bundle'
3982
raise errors.BzrCommandError('Format 0.9 does not'
3983
' permit bundle with no patch')
3989
directive = merge_directive.MergeDirective.from_objects(
3990
branch.repository, revision_id, time.time(),
3991
osutils.local_time_offset(), submit_branch,
3992
public_branch=public_branch, patch_type=patch_type,
3995
outfile.writelines(directive.to_lines())
3997
subject = '[MERGE] '
3998
if message is not None:
4001
revision = branch.repository.get_revision(revision_id)
4002
subject += revision.get_summary()
4003
mail_client.compose_merge_request(mail_to, subject,
4010
class cmd_bundle_revisions(cmd_send):
4012
"""Create a merge-directive for submiting changes.
4014
A merge directive provides many things needed for requesting merges:
4016
* A machine-readable description of the merge to perform
4018
* An optional patch that is a preview of the changes requested
4020
* An optional bundle of revision data, so that the changes can be applied
4021
directly from the merge directive, without retrieving data from a
4024
If --no-bundle is specified, then public_branch is needed (and must be
4025
up-to-date), so that the receiver can perform the merge using the
4026
public_branch. The public_branch is always included if known, so that
4027
people can check it later.
4029
The submit branch defaults to the parent, but can be overridden. Both
4030
submit branch and public branch will be remembered if supplied.
4032
If a public_branch is known for the submit_branch, that public submit
4033
branch is used in the merge instructions. This means that a local mirror
4034
can be used as your actual submit branch, once you have set public_branch
4037
Two formats are currently supported: "4" uses revision bundle format 4 and
4038
merge directive format 2. It is significantly faster and smaller than
4039
older formats. It is compatible with Bazaar 0.19 and later. It is the
4040
default. "0.9" uses revision bundle format 0.9 and merge directive
4041
format 1. It is compatible with Bazaar 0.12 - 0.18.
4046
help='Do not include a bundle in the merge directive.'),
4047
Option('no-patch', help='Do not include a preview patch in the merge'
4050
help='Remember submit and public branch.'),
4052
help='Branch to generate the submission from, '
4053
'rather than the one containing the working directory.',
4056
Option('output', short_name='o', help='Write directive to this file.',
4059
RegistryOption.from_kwargs('format',
4060
'Use the specified output format.',
4061
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4062
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4064
aliases = ['bundle']
4066
_see_also = ['send', 'merge']
4070
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4071
no_patch=False, revision=None, remember=False, output=None,
4072
format='4', **kwargs):
4075
return self._run(submit_branch, revision, public_branch, remember,
4076
format, no_bundle, no_patch, output,
4077
kwargs.get('from', '.'), None, None)
4080
class cmd_tag(Command):
4081
"""Create, remove or modify a tag naming a revision.
4083
Tags give human-meaningful names to revisions. Commands that take a -r
4084
(--revision) option can be given -rtag:X, where X is any previously
4087
Tags are stored in the branch. Tags are copied from one branch to another
4088
along when you branch, push, pull or merge.
4090
It is an error to give a tag name that already exists unless you pass
4091
--force, in which case the tag is moved to point to the new revision.
4094
_see_also = ['commit', 'tags']
4095
takes_args = ['tag_name']
4098
help='Delete this tag rather than placing it.',
4101
help='Branch in which to place the tag.',
4106
help='Replace existing tags.',
4111
def run(self, tag_name,
4117
branch, relpath = Branch.open_containing(directory)
4121
branch.tags.delete_tag(tag_name)
4122
self.outf.write('Deleted tag %s.\n' % tag_name)
4125
if len(revision) != 1:
4126
raise errors.BzrCommandError(
4127
"Tags can only be placed on a single revision, "
4129
revision_id = revision[0].in_history(branch).rev_id
4131
revision_id = branch.last_revision()
4132
if (not force) and branch.tags.has_tag(tag_name):
4133
raise errors.TagAlreadyExists(tag_name)
4134
branch.tags.set_tag(tag_name, revision_id)
4135
self.outf.write('Created tag %s.\n' % tag_name)
4140
class cmd_tags(Command):
4143
This tag shows a table of tag names and the revisions they reference.
4149
help='Branch whose tags should be displayed.',
4159
branch, relpath = Branch.open_containing(directory)
4160
for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4161
self.outf.write('%-20s %s\n' % (tag_name, target))
4164
class cmd_reconfigure(Command):
4165
"""Reconfigure the type of a bzr directory.
4167
A target configuration must be specified.
4169
For checkouts, the bind-to location will be auto-detected if not specified.
4170
The order of preference is
4171
1. For a lightweight checkout, the current bound location.
4172
2. For branches that used to be checkouts, the previously-bound location.
4173
3. The push location.
4174
4. The parent location.
4175
If none of these is available, --bind-to must be specified.
4178
takes_args = ['location?']
4179
takes_options = [RegistryOption.from_kwargs('target_type',
4180
title='Target type',
4181
help='The type to reconfigure the directory to.',
4182
value_switches=True, enum_switch=False,
4183
branch='Reconfigure to a branch.',
4184
tree='Reconfigure to a tree.',
4185
checkout='Reconfigure to a checkout.'),
4186
Option('bind-to', help='Branch to bind checkout to.',
4189
help='Perform reconfiguration even if local changes'
4193
def run(self, location=None, target_type=None, bind_to=None, force=False):
4194
directory = bzrdir.BzrDir.open(location)
4195
if target_type is None:
4196
raise errors.BzrCommandError('No target configuration specified')
4197
elif target_type == 'branch':
4198
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4199
elif target_type == 'tree':
4200
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4201
elif target_type == 'checkout':
4202
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4204
reconfiguration.apply(force)
4207
def _create_prefix(cur_transport):
4208
needed = [cur_transport]
4209
# Recurse upwards until we can create a directory successfully
4211
new_transport = cur_transport.clone('..')
4212
if new_transport.base == cur_transport.base:
4213
raise errors.BzrCommandError(
4214
"Failed to create path prefix for %s."
4215
% cur_transport.base)
4217
new_transport.mkdir('.')
4218
except errors.NoSuchFile:
4219
needed.append(new_transport)
4220
cur_transport = new_transport
4223
# Now we only need to create child directories
4225
cur_transport = needed.pop()
4226
cur_transport.ensure_base()
4229
def _get_mergeable_helper(location):
4230
"""Get a merge directive or bundle if 'location' points to one.
4232
Try try to identify a bundle and returns its mergeable form. If it's not,
4233
we return the tried transport anyway so that it can reused to access the
4236
:param location: can point to a bundle or a branch.
4238
:return: mergeable, transport
4241
url = urlutils.normalize_url(location)
4242
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4243
location_transport = transport.get_transport(url)
4246
# There may be redirections but we ignore the intermediate
4247
# and final transports used
4248
read = bundle.read_mergeable_from_transport
4249
mergeable, t = read(location_transport, filename)
4250
except errors.NotABundle:
4251
# Continue on considering this url a Branch but adjust the
4252
# location_transport
4253
location_transport = location_transport.clone(filename)
4254
return mergeable, location_transport
4257
# these get imported and then picked up by the scan for cmd_*
4258
# TODO: Some more consistent way to split command definitions across files;
4259
# we do need to load at least some information about them to know of
4260
# aliases. ideally we would avoid loading the implementation until the
4261
# details were needed.
4262
from bzrlib.cmd_version_info import cmd_version_info
4263
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4264
from bzrlib.bundle.commands import (
4267
from bzrlib.sign_my_commits import cmd_sign_my_commits
4268
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4269
cmd_weave_plan_merge, cmd_weave_merge_text