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(), """
53
from bzrlib.branch import Branch
54
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
55
from bzrlib.conflicts import ConflictList
56
from bzrlib.revision import common_ancestor
57
from bzrlib.revisionspec import RevisionSpec
58
from bzrlib.workingtree import WorkingTree
61
from bzrlib.commands import Command, display_command
62
from bzrlib.option import Option, RegistryOption
63
from bzrlib.progress import DummyProgress, ProgressPhase
64
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
67
def tree_files(file_list, default_branch=u'.'):
69
return internal_tree_files(file_list, default_branch)
70
except errors.FileInWrongBranch, e:
71
raise errors.BzrCommandError("%s is not in the same branch as %s" %
72
(e.path, file_list[0]))
75
# XXX: Bad function name; should possibly also be a class method of
76
# WorkingTree rather than a function.
77
def internal_tree_files(file_list, default_branch=u'.'):
78
"""Convert command-line paths to a WorkingTree and relative paths.
80
This is typically used for command-line processors that take one or
81
more filenames, and infer the workingtree that contains them.
83
The filenames given are not required to exist.
85
:param file_list: Filenames to convert.
87
:param default_branch: Fallback tree path to use if file_list is empty or
90
:return: workingtree, [relative_paths]
92
if file_list is None or len(file_list) == 0:
93
return WorkingTree.open_containing(default_branch)[0], file_list
94
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
96
for filename in file_list:
98
new_list.append(tree.relpath(osutils.dereference_path(filename)))
99
except errors.PathNotChild:
100
raise errors.FileInWrongBranch(tree.branch, filename)
101
return tree, new_list
104
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
105
def get_format_type(typestring):
106
"""Parse and return a format specifier."""
107
# Have to use BzrDirMetaFormat1 directly, so that
108
# RepositoryFormat.set_default_format works
109
if typestring == "default":
110
return bzrdir.BzrDirMetaFormat1()
112
return bzrdir.format_registry.make_bzrdir(typestring)
114
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
115
raise errors.BzrCommandError(msg)
118
# TODO: Make sure no commands unconditionally use the working directory as a
119
# branch. If a filename argument is used, the first of them should be used to
120
# specify the branch. (Perhaps this can be factored out into some kind of
121
# Argument class, representing a file in a branch, where the first occurrence
124
class cmd_status(Command):
125
"""Display status summary.
127
This reports on versioned and unknown files, reporting them
128
grouped by state. Possible states are:
131
Versioned in the working copy but not in the previous revision.
134
Versioned in the previous revision but removed or deleted
138
Path of this file changed from the previous revision;
139
the text may also have changed. This includes files whose
140
parent directory was renamed.
143
Text has changed since the previous revision.
146
File kind has been changed (e.g. from file to directory).
149
Not versioned and not matching an ignore pattern.
151
To see ignored files use 'bzr ignored'. For details on the
152
changes to file texts, use 'bzr diff'.
154
--short gives a status flags for each item, similar to the SVN's status
157
Column 1: versioning / renames
163
P Entry for a pending merge (not a file)
172
* The execute bit was changed
174
If no arguments are specified, the status of the entire working
175
directory is shown. Otherwise, only the status of the specified
176
files or directories is reported. If a directory is given, status
177
is reported for everything inside that directory.
179
If a revision argument is given, the status is calculated against
180
that revision, or between two revisions if two are provided.
183
# TODO: --no-recurse, --recurse options
185
takes_args = ['file*']
186
takes_options = ['show-ids', 'revision',
187
Option('short', help='Give short SVN-style status lines'),
188
Option('versioned', help='Only show versioned files')]
189
aliases = ['st', 'stat']
191
encoding_type = 'replace'
192
_see_also = ['diff', 'revert']
195
def run(self, show_ids=False, file_list=None, revision=None, short=False,
197
from bzrlib.status import show_tree_status
199
tree, file_list = tree_files(file_list)
201
show_tree_status(tree, show_ids=show_ids,
202
specific_files=file_list, revision=revision,
203
to_file=self.outf, short=short, versioned=versioned)
206
class cmd_cat_revision(Command):
207
"""Write out metadata for a revision.
209
The revision to print can either be specified by a specific
210
revision identifier, or you can use --revision.
214
takes_args = ['revision_id?']
215
takes_options = ['revision']
216
# cat-revision is more for frontends so should be exact
220
def run(self, revision_id=None, revision=None):
222
revision_id = osutils.safe_revision_id(revision_id, warn=False)
223
if revision_id is not None and revision is not None:
224
raise errors.BzrCommandError('You can only supply one of'
225
' revision_id or --revision')
226
if revision_id is None and revision is None:
227
raise errors.BzrCommandError('You must supply either'
228
' --revision or a revision_id')
229
b = WorkingTree.open_containing(u'.')[0].branch
231
# TODO: jam 20060112 should cat-revision always output utf-8?
232
if revision_id is not None:
233
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
234
elif revision is not None:
237
raise errors.BzrCommandError('You cannot specify a NULL'
239
revno, rev_id = rev.in_history(b)
240
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
243
class cmd_remove_tree(Command):
244
"""Remove the working tree from a given branch/checkout.
246
Since a lightweight checkout is little more than a working tree
247
this will refuse to run against one.
249
To re-create the working tree, use "bzr checkout".
251
_see_also = ['checkout']
253
takes_args = ['location?']
255
def run(self, location='.'):
256
d = bzrdir.BzrDir.open(location)
259
working = d.open_workingtree()
260
except errors.NoWorkingTree:
261
raise errors.BzrCommandError("No working tree to remove")
262
except errors.NotLocalUrl:
263
raise errors.BzrCommandError("You cannot remove the working tree of a "
266
working_path = working.bzrdir.root_transport.base
267
branch_path = working.branch.bzrdir.root_transport.base
268
if working_path != branch_path:
269
raise errors.BzrCommandError("You cannot remove the working tree from "
270
"a lightweight checkout")
272
d.destroy_workingtree()
275
class cmd_revno(Command):
276
"""Show current revision number.
278
This is equal to the number of revisions on this branch.
282
takes_args = ['location?']
285
def run(self, location=u'.'):
286
self.outf.write(str(Branch.open_containing(location)[0].revno()))
287
self.outf.write('\n')
290
class cmd_revision_info(Command):
291
"""Show revision number and revision id for a given revision identifier.
294
takes_args = ['revision_info*']
295
takes_options = ['revision']
298
def run(self, revision=None, revision_info_list=[]):
301
if revision is not None:
302
revs.extend(revision)
303
if revision_info_list is not None:
304
for rev in revision_info_list:
305
revs.append(RevisionSpec.from_string(rev))
307
raise errors.BzrCommandError('You must supply a revision identifier')
309
b = WorkingTree.open_containing(u'.')[0].branch
312
revinfo = rev.in_history(b)
313
if revinfo.revno is None:
314
print ' %s' % revinfo.rev_id
316
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
319
class cmd_add(Command):
320
"""Add specified files or directories.
322
In non-recursive mode, all the named items are added, regardless
323
of whether they were previously ignored. A warning is given if
324
any of the named files are already versioned.
326
In recursive mode (the default), files are treated the same way
327
but the behaviour for directories is different. Directories that
328
are already versioned do not give a warning. All directories,
329
whether already versioned or not, are searched for files or
330
subdirectories that are neither versioned or ignored, and these
331
are added. This search proceeds recursively into versioned
332
directories. If no names are given '.' is assumed.
334
Therefore simply saying 'bzr add' will version all files that
335
are currently unknown.
337
Adding a file whose parent directory is not versioned will
338
implicitly add the parent, and so on up to the root. This means
339
you should never need to explicitly add a directory, they'll just
340
get added when you add a file in the directory.
342
--dry-run will show which files would be added, but not actually
345
--file-ids-from will try to use the file ids from the supplied path.
346
It looks up ids trying to find a matching parent directory with the
347
same filename, and then by pure path. This option is rarely needed
348
but can be useful when adding the same logical file into two
349
branches that will be merged later (without showing the two different
350
adds as a conflict). It is also useful when merging another project
351
into a subdirectory of this one.
353
takes_args = ['file*']
354
takes_options = ['no-recurse', 'dry-run', 'verbose',
355
Option('file-ids-from', type=unicode,
356
help='Lookup file ids from here')]
357
encoding_type = 'replace'
358
_see_also = ['remove']
360
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
365
if file_ids_from is not None:
367
base_tree, base_path = WorkingTree.open_containing(
369
except errors.NoWorkingTree:
370
base_branch, base_path = Branch.open_containing(
372
base_tree = base_branch.basis_tree()
374
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
375
to_file=self.outf, should_print=(not is_quiet()))
377
action = bzrlib.add.AddAction(to_file=self.outf,
378
should_print=(not is_quiet()))
381
base_tree.lock_read()
383
added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
384
action=action, save=not dry_run)
386
if base_tree is not None:
390
for glob in sorted(ignored.keys()):
391
for path in ignored[glob]:
392
self.outf.write("ignored %s matching \"%s\"\n"
396
for glob, paths in ignored.items():
397
match_len += len(paths)
398
self.outf.write("ignored %d file(s).\n" % match_len)
399
self.outf.write("If you wish to add some of these files,"
400
" please add them by name.\n")
403
class cmd_mkdir(Command):
404
"""Create a new versioned directory.
406
This is equivalent to creating the directory and then adding it.
409
takes_args = ['dir+']
410
encoding_type = 'replace'
412
def run(self, dir_list):
415
wt, dd = WorkingTree.open_containing(d)
417
self.outf.write('added %s\n' % d)
420
class cmd_relpath(Command):
421
"""Show path of a file relative to root"""
423
takes_args = ['filename']
427
def run(self, filename):
428
# TODO: jam 20050106 Can relpath return a munged path if
429
# sys.stdout encoding cannot represent it?
430
tree, relpath = WorkingTree.open_containing(filename)
431
self.outf.write(relpath)
432
self.outf.write('\n')
435
class cmd_inventory(Command):
436
"""Show inventory of the current working copy or a revision.
438
It is possible to limit the output to a particular entry
439
type using the --kind option. For example: --kind file.
441
It is also possible to restrict the list of files to a specific
442
set. For example: bzr inventory --show-ids this/file
447
takes_options = ['revision', 'show-ids', 'kind']
448
takes_args = ['file*']
451
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
452
if kind and kind not in ['file', 'directory', 'symlink']:
453
raise errors.BzrCommandError('invalid kind specified')
455
work_tree, file_list = tree_files(file_list)
456
work_tree.lock_read()
458
if revision is not None:
459
if len(revision) > 1:
460
raise errors.BzrCommandError(
461
'bzr inventory --revision takes exactly one revision'
463
revision_id = revision[0].in_history(work_tree.branch).rev_id
464
tree = work_tree.branch.repository.revision_tree(revision_id)
466
extra_trees = [work_tree]
472
if file_list is not None:
473
file_ids = tree.paths2ids(file_list, trees=extra_trees,
474
require_versioned=True)
475
# find_ids_across_trees may include some paths that don't
477
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
478
for file_id in file_ids if file_id in tree)
480
entries = tree.inventory.entries()
483
if tree is not work_tree:
486
for path, entry in entries:
487
if kind and kind != entry.kind:
490
self.outf.write('%-50s %s\n' % (path, entry.file_id))
492
self.outf.write(path)
493
self.outf.write('\n')
496
class cmd_mv(Command):
497
"""Move or rename a file.
500
bzr mv OLDNAME NEWNAME
501
bzr mv SOURCE... DESTINATION
503
If the last argument is a versioned directory, all the other names
504
are moved into it. Otherwise, there must be exactly two arguments
505
and the file is changed to a new name.
507
If OLDNAME does not exist on the filesystem but is versioned and
508
NEWNAME does exist on the filesystem but is not versioned, mv
509
assumes that the file has been manually moved and only updates
510
its internal inventory to reflect that change.
511
The same is valid when moving many SOURCE files to a DESTINATION.
513
Files cannot be moved between branches.
516
takes_args = ['names*']
517
takes_options = [Option("after", help="move only the bzr identifier"
518
" of the file (file has already been moved). Use this flag if"
519
" bzr is not able to detect this itself.")]
520
aliases = ['move', 'rename']
521
encoding_type = 'replace'
523
def run(self, names_list, after=False):
524
if names_list is None:
527
if len(names_list) < 2:
528
raise errors.BzrCommandError("missing file argument")
529
tree, rel_names = tree_files(names_list)
531
if os.path.isdir(names_list[-1]):
532
# move into existing directory
533
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
534
self.outf.write("%s => %s\n" % pair)
536
if len(names_list) != 2:
537
raise errors.BzrCommandError('to mv multiple files the'
538
' destination must be a versioned'
540
tree.rename_one(rel_names[0], rel_names[1], after=after)
541
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
544
class cmd_pull(Command):
545
"""Turn this branch into a mirror of another branch.
547
This command only works on branches that have not diverged. Branches are
548
considered diverged if the destination branch's most recent commit is one
549
that has not been merged (directly or indirectly) into the parent.
551
If branches have diverged, you can use 'bzr merge' to integrate the changes
552
from one into the other. Once one branch has merged, the other should
553
be able to pull it again.
555
If you want to forget your local changes and just update your branch to
556
match the remote one, use pull --overwrite.
558
If there is no default location set, the first pull will set it. After
559
that, you can omit the location to use the default. To change the
560
default, use --remember. The value will only be saved if the remote
561
location can be accessed.
564
_see_also = ['push', 'update']
565
takes_options = ['remember', 'overwrite', 'revision', 'verbose',
567
help='branch to pull into, '
568
'rather than the one containing the working directory',
573
takes_args = ['location?']
574
encoding_type = 'replace'
576
def run(self, location=None, remember=False, overwrite=False,
577
revision=None, verbose=False,
579
from bzrlib.tag import _merge_tags_if_possible
580
# FIXME: too much stuff is in the command class
583
if directory is None:
586
tree_to = WorkingTree.open_containing(directory)[0]
587
branch_to = tree_to.branch
588
except errors.NoWorkingTree:
590
branch_to = Branch.open_containing(directory)[0]
593
if location is not None:
595
mergeable = bundle.read_mergeable_from_url(
597
except errors.NotABundle:
598
pass # Continue on considering this url a Branch
600
stored_loc = branch_to.get_parent()
602
if stored_loc is None:
603
raise errors.BzrCommandError("No pull location known or"
606
display_url = urlutils.unescape_for_display(stored_loc,
608
self.outf.write("Using saved location: %s\n" % display_url)
609
location = stored_loc
611
if mergeable is not None:
612
if revision is not None:
613
raise errors.BzrCommandError(
614
'Cannot use -r with merge directives or bundles')
615
revision_id = mergeable.install_revisions(branch_to.repository)
616
branch_from = branch_to
618
branch_from = Branch.open(location)
620
if branch_to.get_parent() is None or remember:
621
branch_to.set_parent(branch_from.base)
623
if revision is not None:
624
if len(revision) == 1:
625
revision_id = revision[0].in_history(branch_from).rev_id
627
raise errors.BzrCommandError(
628
'bzr pull --revision takes one value.')
630
old_rh = branch_to.revision_history()
631
if tree_to is not None:
632
result = tree_to.pull(branch_from, overwrite, revision_id,
633
delta._ChangeReporter(unversioned_filter=tree_to.is_ignored))
635
result = branch_to.pull(branch_from, overwrite, revision_id)
637
result.report(self.outf)
639
from bzrlib.log import show_changed_revisions
640
new_rh = branch_to.revision_history()
641
show_changed_revisions(branch_to, old_rh, new_rh,
645
class cmd_push(Command):
646
"""Update a mirror of this branch.
648
The target branch will not have its working tree populated because this
649
is both expensive, and is not supported on remote file systems.
651
Some smart servers or protocols *may* put the working tree in place in
654
This command only works on branches that have not diverged. Branches are
655
considered diverged if the destination branch's most recent commit is one
656
that has not been merged (directly or indirectly) by the source branch.
658
If branches have diverged, you can use 'bzr push --overwrite' to replace
659
the other branch completely, discarding its unmerged changes.
661
If you want to ensure you have the different changes in the other branch,
662
do a merge (see bzr help merge) from the other branch, and commit that.
663
After that you will be able to do a push without '--overwrite'.
665
If there is no default push location set, the first push will set it.
666
After that, you can omit the location to use the default. To change the
667
default, use --remember. The value will only be saved if the remote
668
location can be accessed.
671
_see_also = ['pull', 'update']
672
takes_options = ['remember', 'overwrite', 'verbose',
673
Option('create-prefix',
674
help='Create the path leading up to the branch '
675
'if it does not already exist'),
677
help='branch to push from, '
678
'rather than the one containing the working directory',
682
Option('use-existing-dir',
683
help='By default push will fail if the target'
684
' directory exists, but does not already'
685
' have a control directory. This flag will'
686
' allow push to proceed.'),
688
takes_args = ['location?']
689
encoding_type = 'replace'
691
def run(self, location=None, remember=False, overwrite=False,
692
create_prefix=False, verbose=False,
693
use_existing_dir=False,
695
# FIXME: Way too big! Put this into a function called from the
697
if directory is None:
699
br_from = Branch.open_containing(directory)[0]
700
stored_loc = br_from.get_push_location()
702
if stored_loc is None:
703
raise errors.BzrCommandError("No push location known or specified.")
705
display_url = urlutils.unescape_for_display(stored_loc,
707
self.outf.write("Using saved location: %s\n" % display_url)
708
location = stored_loc
710
to_transport = transport.get_transport(location)
711
location_url = to_transport.base
713
br_to = repository_to = dir_to = None
715
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
716
except errors.NotBranchError:
717
pass # Didn't find anything
719
# If we can open a branch, use its direct repository, otherwise see
720
# if there is a repository without a branch.
722
br_to = dir_to.open_branch()
723
except errors.NotBranchError:
724
# Didn't find a branch, can we find a repository?
726
repository_to = dir_to.find_repository()
727
except errors.NoRepositoryPresent:
730
# Found a branch, so we must have found a repository
731
repository_to = br_to.repository
735
# The destination doesn't exist; create it.
736
# XXX: Refactor the create_prefix/no_create_prefix code into a
737
# common helper function
739
to_transport.mkdir('.')
740
except errors.FileExists:
741
if not use_existing_dir:
742
raise errors.BzrCommandError("Target directory %s"
743
" already exists, but does not have a valid .bzr"
744
" directory. Supply --use-existing-dir to push"
745
" there anyway." % location)
746
except errors.NoSuchFile:
747
if not create_prefix:
748
raise errors.BzrCommandError("Parent directory of %s"
750
"\nYou may supply --create-prefix to create all"
751
" leading parent directories."
754
cur_transport = to_transport
755
needed = [cur_transport]
756
# Recurse upwards until we can create a directory successfully
758
new_transport = cur_transport.clone('..')
759
if new_transport.base == cur_transport.base:
760
raise errors.BzrCommandError("Failed to create path"
764
new_transport.mkdir('.')
765
except errors.NoSuchFile:
766
needed.append(new_transport)
767
cur_transport = new_transport
771
# Now we only need to create child directories
773
cur_transport = needed.pop()
774
cur_transport.mkdir('.')
776
# Now the target directory exists, but doesn't have a .bzr
777
# directory. So we need to create it, along with any work to create
778
# all of the dependent branches, etc.
779
dir_to = br_from.bzrdir.clone(location_url,
780
revision_id=br_from.last_revision())
781
br_to = dir_to.open_branch()
782
# TODO: Some more useful message about what was copied
783
note('Created new branch.')
784
# We successfully created the target, remember it
785
if br_from.get_push_location() is None or remember:
786
br_from.set_push_location(br_to.base)
787
elif repository_to is None:
788
# we have a bzrdir but no branch or repository
789
# XXX: Figure out what to do other than complain.
790
raise errors.BzrCommandError("At %s you have a valid .bzr control"
791
" directory, but not a branch or repository. This is an"
792
" unsupported configuration. Please move the target directory"
793
" out of the way and try again."
796
# We have a repository but no branch, copy the revisions, and then
798
last_revision_id = br_from.last_revision()
799
repository_to.fetch(br_from.repository,
800
revision_id=last_revision_id)
801
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
802
note('Created new branch.')
803
if br_from.get_push_location() is None or remember:
804
br_from.set_push_location(br_to.base)
805
else: # We have a valid to branch
806
# We were able to connect to the remote location, so remember it
807
# we don't need to successfully push because of possible divergence.
808
if br_from.get_push_location() is None or remember:
809
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' % (br_to.base,))
817
push_result = br_from.push(br_to, overwrite)
818
except errors.NoWorkingTree:
819
push_result = br_from.push(br_to, overwrite)
823
push_result = br_from.push(tree_to.branch, overwrite)
827
except errors.DivergedBranches:
828
raise errors.BzrCommandError('These branches have diverged.'
829
' Try using "merge" and then "push".')
830
if push_result is not None:
831
push_result.report(self.outf)
833
new_rh = br_to.revision_history()
836
from bzrlib.log import show_changed_revisions
837
show_changed_revisions(br_to, old_rh, new_rh,
840
# we probably did a clone rather than a push, so a message was
845
class cmd_branch(Command):
846
"""Create a new copy of a branch.
848
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
849
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
851
To retrieve the branch as of a particular revision, supply the --revision
852
parameter, as in "branch foo/bar -r 5".
855
_see_also = ['checkout']
856
takes_args = ['from_location', 'to_location?']
857
takes_options = ['revision']
858
aliases = ['get', 'clone']
860
def run(self, from_location, to_location=None, revision=None):
861
from bzrlib.tag import _merge_tags_if_possible
864
elif len(revision) > 1:
865
raise errors.BzrCommandError(
866
'bzr branch --revision takes exactly 1 revision value')
868
br_from = Branch.open(from_location)
871
if len(revision) == 1 and revision[0] is not None:
872
revision_id = revision[0].in_history(br_from)[1]
874
# FIXME - wt.last_revision, fallback to branch, fall back to
875
# None or perhaps NULL_REVISION to mean copy nothing
877
revision_id = br_from.last_revision()
878
if to_location is None:
879
to_location = os.path.basename(from_location.rstrip("/\\"))
882
name = os.path.basename(to_location) + '\n'
884
to_transport = transport.get_transport(to_location)
886
to_transport.mkdir('.')
887
except errors.FileExists:
888
raise errors.BzrCommandError('Target directory "%s" already'
889
' exists.' % to_location)
890
except errors.NoSuchFile:
891
raise errors.BzrCommandError('Parent of "%s" does not exist.'
894
# preserve whatever source format we have.
895
dir = br_from.bzrdir.sprout(to_transport.base, revision_id)
896
branch = dir.open_branch()
897
except errors.NoSuchRevision:
898
to_transport.delete_tree('.')
899
msg = "The branch %s has no revision %s." % (from_location, revision[0])
900
raise errors.BzrCommandError(msg)
902
branch.control_files.put_utf8('branch-name', name)
903
_merge_tags_if_possible(br_from, branch)
904
note('Branched %d revision(s).' % branch.revno())
909
class cmd_checkout(Command):
910
"""Create a new checkout of an existing branch.
912
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
913
the branch found in '.'. This is useful if you have removed the working tree
914
or if it was never created - i.e. if you pushed the branch to its current
917
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
918
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
920
To retrieve the branch as of a particular revision, supply the --revision
921
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
922
out of date [so you cannot commit] but it may be useful (i.e. to examine old
926
_see_also = ['checkouts', 'branch']
927
takes_args = ['branch_location?', 'to_location?']
928
takes_options = ['revision',
929
Option('lightweight',
930
help="perform a lightweight checkout. Lightweight "
931
"checkouts depend on access to the branch for "
932
"every operation. Normal checkouts can perform "
933
"common operations like diff and status without "
934
"such access, and also support local commits."
939
def run(self, branch_location=None, to_location=None, revision=None,
943
elif len(revision) > 1:
944
raise errors.BzrCommandError(
945
'bzr checkout --revision takes exactly 1 revision value')
946
if branch_location is None:
947
branch_location = osutils.getcwd()
948
to_location = branch_location
949
source = Branch.open(branch_location)
950
if len(revision) == 1 and revision[0] is not None:
951
revision_id = revision[0].in_history(source)[1]
954
if to_location is None:
955
to_location = os.path.basename(branch_location.rstrip("/\\"))
956
# if the source and to_location are the same,
957
# and there is no working tree,
958
# then reconstitute a branch
959
if (osutils.abspath(to_location) ==
960
osutils.abspath(branch_location)):
962
source.bzrdir.open_workingtree()
963
except errors.NoWorkingTree:
964
source.bzrdir.create_workingtree()
967
os.mkdir(to_location)
969
if e.errno == errno.EEXIST:
970
raise errors.BzrCommandError('Target directory "%s" already'
971
' exists.' % to_location)
972
if e.errno == errno.ENOENT:
973
raise errors.BzrCommandError('Parent of "%s" does not exist.'
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']
1021
takes_args = ['dir?']
1024
def run(self, dir='.'):
1025
tree = WorkingTree.open_containing(dir)[0]
1026
master = tree.branch.get_master_branch()
1027
if master is not None:
1030
tree.lock_tree_write()
1032
existing_pending_merges = tree.get_parent_ids()[1:]
1033
last_rev = tree.last_revision()
1034
if last_rev == tree.branch.last_revision():
1035
# may be up to date, check master too.
1036
master = tree.branch.get_master_branch()
1037
if master is None or last_rev == master.last_revision():
1038
revno = tree.branch.revision_id_to_revno(last_rev)
1039
note("Tree is up to date at revision %d." % (revno,))
1041
conflicts = tree.update()
1042
revno = tree.branch.revision_id_to_revno(tree.last_revision())
1043
note('Updated to revision %d.' % (revno,))
1044
if tree.get_parent_ids()[1:] != existing_pending_merges:
1045
note('Your local commits will now show as pending merges with '
1046
"'bzr status', and can be committed with 'bzr commit'.")
1055
class cmd_info(Command):
1056
"""Show information about a working tree, branch or repository.
1058
This command will show all known locations and formats associated to the
1059
tree, branch or repository. Statistical information is included with
1062
Branches and working trees will also report any missing revisions.
1064
_see_also = ['revno']
1065
takes_args = ['location?']
1066
takes_options = ['verbose']
1069
def run(self, location=None, verbose=False):
1070
from bzrlib.info import show_bzrdir_info
1071
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1075
class cmd_remove(Command):
1076
"""Make a file unversioned.
1078
This makes bzr stop tracking changes to a versioned file. It does
1079
not delete the working copy.
1081
You can specify one or more files, and/or --new. If you specify --new,
1082
only 'added' files will be removed. If you specify both, then new files
1083
in the specified directories will be removed. If the directories are
1084
also new, they will also be removed.
1086
takes_args = ['file*']
1087
takes_options = ['verbose', Option('new', help='remove newly-added files')]
1089
encoding_type = 'replace'
1091
def run(self, file_list, verbose=False, new=False):
1092
tree, file_list = tree_files(file_list)
1094
if file_list is None:
1095
raise errors.BzrCommandError('Specify one or more files to'
1096
' remove, or use --new.')
1098
added = tree.changes_from(tree.basis_tree(),
1099
specific_files=file_list).added
1100
file_list = sorted([f[0] for f in added], reverse=True)
1101
if len(file_list) == 0:
1102
raise errors.BzrCommandError('No matching files.')
1103
tree.remove(file_list, verbose=verbose, to_file=self.outf)
1106
class cmd_file_id(Command):
1107
"""Print file_id of a particular file or directory.
1109
The file_id is assigned when the file is first added and remains the
1110
same through all revisions where the file exists, even when it is
1115
_see_also = ['inventory', 'ls']
1116
takes_args = ['filename']
1119
def run(self, filename):
1120
tree, relpath = WorkingTree.open_containing(filename)
1121
i = tree.path2id(relpath)
1123
raise errors.NotVersionedError(filename)
1125
self.outf.write(i + '\n')
1128
class cmd_file_path(Command):
1129
"""Print path of file_ids to a file or directory.
1131
This prints one line for each directory down to the target,
1132
starting at the branch root.
1136
takes_args = ['filename']
1139
def run(self, filename):
1140
tree, relpath = WorkingTree.open_containing(filename)
1141
fid = tree.path2id(relpath)
1143
raise errors.NotVersionedError(filename)
1144
segments = osutils.splitpath(relpath)
1145
for pos in range(1, len(segments) + 1):
1146
path = osutils.joinpath(segments[:pos])
1147
self.outf.write("%s\n" % tree.path2id(path))
1150
class cmd_reconcile(Command):
1151
"""Reconcile bzr metadata in a branch.
1153
This can correct data mismatches that may have been caused by
1154
previous ghost operations or bzr upgrades. You should only
1155
need to run this command if 'bzr check' or a bzr developer
1156
advises you to run it.
1158
If a second branch is provided, cross-branch reconciliation is
1159
also attempted, which will check that data like the tree root
1160
id which was not present in very early bzr versions is represented
1161
correctly in both branches.
1163
At the same time it is run it may recompress data resulting in
1164
a potential saving in disk space or performance gain.
1166
The branch *MUST* be on a listable system such as local disk or sftp.
1169
_see_also = ['check']
1170
takes_args = ['branch?']
1172
def run(self, branch="."):
1173
from bzrlib.reconcile import reconcile
1174
dir = bzrdir.BzrDir.open(branch)
1178
class cmd_revision_history(Command):
1179
"""Display the list of revision ids on a branch."""
1182
takes_args = ['location?']
1187
def run(self, location="."):
1188
branch = Branch.open_containing(location)[0]
1189
for revid in branch.revision_history():
1190
self.outf.write(revid)
1191
self.outf.write('\n')
1194
class cmd_ancestry(Command):
1195
"""List all revisions merged into this branch."""
1197
_see_also = ['log', 'revision-history']
1198
takes_args = ['location?']
1203
def run(self, location="."):
1205
wt = WorkingTree.open_containing(location)[0]
1206
except errors.NoWorkingTree:
1207
b = Branch.open(location)
1208
last_revision = b.last_revision()
1211
last_revision = wt.last_revision()
1213
revision_ids = b.repository.get_ancestry(last_revision)
1214
assert revision_ids[0] is None
1216
for revision_id in revision_ids:
1217
self.outf.write(revision_id + '\n')
1220
class cmd_init(Command):
1221
"""Make a directory into a versioned branch.
1223
Use this to create an empty branch, or before importing an
1226
If there is a repository in a parent directory of the location, then
1227
the history of the branch will be stored in the repository. Otherwise
1228
init creates a standalone branch which carries its own history
1229
in the .bzr directory.
1231
If there is already a branch at the location but it has no working tree,
1232
the tree can be populated with 'bzr checkout'.
1234
Recipe for importing a tree of files:
1239
bzr commit -m 'imported project'
1242
_see_also = ['init-repo', 'branch', 'checkout']
1243
takes_args = ['location?']
1245
RegistryOption('format',
1246
help='Specify a format for this branch. '
1247
'See "help formats".',
1248
registry=bzrdir.format_registry,
1249
converter=bzrdir.format_registry.make_bzrdir,
1250
value_switches=True,
1251
title="Branch Format",
1253
Option('append-revisions-only',
1254
help='Never change revnos or the existing log.'
1255
' Append revisions to it only.')
1257
def run(self, location=None, format=None, append_revisions_only=False):
1259
format = bzrdir.format_registry.make_bzrdir('default')
1260
if location is None:
1263
to_transport = transport.get_transport(location)
1265
# The path has to exist to initialize a
1266
# branch inside of it.
1267
# Just using os.mkdir, since I don't
1268
# believe that we want to create a bunch of
1269
# locations if the user supplies an extended path
1270
# TODO: create-prefix
1272
to_transport.mkdir('.')
1273
except errors.FileExists:
1277
existing_bzrdir = bzrdir.BzrDir.open(location)
1278
except errors.NotBranchError:
1279
# really a NotBzrDir error...
1280
branch = bzrdir.BzrDir.create_branch_convenience(to_transport.base,
1283
from bzrlib.transport.local import LocalTransport
1284
if existing_bzrdir.has_branch():
1285
if (isinstance(to_transport, LocalTransport)
1286
and not existing_bzrdir.has_workingtree()):
1287
raise errors.BranchExistsWithoutWorkingTree(location)
1288
raise errors.AlreadyBranchError(location)
1290
branch = existing_bzrdir.create_branch()
1291
existing_bzrdir.create_workingtree()
1292
if append_revisions_only:
1294
branch.set_append_revisions_only(True)
1295
except errors.UpgradeRequired:
1296
raise errors.BzrCommandError('This branch format cannot be set'
1297
' to append-revisions-only. Try --experimental-branch6')
1300
class cmd_init_repository(Command):
1301
"""Create a shared repository to hold branches.
1303
New branches created under the repository directory will store their revisions
1304
in the repository, not in the branch directory.
1307
bzr init-repo --no-trees repo
1309
bzr checkout --lightweight repo/trunk trunk-checkout
1314
_see_also = ['init', 'branch', 'checkout']
1315
takes_args = ["location"]
1316
takes_options = [RegistryOption('format',
1317
help='Specify a format for this repository. See'
1318
' "bzr help formats" for details',
1319
registry=bzrdir.format_registry,
1320
converter=bzrdir.format_registry.make_bzrdir,
1321
value_switches=True, title='Repository format'),
1323
help='Branches in the repository will default to'
1324
' not having a working tree'),
1326
aliases = ["init-repo"]
1328
def run(self, location, format=None, no_trees=False):
1330
format = bzrdir.format_registry.make_bzrdir('default')
1332
if location is None:
1335
to_transport = transport.get_transport(location)
1337
to_transport.mkdir('.')
1338
except errors.FileExists:
1341
newdir = format.initialize_on_transport(to_transport)
1342
repo = newdir.create_repository(shared=True)
1343
repo.set_make_working_trees(not no_trees)
1346
class cmd_diff(Command):
1347
"""Show differences in the working tree or between revisions.
1349
If files are listed, only the changes in those files are listed.
1350
Otherwise, all changes for the tree are listed.
1352
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1353
produces patches suitable for "patch -p1".
1357
Shows the difference in the working tree versus the last commit
1359
Difference between the working tree and revision 1
1361
Difference between revision 2 and revision 1
1362
bzr diff --prefix old/:new/
1363
Same as 'bzr diff' but prefix paths with old/ and new/
1364
bzr diff bzr.mine bzr.dev
1365
Show the differences between the two working trees
1367
Show just the differences for 'foo.c'
1369
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1370
# or a graphical diff.
1372
# TODO: Python difflib is not exactly the same as unidiff; should
1373
# either fix it up or prefer to use an external diff.
1375
# TODO: Selected-file diff is inefficient and doesn't show you
1378
# TODO: This probably handles non-Unix newlines poorly.
1380
_see_also = ['status']
1381
takes_args = ['file*']
1382
takes_options = ['revision', 'diff-options',
1383
Option('prefix', type=str,
1385
help='Set prefixes to added to old and new filenames, as '
1386
'two values separated by a colon. (eg "old/:new/")'),
1388
aliases = ['di', 'dif']
1389
encoding_type = 'exact'
1392
def run(self, revision=None, file_list=None, diff_options=None,
1394
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1396
if (prefix is None) or (prefix == '0'):
1404
old_label, new_label = prefix.split(":")
1406
raise errors.BzrCommandError(
1407
'--prefix expects two values separated by a colon'
1408
' (eg "old/:new/")')
1410
if revision and len(revision) > 2:
1411
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1412
' one or two revision specifiers')
1415
tree1, file_list = internal_tree_files(file_list)
1419
except errors.FileInWrongBranch:
1420
if len(file_list) != 2:
1421
raise errors.BzrCommandError("Files are in different branches")
1423
tree1, file1 = WorkingTree.open_containing(file_list[0])
1424
tree2, file2 = WorkingTree.open_containing(file_list[1])
1425
if file1 != "" or file2 != "":
1426
# FIXME diff those two files. rbc 20051123
1427
raise errors.BzrCommandError("Files are in different branches")
1429
except errors.NotBranchError:
1430
if (revision is not None and len(revision) == 2
1431
and not revision[0].needs_branch()
1432
and not revision[1].needs_branch()):
1433
# If both revision specs include a branch, we can
1434
# diff them without needing a local working tree
1435
tree1, tree2 = None, None
1439
if tree2 is not None:
1440
if revision is not None:
1441
# FIXME: but there should be a clean way to diff between
1442
# non-default versions of two trees, it's not hard to do
1444
raise errors.BzrCommandError(
1445
"Sorry, diffing arbitrary revisions across branches "
1446
"is not implemented yet")
1447
return show_diff_trees(tree1, tree2, sys.stdout,
1448
specific_files=file_list,
1449
external_diff_options=diff_options,
1450
old_label=old_label, new_label=new_label)
1452
return diff_cmd_helper(tree1, file_list, diff_options,
1453
revision_specs=revision,
1454
old_label=old_label, new_label=new_label)
1457
class cmd_deleted(Command):
1458
"""List files deleted in the working tree.
1460
# TODO: Show files deleted since a previous revision, or
1461
# between two revisions.
1462
# TODO: Much more efficient way to do this: read in new
1463
# directories with readdir, rather than stating each one. Same
1464
# level of effort but possibly much less IO. (Or possibly not,
1465
# if the directories are very large...)
1466
_see_also = ['status', 'ls']
1467
takes_options = ['show-ids']
1470
def run(self, show_ids=False):
1471
tree = WorkingTree.open_containing(u'.')[0]
1474
old = tree.basis_tree()
1477
for path, ie in old.inventory.iter_entries():
1478
if not tree.has_id(ie.file_id):
1479
self.outf.write(path)
1481
self.outf.write(' ')
1482
self.outf.write(ie.file_id)
1483
self.outf.write('\n')
1490
class cmd_modified(Command):
1491
"""List files modified in working tree.
1495
_see_also = ['status', 'ls']
1499
tree = WorkingTree.open_containing(u'.')[0]
1500
td = tree.changes_from(tree.basis_tree())
1501
for path, id, kind, text_modified, meta_modified in td.modified:
1502
self.outf.write(path + '\n')
1505
class cmd_added(Command):
1506
"""List files added in working tree.
1510
_see_also = ['status', 'ls']
1514
wt = WorkingTree.open_containing(u'.')[0]
1517
basis = wt.basis_tree()
1520
basis_inv = basis.inventory
1523
if file_id in basis_inv:
1525
if inv.is_root(file_id) and len(basis_inv) == 0:
1527
path = inv.id2path(file_id)
1528
if not os.access(osutils.abspath(path), os.F_OK):
1530
self.outf.write(path + '\n')
1537
class cmd_root(Command):
1538
"""Show the tree root directory.
1540
The root is the nearest enclosing directory with a .bzr control
1543
takes_args = ['filename?']
1545
def run(self, filename=None):
1546
"""Print the branch root."""
1547
tree = WorkingTree.open_containing(filename)[0]
1548
self.outf.write(tree.basedir + '\n')
1551
class cmd_log(Command):
1552
"""Show log of a branch, file, or directory.
1554
By default show the log of the branch containing the working directory.
1556
To request a range of logs, you can use the command -r begin..end
1557
-r revision requests a specific revision, -r ..end or -r begin.. are
1563
bzr log -r -10.. http://server/branch
1566
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1568
takes_args = ['location?']
1569
takes_options = [Option('forward',
1570
help='show from oldest to newest'),
1574
help='show files changed in each revision'),
1575
'show-ids', 'revision',
1579
help='show revisions whose message matches this regexp',
1582
encoding_type = 'replace'
1585
def run(self, location=None, timezone='original',
1592
from bzrlib.log import show_log
1593
assert message is None or isinstance(message, basestring), \
1594
"invalid message argument %r" % message
1595
direction = (forward and 'forward') or 'reverse'
1600
# find the file id to log:
1602
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1606
tree = b.basis_tree()
1607
file_id = tree.path2id(fp)
1609
raise errors.BzrCommandError(
1610
"Path does not have any revision history: %s" %
1614
# FIXME ? log the current subdir only RBC 20060203
1615
if revision is not None \
1616
and len(revision) > 0 and revision[0].get_branch():
1617
location = revision[0].get_branch()
1620
dir, relpath = bzrdir.BzrDir.open_containing(location)
1621
b = dir.open_branch()
1625
if revision is None:
1628
elif len(revision) == 1:
1629
rev1 = rev2 = revision[0].in_history(b).revno
1630
elif len(revision) == 2:
1631
if revision[1].get_branch() != revision[0].get_branch():
1632
# b is taken from revision[0].get_branch(), and
1633
# show_log will use its revision_history. Having
1634
# different branches will lead to weird behaviors.
1635
raise errors.BzrCommandError(
1636
"Log doesn't accept two revisions in different"
1638
if revision[0].spec is None:
1639
# missing begin-range means first revision
1642
rev1 = revision[0].in_history(b).revno
1644
if revision[1].spec is None:
1645
# missing end-range means last known revision
1648
rev2 = revision[1].in_history(b).revno
1650
raise errors.BzrCommandError(
1651
'bzr log --revision takes one or two values.')
1653
# By this point, the revision numbers are converted to the +ve
1654
# form if they were supplied in the -ve form, so we can do
1655
# this comparison in relative safety
1657
(rev2, rev1) = (rev1, rev2)
1659
if log_format is None:
1660
log_format = log.log_formatter_registry.get_default(b)
1662
lf = log_format(show_ids=show_ids, to_file=self.outf,
1663
show_timezone=timezone)
1669
direction=direction,
1670
start_revision=rev1,
1677
def get_log_format(long=False, short=False, line=False, default='long'):
1678
log_format = default
1682
log_format = 'short'
1688
class cmd_touching_revisions(Command):
1689
"""Return revision-ids which affected a particular file.
1691
A more user-friendly interface is "bzr log FILE".
1695
takes_args = ["filename"]
1698
def run(self, filename):
1699
tree, relpath = WorkingTree.open_containing(filename)
1701
file_id = tree.path2id(relpath)
1702
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1703
self.outf.write("%6d %s\n" % (revno, what))
1706
class cmd_ls(Command):
1707
"""List files in a tree.
1710
_see_also = ['status', 'cat']
1711
takes_args = ['path?']
1712
# TODO: Take a revision or remote path and list that tree instead.
1713
takes_options = ['verbose', 'revision',
1714
Option('non-recursive',
1715
help='don\'t recurse into sub-directories'),
1717
help='Print all paths from the root of the branch.'),
1718
Option('unknown', help='Print unknown files'),
1719
Option('versioned', help='Print versioned files'),
1720
Option('ignored', help='Print ignored files'),
1722
Option('null', help='Null separate the files'),
1726
def run(self, revision=None, verbose=False,
1727
non_recursive=False, from_root=False,
1728
unknown=False, versioned=False, ignored=False,
1729
null=False, kind=None, show_ids=False, path=None):
1731
if kind and kind not in ('file', 'directory', 'symlink'):
1732
raise errors.BzrCommandError('invalid kind specified')
1734
if verbose and null:
1735
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1736
all = not (unknown or versioned or ignored)
1738
selection = {'I':ignored, '?':unknown, 'V':versioned}
1745
raise errors.BzrCommandError('cannot specify both --from-root'
1749
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1755
if revision is not None:
1756
tree = branch.repository.revision_tree(
1757
revision[0].in_history(branch).rev_id)
1759
tree = branch.basis_tree()
1763
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1764
if fp.startswith(relpath):
1765
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1766
if non_recursive and '/' in fp:
1768
if not all and not selection[fc]:
1770
if kind is not None and fkind != kind:
1773
kindch = entry.kind_character()
1774
outstring = '%-8s %s%s' % (fc, fp, kindch)
1775
if show_ids and fid is not None:
1776
outstring = "%-50s %s" % (outstring, fid)
1777
self.outf.write(outstring + '\n')
1779
self.outf.write(fp + '\0')
1782
self.outf.write(fid)
1783
self.outf.write('\0')
1791
self.outf.write('%-50s %s\n' % (fp, my_id))
1793
self.outf.write(fp + '\n')
1798
class cmd_unknowns(Command):
1799
"""List unknown files.
1807
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1808
self.outf.write(osutils.quotefn(f) + '\n')
1811
class cmd_ignore(Command):
1812
"""Ignore specified files or patterns.
1814
To remove patterns from the ignore list, edit the .bzrignore file.
1816
Trailing slashes on patterns are ignored.
1817
If the pattern contains a slash or is a regular expression, it is compared
1818
to the whole path from the branch root. Otherwise, it is compared to only
1819
the last component of the path. To match a file only in the root
1820
directory, prepend './'.
1822
Ignore patterns specifying absolute paths are not allowed.
1824
Ignore patterns may include globbing wildcards such as:
1825
? - Matches any single character except '/'
1826
* - Matches 0 or more characters except '/'
1827
/**/ - Matches 0 or more directories in a path
1828
[a-z] - Matches a single character from within a group of characters
1830
Ignore patterns may also be Python regular expressions.
1831
Regular expression ignore patterns are identified by a 'RE:' prefix
1832
followed by the regular expression. Regular expression ignore patterns
1833
may not include named or numbered groups.
1835
Note: ignore patterns containing shell wildcards must be quoted from
1839
bzr ignore ./Makefile
1840
bzr ignore '*.class'
1841
bzr ignore 'lib/**/*.o'
1842
bzr ignore 'RE:lib/.*\.o'
1845
_see_also = ['status', 'ignored']
1846
takes_args = ['name_pattern*']
1848
Option('old-default-rules',
1849
help='Out the ignore rules bzr < 0.9 always used.')
1852
def run(self, name_pattern_list=None, old_default_rules=None):
1853
from bzrlib.atomicfile import AtomicFile
1854
if old_default_rules is not None:
1855
# dump the rules and exit
1856
for pattern in ignores.OLD_DEFAULTS:
1859
if not name_pattern_list:
1860
raise errors.BzrCommandError("ignore requires at least one "
1861
"NAME_PATTERN or --old-default-rules")
1862
name_pattern_list = [globbing.normalize_pattern(p)
1863
for p in name_pattern_list]
1864
for name_pattern in name_pattern_list:
1865
if (name_pattern[0] == '/' or
1866
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1867
raise errors.BzrCommandError(
1868
"NAME_PATTERN should not be an absolute path")
1869
tree, relpath = WorkingTree.open_containing(u'.')
1870
ifn = tree.abspath('.bzrignore')
1871
if os.path.exists(ifn):
1874
igns = f.read().decode('utf-8')
1880
# TODO: If the file already uses crlf-style termination, maybe
1881
# we should use that for the newly added lines?
1883
if igns and igns[-1] != '\n':
1885
for name_pattern in name_pattern_list:
1886
igns += name_pattern + '\n'
1888
f = AtomicFile(ifn, 'wb')
1890
f.write(igns.encode('utf-8'))
1895
if not tree.path2id('.bzrignore'):
1896
tree.add(['.bzrignore'])
1899
class cmd_ignored(Command):
1900
"""List ignored files and the patterns that matched them.
1903
_see_also = ['ignore']
1906
tree = WorkingTree.open_containing(u'.')[0]
1909
for path, file_class, kind, file_id, entry in tree.list_files():
1910
if file_class != 'I':
1912
## XXX: Slightly inefficient since this was already calculated
1913
pat = tree.is_ignored(path)
1914
print '%-50s %s' % (path, pat)
1919
class cmd_lookup_revision(Command):
1920
"""Lookup the revision-id from a revision-number
1923
bzr lookup-revision 33
1926
takes_args = ['revno']
1929
def run(self, revno):
1933
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
1935
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1938
class cmd_export(Command):
1939
"""Export current or past revision to a destination directory or archive.
1941
If no revision is specified this exports the last committed revision.
1943
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1944
given, try to find the format with the extension. If no extension
1945
is found exports to a directory (equivalent to --format=dir).
1947
If root is supplied, it will be used as the root directory inside
1948
container formats (tar, zip, etc). If it is not supplied it will default
1949
to the exported filename. The root option has no effect for 'dir' format.
1951
If branch is omitted then the branch containing the current working
1952
directory will be used.
1954
Note: Export of tree with non-ASCII filenames to zip is not supported.
1956
Supported formats Autodetected by extension
1957
----------------- -------------------------
1960
tbz2 .tar.bz2, .tbz2
1964
takes_args = ['dest', 'branch?']
1965
takes_options = ['revision', 'format', 'root']
1966
def run(self, dest, branch=None, revision=None, format=None, root=None):
1967
from bzrlib.export import export
1970
tree = WorkingTree.open_containing(u'.')[0]
1973
b = Branch.open(branch)
1975
if revision is None:
1976
# should be tree.last_revision FIXME
1977
rev_id = b.last_revision()
1979
if len(revision) != 1:
1980
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
1981
rev_id = revision[0].in_history(b).rev_id
1982
t = b.repository.revision_tree(rev_id)
1984
export(t, dest, format, root)
1985
except errors.NoSuchExportFormat, e:
1986
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1989
class cmd_cat(Command):
1990
"""Write the contents of a file as of a given revision to standard output.
1992
If no revision is nominated, the last revision is used.
1994
Note: Take care to redirect standard output when using this command on a
1999
takes_options = ['revision', 'name-from-revision']
2000
takes_args = ['filename']
2001
encoding_type = 'exact'
2004
def run(self, filename, revision=None, name_from_revision=False):
2005
if revision is not None and len(revision) != 1:
2006
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2011
tree, b, relpath = \
2012
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2013
except errors.NotBranchError:
2016
if revision is not None and revision[0].get_branch() is not None:
2017
b = Branch.open(revision[0].get_branch())
2019
tree = b.basis_tree()
2020
if revision is None:
2021
revision_id = b.last_revision()
2023
revision_id = revision[0].in_history(b).rev_id
2025
cur_file_id = tree.path2id(relpath)
2026
rev_tree = b.repository.revision_tree(revision_id)
2027
old_file_id = rev_tree.path2id(relpath)
2029
if name_from_revision:
2030
if old_file_id is None:
2031
raise errors.BzrCommandError("%r is not present in revision %s"
2032
% (filename, revision_id))
2034
rev_tree.print_file(old_file_id)
2035
elif cur_file_id is not None:
2036
rev_tree.print_file(cur_file_id)
2037
elif old_file_id is not None:
2038
rev_tree.print_file(old_file_id)
2040
raise errors.BzrCommandError("%r is not present in revision %s" %
2041
(filename, revision_id))
2044
class cmd_local_time_offset(Command):
2045
"""Show the offset in seconds from GMT to local time."""
2049
print osutils.local_time_offset()
2053
class cmd_commit(Command):
2054
"""Commit changes into a new revision.
2056
If no arguments are given, the entire tree is committed.
2058
If selected files are specified, only changes to those files are
2059
committed. If a directory is specified then the directory and everything
2060
within it is committed.
2062
A selected-file commit may fail in some cases where the committed
2063
tree would be invalid. Consider::
2068
bzr commit foo -m "committing foo"
2069
bzr mv foo/bar foo/baz
2072
bzr commit foo/bar -m "committing bar but not baz"
2074
In the example above, the last commit will fail by design. This gives
2075
the user the opportunity to decide whether they want to commit the
2076
rename at the same time, separately first, or not at all. (As a general
2077
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2079
Note: A selected-file commit after a merge is not yet supported.
2081
# TODO: Run hooks on tree to-be-committed, and after commit.
2083
# TODO: Strict commit that fails if there are deleted files.
2084
# (what does "deleted files" mean ??)
2086
# TODO: Give better message for -s, --summary, used by tla people
2088
# XXX: verbose currently does nothing
2090
_see_also = ['uncommit']
2091
takes_args = ['selected*']
2092
takes_options = ['message', 'verbose',
2094
help='commit even if nothing has changed'),
2095
Option('file', type=str,
2098
help='file containing commit message'),
2100
help="refuse to commit if there are unknown "
2101
"files in the working tree."),
2103
help="perform a local only commit in a bound "
2104
"branch. Such commits are not pushed to "
2105
"the master branch until a normal commit "
2109
aliases = ['ci', 'checkin']
2111
def run(self, message=None, file=None, verbose=True, selected_list=None,
2112
unchanged=False, strict=False, local=False):
2113
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2114
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2116
from bzrlib.msgeditor import edit_commit_message, \
2117
make_commit_message_template
2119
# TODO: Need a blackbox test for invoking the external editor; may be
2120
# slightly problematic to run this cross-platform.
2122
# TODO: do more checks that the commit will succeed before
2123
# spending the user's valuable time typing a commit message.
2124
tree, selected_list = tree_files(selected_list)
2125
if selected_list == ['']:
2126
# workaround - commit of root of tree should be exactly the same
2127
# as just default commit in that tree, and succeed even though
2128
# selected-file merge commit is not done yet
2131
if local and not tree.branch.get_bound_location():
2132
raise errors.LocalRequiresBoundBranch()
2134
def get_message(commit_obj):
2135
"""Callback to get commit message"""
2136
my_message = message
2137
if my_message is None and not file:
2138
template = make_commit_message_template(tree, selected_list)
2139
my_message = edit_commit_message(template)
2140
if my_message is None:
2141
raise errors.BzrCommandError("please specify a commit"
2142
" message with either --message or --file")
2143
elif my_message and file:
2144
raise errors.BzrCommandError(
2145
"please specify either --message or --file")
2147
my_message = codecs.open(file, 'rt',
2148
bzrlib.user_encoding).read()
2149
if my_message == "":
2150
raise errors.BzrCommandError("empty commit message specified")
2154
reporter = ReportCommitToLog()
2156
reporter = NullCommitReporter()
2159
tree.commit(message_callback=get_message,
2160
specific_files=selected_list,
2161
allow_pointless=unchanged, strict=strict, local=local,
2163
except PointlessCommit:
2164
# FIXME: This should really happen before the file is read in;
2165
# perhaps prepare the commit; get the message; then actually commit
2166
raise errors.BzrCommandError("no changes to commit."
2167
" use --unchanged to commit anyhow")
2168
except ConflictsInTree:
2169
raise errors.BzrCommandError('Conflicts detected in working '
2170
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2172
except StrictCommitFailed:
2173
raise errors.BzrCommandError("Commit refused because there are"
2174
" unknown files in the working tree.")
2175
except errors.BoundBranchOutOfDate, e:
2176
raise errors.BzrCommandError(str(e) + "\n"
2177
'To commit to master branch, run update and then commit.\n'
2178
'You can also pass --local to commit to continue working '
2182
class cmd_check(Command):
2183
"""Validate consistency of branch history.
2185
This command checks various invariants about the branch storage to
2186
detect data corruption or bzr bugs.
2189
_see_also = ['reconcile']
2190
takes_args = ['branch?']
2191
takes_options = ['verbose']
2193
def run(self, branch=None, verbose=False):
2194
from bzrlib.check import check
2196
tree = WorkingTree.open_containing()[0]
2197
branch = tree.branch
2199
branch = Branch.open(branch)
2200
check(branch, verbose)
2203
class cmd_upgrade(Command):
2204
"""Upgrade branch storage to current format.
2206
The check command or bzr developers may sometimes advise you to run
2207
this command. When the default format has changed you may also be warned
2208
during other operations to upgrade.
2211
_see_also = ['check']
2212
takes_args = ['url?']
2214
RegistryOption('format',
2215
help='Upgrade to a specific format. See "bzr help'
2216
' formats" for details',
2217
registry=bzrdir.format_registry,
2218
converter=bzrdir.format_registry.make_bzrdir,
2219
value_switches=True, title='Branch format'),
2222
def run(self, url='.', format=None):
2223
from bzrlib.upgrade import upgrade
2225
format = bzrdir.format_registry.make_bzrdir('default')
2226
upgrade(url, format)
2229
class cmd_whoami(Command):
2230
"""Show or set bzr user id.
2234
bzr whoami 'Frank Chu <fchu@example.com>'
2236
takes_options = [ Option('email',
2237
help='display email address only'),
2239
help='set identity for the current branch instead of '
2242
takes_args = ['name?']
2243
encoding_type = 'replace'
2246
def run(self, email=False, branch=False, name=None):
2248
# use branch if we're inside one; otherwise global config
2250
c = Branch.open_containing('.')[0].get_config()
2251
except errors.NotBranchError:
2252
c = config.GlobalConfig()
2254
self.outf.write(c.user_email() + '\n')
2256
self.outf.write(c.username() + '\n')
2259
# display a warning if an email address isn't included in the given name.
2261
config.extract_email_address(name)
2262
except errors.NoEmailInUsername, e:
2263
warning('"%s" does not seem to contain an email address. '
2264
'This is allowed, but not recommended.', name)
2266
# use global config unless --branch given
2268
c = Branch.open_containing('.')[0].get_config()
2270
c = config.GlobalConfig()
2271
c.set_user_option('email', name)
2274
class cmd_nick(Command):
2275
"""Print or set the branch nickname.
2277
If unset, the tree root directory name is used as the nickname
2278
To print the current nickname, execute with no argument.
2281
_see_also = ['info']
2282
takes_args = ['nickname?']
2283
def run(self, nickname=None):
2284
branch = Branch.open_containing(u'.')[0]
2285
if nickname is None:
2286
self.printme(branch)
2288
branch.nick = nickname
2291
def printme(self, branch):
2295
class cmd_selftest(Command):
2296
"""Run internal test suite.
2298
This creates temporary test directories in the working directory, but not
2299
existing data is affected. These directories are deleted if the tests
2300
pass, or left behind to help in debugging if they fail and --keep-output
2303
If arguments are given, they are regular expressions that say which tests
2304
should run. Tests matching any expression are run, and other tests are
2307
Alternatively if --first is given, matching tests are run first and then
2308
all other tests are run. This is useful if you have been working in a
2309
particular area, but want to make sure nothing else was broken.
2311
If the global option '--no-plugins' is given, plugins are not loaded
2312
before running the selftests. This has two effects: features provided or
2313
modified by plugins will not be tested, and tests provided by plugins will
2318
run only tests relating to 'ignore'
2319
bzr --no-plugins selftest -v
2320
disable plugins and list tests as they're run
2322
For each test, that needs actual disk access, bzr create their own
2323
subdirectory in the temporary testing directory (testXXXX.tmp).
2324
By default the name of such subdirectory is based on the name of the test.
2325
If option '--numbered-dirs' is given, bzr will use sequent numbers
2326
of running tests to create such subdirectories. This is default behavior
2327
on Windows because of path length limitation.
2329
# TODO: --list should give a list of all available tests
2331
# NB: this is used from the class without creating an instance, which is
2332
# why it does not have a self parameter.
2333
def get_transport_type(typestring):
2334
"""Parse and return a transport specifier."""
2335
if typestring == "sftp":
2336
from bzrlib.transport.sftp import SFTPAbsoluteServer
2337
return SFTPAbsoluteServer
2338
if typestring == "memory":
2339
from bzrlib.transport.memory import MemoryServer
2341
if typestring == "fakenfs":
2342
from bzrlib.transport.fakenfs import FakeNFSServer
2343
return FakeNFSServer
2344
msg = "No known transport type %s. Supported types are: sftp\n" %\
2346
raise errors.BzrCommandError(msg)
2349
takes_args = ['testspecs*']
2350
takes_options = ['verbose',
2352
help='stop when one test fails',
2355
Option('keep-output',
2356
help='keep output directories when tests fail'),
2358
help='Use a different transport by default '
2359
'throughout the test suite.',
2360
type=get_transport_type),
2361
Option('benchmark', help='run the bzr benchmarks.'),
2362
Option('lsprof-timed',
2363
help='generate lsprof output for benchmarked'
2364
' sections of code.'),
2365
Option('cache-dir', type=str,
2366
help='a directory to cache intermediate'
2367
' benchmark steps'),
2368
Option('clean-output',
2369
help='clean temporary tests directories'
2370
' without running tests'),
2372
help='run all tests, but run specified tests first',
2375
Option('numbered-dirs',
2376
help='use numbered dirs for TestCaseInTempDir'),
2378
encoding_type = 'replace'
2380
def run(self, testspecs_list=None, verbose=None, one=False,
2381
keep_output=False, transport=None, benchmark=None,
2382
lsprof_timed=None, cache_dir=None, clean_output=False,
2383
first=False, numbered_dirs=None):
2385
from bzrlib.tests import selftest
2386
import bzrlib.benchmarks as benchmarks
2387
from bzrlib.benchmarks import tree_creator
2390
from bzrlib.tests import clean_selftest_output
2391
clean_selftest_output()
2394
if numbered_dirs is None and sys.platform == 'win32':
2395
numbered_dirs = True
2397
if cache_dir is not None:
2398
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2399
print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
2400
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
2402
if testspecs_list is not None:
2403
pattern = '|'.join(testspecs_list)
2407
test_suite_factory = benchmarks.test_suite
2410
# TODO: should possibly lock the history file...
2411
benchfile = open(".perf_history", "at", buffering=1)
2413
test_suite_factory = None
2418
result = selftest(verbose=verbose,
2420
stop_on_failure=one,
2421
keep_output=keep_output,
2422
transport=transport,
2423
test_suite_factory=test_suite_factory,
2424
lsprof_timed=lsprof_timed,
2425
bench_history=benchfile,
2426
matching_tests_first=first,
2427
numbered_dirs=numbered_dirs,
2430
if benchfile is not None:
2433
info('tests passed')
2435
info('tests failed')
2436
return int(not result)
2439
class cmd_version(Command):
2440
"""Show version of bzr."""
2444
from bzrlib.version import show_version
2448
class cmd_rocks(Command):
2449
"""Statement of optimism."""
2455
print "It sure does!"
2458
class cmd_find_merge_base(Command):
2459
"""Find and print a base revision for merging two branches."""
2460
# TODO: Options to specify revisions on either side, as if
2461
# merging only part of the history.
2462
takes_args = ['branch', 'other']
2466
def run(self, branch, other):
2467
from bzrlib.revision import MultipleRevisionSources
2469
branch1 = Branch.open_containing(branch)[0]
2470
branch2 = Branch.open_containing(other)[0]
2472
last1 = branch1.last_revision()
2473
last2 = branch2.last_revision()
2475
source = MultipleRevisionSources(branch1.repository,
2478
base_rev_id = common_ancestor(last1, last2, source)
2480
print 'merge base is revision %s' % base_rev_id
2483
class cmd_merge(Command):
2484
"""Perform a three-way merge.
2486
The branch is the branch you will merge from. By default, it will merge
2487
the latest revision. If you specify a revision, that revision will be
2488
merged. If you specify two revisions, the first will be used as a BASE,
2489
and the second one as OTHER. Revision numbers are always relative to the
2492
By default, bzr will try to merge in all new work from the other
2493
branch, automatically determining an appropriate base. If this
2494
fails, you may need to give an explicit base.
2496
Merge will do its best to combine the changes in two branches, but there
2497
are some kinds of problems only a human can fix. When it encounters those,
2498
it will mark a conflict. A conflict means that you need to fix something,
2499
before you should commit.
2501
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2503
If there is no default branch set, the first merge will set it. After
2504
that, you can omit the branch to use the default. To change the
2505
default, use --remember. The value will only be saved if the remote
2506
location can be accessed.
2508
The results of the merge are placed into the destination working
2509
directory, where they can be reviewed (with bzr diff), tested, and then
2510
committed to record the result of the merge.
2514
To merge the latest revision from bzr.dev:
2515
bzr merge ../bzr.dev
2517
To merge changes up to and including revision 82 from bzr.dev:
2518
bzr merge -r 82 ../bzr.dev
2520
To merge the changes introduced by 82, without previous changes:
2521
bzr merge -r 81..82 ../bzr.dev
2523
merge refuses to run if there are any uncommitted changes, unless
2527
_see_also = ['update', 'remerge']
2528
takes_args = ['branch?']
2529
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
2530
Option('show-base', help="Show base revision text in "
2532
Option('uncommitted', help='Apply uncommitted changes'
2533
' from a working copy, instead of branch changes'),
2534
Option('pull', help='If the destination is already'
2535
' completely merged into the source, pull from the'
2536
' source rather than merging. When this happens,'
2537
' you do not need to commit the result.'),
2539
help='Branch to merge into, '
2540
'rather than the one containing the working directory',
2546
def run(self, branch=None, revision=None, force=False, merge_type=None,
2547
show_base=False, reprocess=False, remember=False,
2548
uncommitted=False, pull=False,
2551
from bzrlib.tag import _merge_tags_if_possible
2552
other_revision_id = None
2553
if merge_type is None:
2554
merge_type = _mod_merge.Merge3Merger
2556
if directory is None: directory = u'.'
2557
# XXX: jam 20070225 WorkingTree should be locked before you extract its
2558
# inventory. Because merge is a mutating operation, it really
2559
# should be a lock_write() for the whole cmd_merge operation.
2560
# However, cmd_merge open's its own tree in _merge_helper, which
2561
# means if we lock here, the later lock_write() will always block.
2562
# Either the merge helper code should be updated to take a tree,
2563
# (What about tree.merge_from_branch?)
2564
tree = WorkingTree.open_containing(directory)[0]
2565
change_reporter = delta._ChangeReporter(
2566
unversioned_filter=tree.is_ignored)
2568
if branch is not None:
2570
mergeable = bundle.read_mergeable_from_url(
2572
except errors.NotABundle:
2573
pass # Continue on considering this url a Branch
2575
if revision is not None:
2576
raise errors.BzrCommandError(
2577
'Cannot use -r with merge directives or bundles')
2578
other_revision_id = mergeable.install_revisions(
2579
tree.branch.repository)
2580
revision = [RevisionSpec.from_string(
2581
'revid:' + other_revision_id)]
2583
if revision is None \
2584
or len(revision) < 1 or revision[0].needs_branch():
2585
branch = self._get_remembered_parent(tree, branch, 'Merging from')
2587
if revision is None or len(revision) < 1:
2590
other = [branch, None]
2593
other = [branch, -1]
2594
other_branch, path = Branch.open_containing(branch)
2597
raise errors.BzrCommandError('Cannot use --uncommitted and'
2598
' --revision at the same time.')
2599
branch = revision[0].get_branch() or branch
2600
if len(revision) == 1:
2602
if other_revision_id is not None:
2607
other_branch, path = Branch.open_containing(branch)
2608
revno = revision[0].in_history(other_branch).revno
2609
other = [branch, revno]
2611
assert len(revision) == 2
2612
if None in revision:
2613
raise errors.BzrCommandError(
2614
"Merge doesn't permit empty revision specifier.")
2615
base_branch, path = Branch.open_containing(branch)
2616
branch1 = revision[1].get_branch() or branch
2617
other_branch, path1 = Branch.open_containing(branch1)
2618
if revision[0].get_branch() is not None:
2619
# then path was obtained from it, and is None.
2622
base = [branch, revision[0].in_history(base_branch).revno]
2623
other = [branch1, revision[1].in_history(other_branch).revno]
2625
if ((tree.branch.get_parent() is None or remember) and
2626
other_branch is not None):
2627
tree.branch.set_parent(other_branch.base)
2629
# pull tags now... it's a bit inconsistent to do it ahead of copying
2630
# the history but that's done inside the merge code
2631
if other_branch is not None:
2632
_merge_tags_if_possible(other_branch, tree.branch)
2635
interesting_files = [path]
2637
interesting_files = None
2638
pb = ui.ui_factory.nested_progress_bar()
2641
conflict_count = _merge_helper(
2642
other, base, other_rev_id=other_revision_id,
2643
check_clean=(not force),
2644
merge_type=merge_type,
2645
reprocess=reprocess,
2646
show_base=show_base,
2649
pb=pb, file_list=interesting_files,
2650
change_reporter=change_reporter)
2653
if conflict_count != 0:
2657
except errors.AmbiguousBase, e:
2658
m = ("sorry, bzr can't determine the right merge base yet\n"
2659
"candidates are:\n "
2660
+ "\n ".join(e.bases)
2662
"please specify an explicit base with -r,\n"
2663
"and (if you want) report this to the bzr developers\n")
2666
# TODO: move up to common parent; this isn't merge-specific anymore.
2667
def _get_remembered_parent(self, tree, supplied_location, verb_string):
2668
"""Use tree.branch's parent if none was supplied.
2670
Report if the remembered location was used.
2672
if supplied_location is not None:
2673
return supplied_location
2674
stored_location = tree.branch.get_parent()
2675
mutter("%s", stored_location)
2676
if stored_location is None:
2677
raise errors.BzrCommandError("No location specified or remembered")
2678
display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2679
self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
2680
return stored_location
2683
class cmd_remerge(Command):
2686
Use this if you want to try a different merge technique while resolving
2687
conflicts. Some merge techniques are better than others, and remerge
2688
lets you try different ones on different files.
2690
The options for remerge have the same meaning and defaults as the ones for
2691
merge. The difference is that remerge can (only) be run when there is a
2692
pending merge, and it lets you specify particular files.
2696
$ bzr remerge --show-base
2697
Re-do the merge of all conflicted files, and show the base text in
2698
conflict regions, in addition to the usual THIS and OTHER texts.
2700
$ bzr remerge --merge-type weave --reprocess foobar
2701
Re-do the merge of "foobar", using the weave merge algorithm, with
2702
additional processing to reduce the size of conflict regions.
2704
takes_args = ['file*']
2705
takes_options = ['merge-type', 'reprocess',
2706
Option('show-base', help="Show base revision text in "
2709
def run(self, file_list=None, merge_type=None, show_base=False,
2711
if merge_type is None:
2712
merge_type = _mod_merge.Merge3Merger
2713
tree, file_list = tree_files(file_list)
2716
parents = tree.get_parent_ids()
2717
if len(parents) != 2:
2718
raise errors.BzrCommandError("Sorry, remerge only works after normal"
2719
" merges. Not cherrypicking or"
2721
repository = tree.branch.repository
2722
base_revision = common_ancestor(parents[0],
2723
parents[1], repository)
2724
base_tree = repository.revision_tree(base_revision)
2725
other_tree = repository.revision_tree(parents[1])
2726
interesting_ids = None
2728
conflicts = tree.conflicts()
2729
if file_list is not None:
2730
interesting_ids = set()
2731
for filename in file_list:
2732
file_id = tree.path2id(filename)
2734
raise errors.NotVersionedError(filename)
2735
interesting_ids.add(file_id)
2736
if tree.kind(file_id) != "directory":
2739
for name, ie in tree.inventory.iter_entries(file_id):
2740
interesting_ids.add(ie.file_id)
2741
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2743
# Remerge only supports resolving contents conflicts
2744
allowed_conflicts = ('text conflict', 'contents conflict')
2745
restore_files = [c.path for c in conflicts
2746
if c.typestring in allowed_conflicts]
2747
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
2748
tree.set_conflicts(ConflictList(new_conflicts))
2749
if file_list is not None:
2750
restore_files = file_list
2751
for filename in restore_files:
2753
restore(tree.abspath(filename))
2754
except errors.NotConflicted:
2756
conflicts = _mod_merge.merge_inner(
2757
tree.branch, other_tree, base_tree,
2759
interesting_ids=interesting_ids,
2760
other_rev_id=parents[1],
2761
merge_type=merge_type,
2762
show_base=show_base,
2763
reprocess=reprocess)
2772
class cmd_revert(Command):
2773
"""Revert files to a previous revision.
2775
Giving a list of files will revert only those files. Otherwise, all files
2776
will be reverted. If the revision is not specified with '--revision', the
2777
last committed revision is used.
2779
To remove only some changes, without reverting to a prior version, use
2780
merge instead. For example, "merge . --r-2..-3" will remove the changes
2781
introduced by -2, without affecting the changes introduced by -1. Or
2782
to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
2784
By default, any files that have been manually changed will be backed up
2785
first. (Files changed only by merge are not backed up.) Backup files have
2786
'.~#~' appended to their name, where # is a number.
2788
When you provide files, you can use their current pathname or the pathname
2789
from the target revision. So you can use revert to "undelete" a file by
2790
name. If you name a directory, all the contents of that directory will be
2794
_see_also = ['cat', 'export']
2795
takes_options = ['revision', 'no-backup']
2796
takes_args = ['file*']
2798
def run(self, revision=None, no_backup=False, file_list=None):
2799
if file_list is not None:
2800
if len(file_list) == 0:
2801
raise errors.BzrCommandError("No files specified")
2805
tree, file_list = tree_files(file_list)
2806
if revision is None:
2807
# FIXME should be tree.last_revision
2808
rev_id = tree.last_revision()
2809
elif len(revision) != 1:
2810
raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
2812
rev_id = revision[0].in_history(tree.branch).rev_id
2813
pb = ui.ui_factory.nested_progress_bar()
2815
tree.revert(file_list,
2816
tree.branch.repository.revision_tree(rev_id),
2817
not no_backup, pb, report_changes=True)
2822
class cmd_assert_fail(Command):
2823
"""Test reporting of assertion failures"""
2824
# intended just for use in testing
2829
raise AssertionError("always fails")
2832
class cmd_help(Command):
2833
"""Show help on a command or other topic.
2836
_see_also = ['topics']
2837
takes_options = [Option('long', 'show help on all commands')]
2838
takes_args = ['topic?']
2839
aliases = ['?', '--help', '-?', '-h']
2842
def run(self, topic=None, long=False):
2844
if topic is None and long:
2846
bzrlib.help.help(topic)
2849
class cmd_shell_complete(Command):
2850
"""Show appropriate completions for context.
2852
For a list of all available commands, say 'bzr shell-complete'.
2854
takes_args = ['context?']
2859
def run(self, context=None):
2860
import shellcomplete
2861
shellcomplete.shellcomplete(context)
2864
class cmd_fetch(Command):
2865
"""Copy in history from another branch but don't merge it.
2867
This is an internal method used for pull and merge.
2870
takes_args = ['from_branch', 'to_branch']
2871
def run(self, from_branch, to_branch):
2872
from bzrlib.fetch import Fetcher
2873
from_b = Branch.open(from_branch)
2874
to_b = Branch.open(to_branch)
2875
Fetcher(to_b, from_b)
2878
class cmd_missing(Command):
2879
"""Show unmerged/unpulled revisions between two branches.
2881
OTHER_BRANCH may be local or remote.
2884
_see_also = ['merge', 'pull']
2885
takes_args = ['other_branch?']
2886
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2888
'Display changes in the local branch only'),
2889
Option('theirs-only',
2890
'Display changes in the remote branch only'),
2895
encoding_type = 'replace'
2898
def run(self, other_branch=None, reverse=False, mine_only=False,
2899
theirs_only=False, log_format=None, long=False, short=False, line=False,
2900
show_ids=False, verbose=False):
2901
from bzrlib.missing import find_unmerged, iter_log_data
2902
from bzrlib.log import log_formatter
2903
local_branch = Branch.open_containing(u".")[0]
2904
parent = local_branch.get_parent()
2905
if other_branch is None:
2906
other_branch = parent
2907
if other_branch is None:
2908
raise errors.BzrCommandError("No peer location known or specified.")
2909
display_url = urlutils.unescape_for_display(parent,
2911
print "Using last location: " + display_url
2913
remote_branch = Branch.open(other_branch)
2914
if remote_branch.base == local_branch.base:
2915
remote_branch = local_branch
2916
local_branch.lock_read()
2918
remote_branch.lock_read()
2920
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2921
if (log_format is None):
2922
log_format = log.log_formatter_registry.get_default(
2924
lf = log_format(to_file=self.outf,
2926
show_timezone='original')
2927
if reverse is False:
2928
local_extra.reverse()
2929
remote_extra.reverse()
2930
if local_extra and not theirs_only:
2931
print "You have %d extra revision(s):" % len(local_extra)
2932
for data in iter_log_data(local_extra, local_branch.repository,
2935
printed_local = True
2937
printed_local = False
2938
if remote_extra and not mine_only:
2939
if printed_local is True:
2941
print "You are missing %d revision(s):" % len(remote_extra)
2942
for data in iter_log_data(remote_extra, remote_branch.repository,
2945
if not remote_extra and not local_extra:
2947
print "Branches are up to date."
2951
remote_branch.unlock()
2953
local_branch.unlock()
2954
if not status_code and parent is None and other_branch is not None:
2955
local_branch.lock_write()
2957
# handle race conditions - a parent might be set while we run.
2958
if local_branch.get_parent() is None:
2959
local_branch.set_parent(remote_branch.base)
2961
local_branch.unlock()
2965
class cmd_plugins(Command):
2970
import bzrlib.plugin
2971
from inspect import getdoc
2972
for name, plugin in bzrlib.plugin.all_plugins().items():
2973
if getattr(plugin, '__path__', None) is not None:
2974
print plugin.__path__[0]
2975
elif getattr(plugin, '__file__', None) is not None:
2976
print plugin.__file__
2982
print '\t', d.split('\n')[0]
2985
class cmd_testament(Command):
2986
"""Show testament (signing-form) of a revision."""
2987
takes_options = ['revision',
2988
Option('long', help='Produce long-format testament'),
2989
Option('strict', help='Produce a strict-format'
2991
takes_args = ['branch?']
2993
def run(self, branch=u'.', revision=None, long=False, strict=False):
2994
from bzrlib.testament import Testament, StrictTestament
2996
testament_class = StrictTestament
2998
testament_class = Testament
2999
b = WorkingTree.open_containing(branch)[0].branch
3002
if revision is None:
3003
rev_id = b.last_revision()
3005
rev_id = revision[0].in_history(b).rev_id
3006
t = testament_class.from_revision(b.repository, rev_id)
3008
sys.stdout.writelines(t.as_text_lines())
3010
sys.stdout.write(t.as_short_text())
3015
class cmd_annotate(Command):
3016
"""Show the origin of each line in a file.
3018
This prints out the given file with an annotation on the left side
3019
indicating which revision, author and date introduced the change.
3021
If the origin is the same for a run of consecutive lines, it is
3022
shown only at the top, unless the --all option is given.
3024
# TODO: annotate directories; showing when each file was last changed
3025
# TODO: if the working copy is modified, show annotations on that
3026
# with new uncommitted lines marked
3027
aliases = ['ann', 'blame', 'praise']
3028
takes_args = ['filename']
3029
takes_options = [Option('all', help='show annotations on all lines'),
3030
Option('long', help='show date in annotations'),
3036
def run(self, filename, all=False, long=False, revision=None,
3038
from bzrlib.annotate import annotate_file
3039
tree, relpath = WorkingTree.open_containing(filename)
3040
branch = tree.branch
3043
if revision is None:
3044
revision_id = branch.last_revision()
3045
elif len(revision) != 1:
3046
raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3048
revision_id = revision[0].in_history(branch).rev_id
3049
file_id = tree.path2id(relpath)
3050
tree = branch.repository.revision_tree(revision_id)
3051
file_version = tree.inventory[file_id].revision
3052
annotate_file(branch, file_version, file_id, long, all, sys.stdout,
3058
class cmd_re_sign(Command):
3059
"""Create a digital signature for an existing revision."""
3060
# TODO be able to replace existing ones.
3062
hidden = True # is this right ?
3063
takes_args = ['revision_id*']
3064
takes_options = ['revision']
3066
def run(self, revision_id_list=None, revision=None):
3067
import bzrlib.gpg as gpg
3068
if revision_id_list is not None and revision is not None:
3069
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3070
if revision_id_list is None and revision is None:
3071
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3072
b = WorkingTree.open_containing(u'.')[0].branch
3073
gpg_strategy = gpg.GPGStrategy(b.get_config())
3074
if revision_id_list is not None:
3075
for revision_id in revision_id_list:
3076
b.repository.sign_revision(revision_id, gpg_strategy)
3077
elif revision is not None:
3078
if len(revision) == 1:
3079
revno, rev_id = revision[0].in_history(b)
3080
b.repository.sign_revision(rev_id, gpg_strategy)
3081
elif len(revision) == 2:
3082
# are they both on rh- if so we can walk between them
3083
# might be nice to have a range helper for arbitrary
3084
# revision paths. hmm.
3085
from_revno, from_revid = revision[0].in_history(b)
3086
to_revno, to_revid = revision[1].in_history(b)
3087
if to_revid is None:
3088
to_revno = b.revno()
3089
if from_revno is None or to_revno is None:
3090
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3091
for revno in range(from_revno, to_revno + 1):
3092
b.repository.sign_revision(b.get_rev_id(revno),
3095
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3098
class cmd_bind(Command):
3099
"""Convert the current branch into a checkout of the supplied branch.
3101
Once converted into a checkout, commits must succeed on the master branch
3102
before they will be applied to the local branch.
3105
_see_also = ['checkouts', 'unbind']
3106
takes_args = ['location?']
3109
def run(self, location=None):
3110
b, relpath = Branch.open_containing(u'.')
3111
if location is None:
3113
location = b.get_old_bound_location()
3114
except errors.UpgradeRequired:
3115
raise errors.BzrCommandError('No location supplied. '
3116
'This format does not remember old locations.')
3118
if location is None:
3119
raise errors.BzrCommandError('No location supplied and no '
3120
'previous location known')
3121
b_other = Branch.open(location)
3124
except errors.DivergedBranches:
3125
raise errors.BzrCommandError('These branches have diverged.'
3126
' Try merging, and then bind again.')
3129
class cmd_unbind(Command):
3130
"""Convert the current checkout into a regular branch.
3132
After unbinding, the local branch is considered independent and subsequent
3133
commits will be local only.
3136
_see_also = ['checkouts', 'bind']
3141
b, relpath = Branch.open_containing(u'.')
3143
raise errors.BzrCommandError('Local branch is not bound')
3146
class cmd_uncommit(Command):
3147
"""Remove the last committed revision.
3149
--verbose will print out what is being removed.
3150
--dry-run will go through all the motions, but not actually
3153
In the future, uncommit will create a revision bundle, which can then
3157
# TODO: jam 20060108 Add an option to allow uncommit to remove
3158
# unreferenced information in 'branch-as-repository' branches.
3159
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3160
# information in shared branches as well.
3161
_see_also = ['commit']
3162
takes_options = ['verbose', 'revision',
3163
Option('dry-run', help='Don\'t actually make changes'),
3164
Option('force', help='Say yes to all questions.')]
3165
takes_args = ['location?']
3168
def run(self, location=None,
3169
dry_run=False, verbose=False,
3170
revision=None, force=False):
3171
from bzrlib.log import log_formatter, show_log
3173
from bzrlib.uncommit import uncommit
3175
if location is None:
3177
control, relpath = bzrdir.BzrDir.open_containing(location)
3179
tree = control.open_workingtree()
3181
except (errors.NoWorkingTree, errors.NotLocalUrl):
3183
b = control.open_branch()
3186
if revision is None:
3189
# 'bzr uncommit -r 10' actually means uncommit
3190
# so that the final tree is at revno 10.
3191
# but bzrlib.uncommit.uncommit() actually uncommits
3192
# the revisions that are supplied.
3193
# So we need to offset it by one
3194
revno = revision[0].in_history(b).revno+1
3196
if revno <= b.revno():
3197
rev_id = b.get_rev_id(revno)
3199
self.outf.write('No revisions to uncommit.\n')
3202
lf = log_formatter('short',
3204
show_timezone='original')
3209
direction='forward',
3210
start_revision=revno,
3211
end_revision=b.revno())
3214
print 'Dry-run, pretending to remove the above revisions.'
3216
val = raw_input('Press <enter> to continue')
3218
print 'The above revision(s) will be removed.'
3220
val = raw_input('Are you sure [y/N]? ')
3221
if val.lower() not in ('y', 'yes'):
3225
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3229
class cmd_break_lock(Command):
3230
"""Break a dead lock on a repository, branch or working directory.
3232
CAUTION: Locks should only be broken when you are sure that the process
3233
holding the lock has been stopped.
3235
You can get information on what locks are open via the 'bzr info' command.
3240
takes_args = ['location?']
3242
def run(self, location=None, show=False):
3243
if location is None:
3245
control, relpath = bzrdir.BzrDir.open_containing(location)
3247
control.break_lock()
3248
except NotImplementedError:
3252
class cmd_wait_until_signalled(Command):
3253
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3255
This just prints a line to signal when it is ready, then blocks on stdin.
3261
sys.stdout.write("running\n")
3263
sys.stdin.readline()
3266
class cmd_serve(Command):
3267
"""Run the bzr server."""
3269
aliases = ['server']
3273
help='serve on stdin/out for use from inetd or sshd'),
3275
help='listen for connections on nominated port of the form '
3276
'[hostname:]portnumber. Passing 0 as the port number will '
3277
'result in a dynamically allocated port. Default port is '
3281
help='serve contents of directory',
3283
Option('allow-writes',
3284
help='By default the server is a readonly server. Supplying '
3285
'--allow-writes enables write access to the contents of '
3286
'the served directory and below. '
3290
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3291
from bzrlib.smart import medium, server
3292
from bzrlib.transport import get_transport
3293
from bzrlib.transport.chroot import ChrootServer
3294
from bzrlib.transport.remote import BZR_DEFAULT_PORT
3295
if directory is None:
3296
directory = os.getcwd()
3297
url = urlutils.local_path_to_url(directory)
3298
if not allow_writes:
3299
url = 'readonly+' + url
3300
chroot_server = ChrootServer(get_transport(url))
3301
chroot_server.setUp()
3302
t = get_transport(chroot_server.get_url())
3304
smart_server = medium.SmartServerPipeStreamMedium(
3305
sys.stdin, sys.stdout, t)
3308
port = BZR_DEFAULT_PORT
3312
host, port = port.split(':')
3316
smart_server = server.SmartTCPServer(t, host=host, port=port)
3317
print 'listening on port: ', smart_server.port
3319
# for the duration of this server, no UI output is permitted.
3320
# note that this may cause problems with blackbox tests. This should
3321
# be changed with care though, as we dont want to use bandwidth sending
3322
# progress over stderr to smart server clients!
3323
old_factory = ui.ui_factory
3325
ui.ui_factory = ui.SilentUIFactory()
3326
smart_server.serve()
3328
ui.ui_factory = old_factory
3331
class cmd_join(Command):
3332
"""Combine a subtree into its containing tree.
3334
This command is for experimental use only. It requires the target tree
3335
to be in dirstate-with-subtree format, which cannot be converted into
3338
The TREE argument should be an independent tree, inside another tree, but
3339
not part of it. (Such trees can be produced by "bzr split", but also by
3340
running "bzr branch" with the target inside a tree.)
3342
The result is a combined tree, with the subtree no longer an independant
3343
part. This is marked as a merge of the subtree into the containing tree,
3344
and all history is preserved.
3346
If --reference is specified, the subtree retains its independence. It can
3347
be branched by itself, and can be part of multiple projects at the same
3348
time. But operations performed in the containing tree, such as commit
3349
and merge, will recurse into the subtree.
3352
_see_also = ['split']
3353
takes_args = ['tree']
3354
takes_options = [Option('reference', 'join by reference')]
3357
def run(self, tree, reference=False):
3358
sub_tree = WorkingTree.open(tree)
3359
parent_dir = osutils.dirname(sub_tree.basedir)
3360
containing_tree = WorkingTree.open_containing(parent_dir)[0]
3361
repo = containing_tree.branch.repository
3362
if not repo.supports_rich_root():
3363
raise errors.BzrCommandError(
3364
"Can't join trees because %s doesn't support rich root data.\n"
3365
"You can use bzr upgrade on the repository."
3369
containing_tree.add_reference(sub_tree)
3370
except errors.BadReferenceTarget, e:
3371
# XXX: Would be better to just raise a nicely printable
3372
# exception from the real origin. Also below. mbp 20070306
3373
raise errors.BzrCommandError("Cannot join %s. %s" %
3377
containing_tree.subsume(sub_tree)
3378
except errors.BadSubsumeSource, e:
3379
raise errors.BzrCommandError("Cannot join %s. %s" %
3383
class cmd_split(Command):
3384
"""Split a tree into two trees.
3386
This command is for experimental use only. It requires the target tree
3387
to be in dirstate-with-subtree format, which cannot be converted into
3390
The TREE argument should be a subdirectory of a working tree. That
3391
subdirectory will be converted into an independent tree, with its own
3392
branch. Commits in the top-level tree will not apply to the new subtree.
3393
If you want that behavior, do "bzr join --reference TREE".
3396
_see_also = ['join']
3397
takes_args = ['tree']
3401
def run(self, tree):
3402
containing_tree, subdir = WorkingTree.open_containing(tree)
3403
sub_id = containing_tree.path2id(subdir)
3405
raise errors.NotVersionedError(subdir)
3407
containing_tree.extract(sub_id)
3408
except errors.RootNotRich:
3409
raise errors.UpgradeRequired(containing_tree.branch.base)
3413
class cmd_merge_directive(Command):
3414
"""Generate a merge directive for auto-merge tools.
3416
A directive requests a merge to be performed, and also provides all the
3417
information necessary to do so. This means it must either include a
3418
revision bundle, or the location of a branch containing the desired
3421
A submit branch (the location to merge into) must be supplied the first
3422
time the command is issued. After it has been supplied once, it will
3423
be remembered as the default.
3425
A public branch is optional if a revision bundle is supplied, but required
3426
if --diff or --plain is specified. It will be remembered as the default
3427
after the first use.
3430
takes_args = ['submit_branch?', 'public_branch?']
3433
RegistryOption.from_kwargs('patch-type',
3434
'The type of patch to include in the directive',
3435
title='Patch type', value_switches=True, enum_switch=False,
3436
bundle='Bazaar revision bundle (default)',
3437
diff='Normal unified diff',
3438
plain='No patch, just directive'),
3439
Option('sign', help='GPG-sign the directive'), 'revision',
3440
Option('mail-to', type=str,
3441
help='Instead of printing the directive, email to this address'),
3442
Option('message', type=str, short_name='m',
3443
help='Message to use when committing this merge')
3446
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
3447
sign=False, revision=None, mail_to=None, message=None):
3448
if patch_type == 'plain':
3450
branch = Branch.open('.')
3451
stored_submit_branch = branch.get_submit_branch()
3452
if submit_branch is None:
3453
submit_branch = stored_submit_branch
3455
if stored_submit_branch is None:
3456
branch.set_submit_branch(submit_branch)
3457
if submit_branch is None:
3458
submit_branch = branch.get_parent()
3459
if submit_branch is None:
3460
raise errors.BzrCommandError('No submit branch specified or known')
3462
stored_public_branch = branch.get_public_branch()
3463
if public_branch is None:
3464
public_branch = stored_public_branch
3465
elif stored_public_branch is None:
3466
branch.set_public_branch(public_branch)
3467
if patch_type != "bundle" and public_branch is None:
3468
raise errors.BzrCommandError('No public branch specified or'
3470
if revision is not None:
3471
if len(revision) != 1:
3472
raise errors.BzrCommandError('bzr merge-directive takes '
3473
'exactly one revision identifier')
3475
revision_id = revision[0].in_history(branch).rev_id
3477
revision_id = branch.last_revision()
3478
directive = merge_directive.MergeDirective.from_objects(
3479
branch.repository, revision_id, time.time(),
3480
osutils.local_time_offset(), submit_branch,
3481
public_branch=public_branch, patch_type=patch_type,
3485
self.outf.write(directive.to_signed(branch))
3487
self.outf.writelines(directive.to_lines())
3489
message = directive.to_email(mail_to, branch, sign)
3491
server = branch.get_config().get_user_option('smtp_server')
3493
server = 'localhost'
3495
s.sendmail(message['From'], message['To'], message.as_string())
3498
class cmd_tag(Command):
3499
"""Create a tag naming a revision.
3501
Tags give human-meaningful names to revisions. Commands that take a -r
3502
(--revision) option can be given -rtag:X, where X is any previously
3505
Tags are stored in the branch. Tags are copied from one branch to another
3506
along when you branch, push, pull or merge.
3508
It is an error to give a tag name that already exists unless you pass
3509
--force, in which case the tag is moved to point to the new revision.
3512
_see_also = ['commit', 'tags']
3513
takes_args = ['tag_name']
3516
help='Delete this tag rather than placing it.',
3519
help='Branch in which to place the tag.',
3524
help='Replace existing tags',
3529
def run(self, tag_name,
3535
branch, relpath = Branch.open_containing(directory)
3539
branch.tags.delete_tag(tag_name)
3540
self.outf.write('Deleted tag %s.\n' % tag_name)
3543
if len(revision) != 1:
3544
raise errors.BzrCommandError(
3545
"Tags can only be placed on a single revision, "
3547
revision_id = revision[0].in_history(branch).rev_id
3549
revision_id = branch.last_revision()
3550
if (not force) and branch.tags.has_tag(tag_name):
3551
raise errors.TagAlreadyExists(tag_name)
3552
branch.tags.set_tag(tag_name, revision_id)
3553
self.outf.write('Created tag %s.\n' % tag_name)
3558
class cmd_tags(Command):
3561
This tag shows a table of tag names and the revisions they reference.
3567
help='Branch whose tags should be displayed',
3577
branch, relpath = Branch.open_containing(directory)
3578
for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
3579
self.outf.write('%-20s %s\n' % (tag_name, target))
3582
# command-line interpretation helper for merge-related commands
3583
def _merge_helper(other_revision, base_revision,
3584
check_clean=True, ignore_zero=False,
3585
this_dir=None, backup_files=False,
3587
file_list=None, show_base=False, reprocess=False,
3590
change_reporter=None,
3592
"""Merge changes into a tree.
3595
list(path, revno) Base for three-way merge.
3596
If [None, None] then a base will be automatically determined.
3598
list(path, revno) Other revision for three-way merge.
3600
Directory to merge changes into; '.' by default.
3602
If true, this_dir must have no uncommitted changes before the
3604
ignore_zero - If true, suppress the "zero conflicts" message when
3605
there are no conflicts; should be set when doing something we expect
3606
to complete perfectly.
3607
file_list - If supplied, merge only changes to selected files.
3609
All available ancestors of other_revision and base_revision are
3610
automatically pulled into the branch.
3612
The revno may be -1 to indicate the last revision on the branch, which is
3615
This function is intended for use from the command line; programmatic
3616
clients might prefer to call merge.merge_inner(), which has less magic
3619
# Loading it late, so that we don't always have to import bzrlib.merge
3620
if merge_type is None:
3621
merge_type = _mod_merge.Merge3Merger
3622
if this_dir is None:
3624
this_tree = WorkingTree.open_containing(this_dir)[0]
3625
if show_base and not merge_type is _mod_merge.Merge3Merger:
3626
raise errors.BzrCommandError("Show-base is not supported for this merge"
3627
" type. %s" % merge_type)
3628
if reprocess and not merge_type.supports_reprocess:
3629
raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3630
" type %s." % merge_type)
3631
if reprocess and show_base:
3632
raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3633
# TODO: jam 20070226 We should really lock these trees earlier. However, we
3634
# only want to take out a lock_tree_write() if we don't have to pull
3635
# any ancestry. But merge might fetch ancestry in the middle, in
3636
# which case we would need a lock_write().
3637
# Because we cannot upgrade locks, for now we live with the fact that
3638
# the tree will be locked multiple times during a merge. (Maybe
3639
# read-only some of the time, but it means things will get read
3642
merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3643
pb=pb, change_reporter=change_reporter)
3644
merger.pp = ProgressPhase("Merge phase", 5, pb)
3645
merger.pp.next_phase()
3646
merger.check_basis(check_clean)
3647
if other_rev_id is not None:
3648
merger.set_other_revision(other_rev_id, this_tree.branch)
3650
merger.set_other(other_revision)
3651
merger.pp.next_phase()
3652
merger.set_base(base_revision)
3653
if merger.base_rev_id == merger.other_rev_id:
3654
note('Nothing to do.')
3656
if file_list is None:
3657
if pull and merger.base_rev_id == merger.this_rev_id:
3658
# FIXME: deduplicate with pull
3659
result = merger.this_tree.pull(merger.this_branch,
3660
False, merger.other_rev_id)
3661
if result.old_revid == result.new_revid:
3662
note('No revisions to pull.')
3664
note('Now on revision %d.' % result.new_revno)
3666
merger.backup_files = backup_files
3667
merger.merge_type = merge_type
3668
merger.set_interesting_files(file_list)
3669
merger.show_base = show_base
3670
merger.reprocess = reprocess
3671
conflicts = merger.do_merge()
3672
if file_list is None:
3673
merger.set_pending()
3680
merge = _merge_helper
3683
# these get imported and then picked up by the scan for cmd_*
3684
# TODO: Some more consistent way to split command definitions across files;
3685
# we do need to load at least some information about them to know of
3686
# aliases. ideally we would avoid loading the implementation until the
3687
# details were needed.
3688
from bzrlib.cmd_version_info import cmd_version_info
3689
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3690
from bzrlib.bundle.commands import cmd_bundle_revisions
3691
from bzrlib.sign_my_commits import cmd_sign_my_commits
3692
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
3693
cmd_weave_plan_merge, cmd_weave_merge_text