1
# Copyright (C) 2004, 2005, 2006, 2007, 2008 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"""
21
from bzrlib.lazy_import import lazy_import
22
lazy_import(globals(), """
42
revision as _mod_revision,
49
from bzrlib.branch import Branch
50
from bzrlib.conflicts import ConflictList
51
from bzrlib.revisionspec import RevisionSpec
52
from bzrlib.smtp_connection import SMTPConnection
53
from bzrlib.workingtree import WorkingTree
56
from bzrlib.commands import Command, display_command
57
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
58
from bzrlib.trace import mutter, note, warning, is_quiet
61
def tree_files(file_list, default_branch=u'.'):
63
return internal_tree_files(file_list, default_branch)
64
except errors.FileInWrongBranch, e:
65
raise errors.BzrCommandError("%s is not in the same branch as %s" %
66
(e.path, file_list[0]))
69
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
74
rev_tree = tree.basis_tree()
76
rev_tree = branch.basis_tree()
78
if len(revisions) != 1:
79
raise errors.BzrCommandError(
80
'bzr %s --revision takes exactly one revision identifier' % (
82
rev_tree = revisions[0].as_tree(branch)
86
# XXX: Bad function name; should possibly also be a class method of
87
# WorkingTree rather than a function.
88
def internal_tree_files(file_list, default_branch=u'.'):
89
"""Convert command-line paths to a WorkingTree and relative paths.
91
This is typically used for command-line processors that take one or
92
more filenames, and infer the workingtree that contains them.
94
The filenames given are not required to exist.
96
:param file_list: Filenames to convert.
98
:param default_branch: Fallback tree path to use if file_list is empty or
101
:return: workingtree, [relative_paths]
103
if file_list is None or len(file_list) == 0:
104
return WorkingTree.open_containing(default_branch)[0], file_list
105
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
106
return tree, safe_relpath_files(tree, file_list)
109
def safe_relpath_files(tree, file_list):
110
"""Convert file_list into a list of relpaths in tree.
112
:param tree: A tree to operate on.
113
:param file_list: A list of user provided paths or None.
114
:return: A list of relative paths.
115
:raises errors.PathNotChild: When a provided path is in a different tree
118
if file_list is None:
121
for filename in file_list:
123
new_list.append(tree.relpath(osutils.dereference_path(filename)))
124
except errors.PathNotChild:
125
raise errors.FileInWrongBranch(tree.branch, filename)
129
# TODO: Make sure no commands unconditionally use the working directory as a
130
# branch. If a filename argument is used, the first of them should be used to
131
# specify the branch. (Perhaps this can be factored out into some kind of
132
# Argument class, representing a file in a branch, where the first occurrence
135
class cmd_status(Command):
136
"""Display status summary.
138
This reports on versioned and unknown files, reporting them
139
grouped by state. Possible states are:
142
Versioned in the working copy but not in the previous revision.
145
Versioned in the previous revision but removed or deleted
149
Path of this file changed from the previous revision;
150
the text may also have changed. This includes files whose
151
parent directory was renamed.
154
Text has changed since the previous revision.
157
File kind has been changed (e.g. from file to directory).
160
Not versioned and not matching an ignore pattern.
162
To see ignored files use 'bzr ignored'. For details on the
163
changes to file texts, use 'bzr diff'.
165
Note that --short or -S gives status flags for each item, similar
166
to Subversion's status command. To get output similar to svn -q,
169
If no arguments are specified, the status of the entire working
170
directory is shown. Otherwise, only the status of the specified
171
files or directories is reported. If a directory is given, status
172
is reported for everything inside that directory.
174
If a revision argument is given, the status is calculated against
175
that revision, or between two revisions if two are provided.
178
# TODO: --no-recurse, --recurse options
180
takes_args = ['file*']
181
takes_options = ['show-ids', 'revision', 'change',
182
Option('short', help='Use short status indicators.',
184
Option('versioned', help='Only show versioned files.',
186
Option('no-pending', help='Don\'t show pending merges.',
189
aliases = ['st', 'stat']
191
encoding_type = 'replace'
192
_see_also = ['diff', 'revert', 'status-flags']
195
def run(self, show_ids=False, file_list=None, revision=None, short=False,
196
versioned=False, no_pending=False):
197
from bzrlib.status import show_tree_status
199
if revision and len(revision) > 2:
200
raise errors.BzrCommandError('bzr status --revision takes exactly'
201
' one or two revision specifiers')
203
tree, relfile_list = tree_files(file_list)
204
# Avoid asking for specific files when that is not needed.
205
if relfile_list == ['']:
207
# Don't disable pending merges for full trees other than '.'.
208
if file_list == ['.']:
210
# A specific path within a tree was given.
211
elif relfile_list is not None:
213
show_tree_status(tree, show_ids=show_ids,
214
specific_files=relfile_list, revision=revision,
215
to_file=self.outf, short=short, versioned=versioned,
216
show_pending=(not no_pending))
219
class cmd_cat_revision(Command):
220
"""Write out metadata for a revision.
222
The revision to print can either be specified by a specific
223
revision identifier, or you can use --revision.
227
takes_args = ['revision_id?']
228
takes_options = ['revision']
229
# cat-revision is more for frontends so should be exact
233
def run(self, revision_id=None, revision=None):
234
if revision_id is not None and revision is not None:
235
raise errors.BzrCommandError('You can only supply one of'
236
' revision_id or --revision')
237
if revision_id is None and revision is None:
238
raise errors.BzrCommandError('You must supply either'
239
' --revision or a revision_id')
240
b = WorkingTree.open_containing(u'.')[0].branch
242
# TODO: jam 20060112 should cat-revision always output utf-8?
243
if revision_id is not None:
244
revision_id = osutils.safe_revision_id(revision_id, warn=False)
246
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
247
except errors.NoSuchRevision:
248
msg = "The repository %s contains no revision %s." % (b.repository.base,
250
raise errors.BzrCommandError(msg)
251
elif revision is not None:
254
raise errors.BzrCommandError('You cannot specify a NULL'
256
rev_id = rev.as_revision_id(b)
257
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
260
class cmd_dump_btree(Command):
261
"""Dump the contents of a btree index file to disk.
263
This is useful because the pages are compressed, so they cannot be read
267
# TODO: Do we want to dump the internal nodes as well?
268
# TODO: It would be nice to be able to dump the un-parsed information,
269
# rather than only going through iter_all_entries. However, this is
270
# good enough for a start
272
takes_args = ['path']
275
from bzrlib import btree_index
277
dirname, basename = osutils.split(path)
278
t = transport.get_transport(dirname)
280
st = t.stat(basename)
281
except errors.TransportNotPossible:
282
# We can't stat, so we'll fake it because we have to do the 'get()'
284
bt = btree_index.BTreeGraphIndex(t, basename, None)
285
bytes = t.get_bytes(basename)
286
bt._file = cStringIO.StringIO(bytes)
287
bt._size = len(bytes)
289
bt = btree_index.BTreeGraphIndex(t, basename, st.st_size)
290
for node in bt.iter_all_entries():
291
# Node is made up of:
292
# (index, key, value, [references])
293
self.outf.write('%s\n' % (node[1:],))
296
class cmd_remove_tree(Command):
297
"""Remove the working tree from a given branch/checkout.
299
Since a lightweight checkout is little more than a working tree
300
this will refuse to run against one.
302
To re-create the working tree, use "bzr checkout".
304
_see_also = ['checkout', 'working-trees']
305
takes_args = ['location?']
308
help='Remove the working tree even if it has '
309
'uncommitted changes.'),
312
def run(self, location='.', force=False):
313
d = bzrdir.BzrDir.open(location)
316
working = d.open_workingtree()
317
except errors.NoWorkingTree:
318
raise errors.BzrCommandError("No working tree to remove")
319
except errors.NotLocalUrl:
320
raise errors.BzrCommandError("You cannot remove the working tree of a "
323
changes = working.changes_from(working.basis_tree())
324
if changes.has_changed():
325
raise errors.UncommittedChanges(working)
327
working_path = working.bzrdir.root_transport.base
328
branch_path = working.branch.bzrdir.root_transport.base
329
if working_path != branch_path:
330
raise errors.BzrCommandError("You cannot remove the working tree from "
331
"a lightweight checkout")
333
d.destroy_workingtree()
336
class cmd_revno(Command):
337
"""Show current revision number.
339
This is equal to the number of revisions on this branch.
343
takes_args = ['location?']
346
def run(self, location=u'.'):
347
self.outf.write(str(Branch.open_containing(location)[0].revno()))
348
self.outf.write('\n')
351
class cmd_revision_info(Command):
352
"""Show revision number and revision id for a given revision identifier.
355
takes_args = ['revision_info*']
356
takes_options = ['revision']
359
def run(self, revision=None, revision_info_list=[]):
362
if revision is not None:
363
revs.extend(revision)
364
if revision_info_list is not None:
365
for rev in revision_info_list:
366
revs.append(RevisionSpec.from_string(rev))
368
b = Branch.open_containing(u'.')[0]
371
revs.append(RevisionSpec.from_string('-1'))
374
revision_id = rev.as_revision_id(b)
376
revno = '%4d' % (b.revision_id_to_revno(revision_id))
377
except errors.NoSuchRevision:
378
dotted_map = b.get_revision_id_to_revno_map()
379
revno = '.'.join(str(i) for i in dotted_map[revision_id])
380
print '%s %s' % (revno, revision_id)
383
class cmd_add(Command):
384
"""Add specified files or directories.
386
In non-recursive mode, all the named items are added, regardless
387
of whether they were previously ignored. A warning is given if
388
any of the named files are already versioned.
390
In recursive mode (the default), files are treated the same way
391
but the behaviour for directories is different. Directories that
392
are already versioned do not give a warning. All directories,
393
whether already versioned or not, are searched for files or
394
subdirectories that are neither versioned or ignored, and these
395
are added. This search proceeds recursively into versioned
396
directories. If no names are given '.' is assumed.
398
Therefore simply saying 'bzr add' will version all files that
399
are currently unknown.
401
Adding a file whose parent directory is not versioned will
402
implicitly add the parent, and so on up to the root. This means
403
you should never need to explicitly add a directory, they'll just
404
get added when you add a file in the directory.
406
--dry-run will show which files would be added, but not actually
409
--file-ids-from will try to use the file ids from the supplied path.
410
It looks up ids trying to find a matching parent directory with the
411
same filename, and then by pure path. This option is rarely needed
412
but can be useful when adding the same logical file into two
413
branches that will be merged later (without showing the two different
414
adds as a conflict). It is also useful when merging another project
415
into a subdirectory of this one.
417
takes_args = ['file*']
420
help="Don't recursively add the contents of directories."),
422
help="Show what would be done, but don't actually do anything."),
424
Option('file-ids-from',
426
help='Lookup file ids from this tree.'),
428
encoding_type = 'replace'
429
_see_also = ['remove']
431
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
436
if file_ids_from is not None:
438
base_tree, base_path = WorkingTree.open_containing(
440
except errors.NoWorkingTree:
441
base_branch, base_path = Branch.open_containing(
443
base_tree = base_branch.basis_tree()
445
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
446
to_file=self.outf, should_print=(not is_quiet()))
448
action = bzrlib.add.AddAction(to_file=self.outf,
449
should_print=(not is_quiet()))
452
base_tree.lock_read()
454
file_list = self._maybe_expand_globs(file_list)
456
tree = WorkingTree.open_containing(file_list[0])[0]
458
tree = WorkingTree.open_containing(u'.')[0]
459
added, ignored = tree.smart_add(file_list, not
460
no_recurse, action=action, save=not dry_run)
462
if base_tree is not None:
466
for glob in sorted(ignored.keys()):
467
for path in ignored[glob]:
468
self.outf.write("ignored %s matching \"%s\"\n"
472
for glob, paths in ignored.items():
473
match_len += len(paths)
474
self.outf.write("ignored %d file(s).\n" % match_len)
475
self.outf.write("If you wish to add some of these files,"
476
" please add them by name.\n")
479
class cmd_mkdir(Command):
480
"""Create a new versioned directory.
482
This is equivalent to creating the directory and then adding it.
485
takes_args = ['dir+']
486
encoding_type = 'replace'
488
def run(self, dir_list):
491
wt, dd = WorkingTree.open_containing(d)
493
self.outf.write('added %s\n' % d)
496
class cmd_relpath(Command):
497
"""Show path of a file relative to root"""
499
takes_args = ['filename']
503
def run(self, filename):
504
# TODO: jam 20050106 Can relpath return a munged path if
505
# sys.stdout encoding cannot represent it?
506
tree, relpath = WorkingTree.open_containing(filename)
507
self.outf.write(relpath)
508
self.outf.write('\n')
511
class cmd_inventory(Command):
512
"""Show inventory of the current working copy or a revision.
514
It is possible to limit the output to a particular entry
515
type using the --kind option. For example: --kind file.
517
It is also possible to restrict the list of files to a specific
518
set. For example: bzr inventory --show-ids this/file
527
help='List entries of a particular kind: file, directory, symlink.',
530
takes_args = ['file*']
533
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
534
if kind and kind not in ['file', 'directory', 'symlink']:
535
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
537
work_tree, file_list = tree_files(file_list)
538
work_tree.lock_read()
540
if revision is not None:
541
if len(revision) > 1:
542
raise errors.BzrCommandError(
543
'bzr inventory --revision takes exactly one revision'
545
tree = revision[0].as_tree(work_tree.branch)
547
extra_trees = [work_tree]
553
if file_list is not None:
554
file_ids = tree.paths2ids(file_list, trees=extra_trees,
555
require_versioned=True)
556
# find_ids_across_trees may include some paths that don't
558
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
559
for file_id in file_ids if file_id in tree)
561
entries = tree.inventory.entries()
564
if tree is not work_tree:
567
for path, entry in entries:
568
if kind and kind != entry.kind:
571
self.outf.write('%-50s %s\n' % (path, entry.file_id))
573
self.outf.write(path)
574
self.outf.write('\n')
577
class cmd_mv(Command):
578
"""Move or rename a file.
581
bzr mv OLDNAME NEWNAME
583
bzr mv SOURCE... DESTINATION
585
If the last argument is a versioned directory, all the other names
586
are moved into it. Otherwise, there must be exactly two arguments
587
and the file is changed to a new name.
589
If OLDNAME does not exist on the filesystem but is versioned and
590
NEWNAME does exist on the filesystem but is not versioned, mv
591
assumes that the file has been manually moved and only updates
592
its internal inventory to reflect that change.
593
The same is valid when moving many SOURCE files to a DESTINATION.
595
Files cannot be moved between branches.
598
takes_args = ['names*']
599
takes_options = [Option("after", help="Move only the bzr identifier"
600
" of the file, because the file has already been moved."),
602
aliases = ['move', 'rename']
603
encoding_type = 'replace'
605
def run(self, names_list, after=False):
606
if names_list is None:
609
if len(names_list) < 2:
610
raise errors.BzrCommandError("missing file argument")
611
tree, rel_names = tree_files(names_list)
614
self._run(tree, names_list, rel_names, after)
618
def _run(self, tree, names_list, rel_names, after):
619
into_existing = osutils.isdir(names_list[-1])
620
if into_existing and len(names_list) == 2:
622
# a. case-insensitive filesystem and change case of dir
623
# b. move directory after the fact (if the source used to be
624
# a directory, but now doesn't exist in the working tree
625
# and the target is an existing directory, just rename it)
626
if (not tree.case_sensitive
627
and rel_names[0].lower() == rel_names[1].lower()):
628
into_existing = False
631
from_id = tree.path2id(rel_names[0])
632
if (not osutils.lexists(names_list[0]) and
633
from_id and inv.get_file_kind(from_id) == "directory"):
634
into_existing = False
637
# move into existing directory
638
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
639
self.outf.write("%s => %s\n" % pair)
641
if len(names_list) != 2:
642
raise errors.BzrCommandError('to mv multiple files the'
643
' destination must be a versioned'
645
tree.rename_one(rel_names[0], rel_names[1], after=after)
646
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
649
class cmd_pull(Command):
650
"""Turn this branch into a mirror of another branch.
652
This command only works on branches that have not diverged. Branches are
653
considered diverged if the destination branch's most recent commit is one
654
that has not been merged (directly or indirectly) into the parent.
656
If branches have diverged, you can use 'bzr merge' to integrate the changes
657
from one into the other. Once one branch has merged, the other should
658
be able to pull it again.
660
If you want to forget your local changes and just update your branch to
661
match the remote one, use pull --overwrite.
663
If there is no default location set, the first pull will set it. After
664
that, you can omit the location to use the default. To change the
665
default, use --remember. The value will only be saved if the remote
666
location can be accessed.
668
Note: The location can be specified either in the form of a branch,
669
or in the form of a path to a file containing a merge directive generated
673
_see_also = ['push', 'update', 'status-flags']
674
takes_options = ['remember', 'overwrite', 'revision',
675
custom_help('verbose',
676
help='Show logs of pulled revisions.'),
678
help='Branch to pull into, '
679
'rather than the one containing the working directory.',
684
takes_args = ['location?']
685
encoding_type = 'replace'
687
def run(self, location=None, remember=False, overwrite=False,
688
revision=None, verbose=False,
690
# FIXME: too much stuff is in the command class
693
if directory is None:
696
tree_to = WorkingTree.open_containing(directory)[0]
697
branch_to = tree_to.branch
698
except errors.NoWorkingTree:
700
branch_to = Branch.open_containing(directory)[0]
702
possible_transports = []
703
if location is not None:
705
mergeable = bundle.read_mergeable_from_url(location,
706
possible_transports=possible_transports)
707
except errors.NotABundle:
710
stored_loc = branch_to.get_parent()
712
if stored_loc is None:
713
raise errors.BzrCommandError("No pull location known or"
716
display_url = urlutils.unescape_for_display(stored_loc,
719
self.outf.write("Using saved parent location: %s\n" % display_url)
720
location = stored_loc
722
if mergeable is not None:
723
if revision is not None:
724
raise errors.BzrCommandError(
725
'Cannot use -r with merge directives or bundles')
726
mergeable.install_revisions(branch_to.repository)
727
base_revision_id, revision_id, verified = \
728
mergeable.get_merge_request(branch_to.repository)
729
branch_from = branch_to
731
branch_from = Branch.open(location,
732
possible_transports=possible_transports)
734
if branch_to.get_parent() is None or remember:
735
branch_to.set_parent(branch_from.base)
737
if revision is not None:
738
if len(revision) == 1:
739
revision_id = revision[0].as_revision_id(branch_from)
741
raise errors.BzrCommandError(
742
'bzr pull --revision takes one value.')
744
branch_to.lock_write()
746
if tree_to is not None:
747
change_reporter = delta._ChangeReporter(
748
unversioned_filter=tree_to.is_ignored)
749
result = tree_to.pull(branch_from, overwrite, revision_id,
751
possible_transports=possible_transports)
753
result = branch_to.pull(branch_from, overwrite, revision_id)
755
result.report(self.outf)
756
if verbose and result.old_revid != result.new_revid:
758
branch_to.repository.iter_reverse_revision_history(
761
new_rh = branch_to.revision_history()
762
log.show_changed_revisions(branch_to, old_rh, new_rh,
768
class cmd_push(Command):
769
"""Update a mirror of this branch.
771
The target branch will not have its working tree populated because this
772
is both expensive, and is not supported on remote file systems.
774
Some smart servers or protocols *may* put the working tree in place in
777
This command only works on branches that have not diverged. Branches are
778
considered diverged if the destination branch's most recent commit is one
779
that has not been merged (directly or indirectly) by the source branch.
781
If branches have diverged, you can use 'bzr push --overwrite' to replace
782
the other branch completely, discarding its unmerged changes.
784
If you want to ensure you have the different changes in the other branch,
785
do a merge (see bzr help merge) from the other branch, and commit that.
786
After that you will be able to do a push without '--overwrite'.
788
If there is no default push location set, the first push will set it.
789
After that, you can omit the location to use the default. To change the
790
default, use --remember. The value will only be saved if the remote
791
location can be accessed.
794
_see_also = ['pull', 'update', 'working-trees']
795
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
796
Option('create-prefix',
797
help='Create the path leading up to the branch '
798
'if it does not already exist.'),
800
help='Branch to push from, '
801
'rather than the one containing the working directory.',
805
Option('use-existing-dir',
806
help='By default push will fail if the target'
807
' directory exists, but does not already'
808
' have a control directory. This flag will'
809
' allow push to proceed.'),
811
help='Create a stacked branch that references the public location '
812
'of the parent branch.'),
814
help='Create a stacked branch that refers to another branch '
815
'for the commit history. Only the work not present in the '
816
'referenced branch is included in the branch created.',
819
takes_args = ['location?']
820
encoding_type = 'replace'
822
def run(self, location=None, remember=False, overwrite=False,
823
create_prefix=False, verbose=False, revision=None,
824
use_existing_dir=False, directory=None, stacked_on=None,
826
from bzrlib.push import _show_push_branch
828
# Get the source branch and revision_id
829
if directory is None:
831
br_from = Branch.open_containing(directory)[0]
832
if revision is not None:
833
if len(revision) == 1:
834
revision_id = revision[0].in_history(br_from).rev_id
836
raise errors.BzrCommandError(
837
'bzr push --revision takes one value.')
839
revision_id = br_from.last_revision()
841
# Get the stacked_on branch, if any
842
if stacked_on is not None:
843
stacked_on = urlutils.normalize_url(stacked_on)
845
parent_url = br_from.get_parent()
847
parent = Branch.open(parent_url)
848
stacked_on = parent.get_public_branch()
850
# I considered excluding non-http url's here, thus forcing
851
# 'public' branches only, but that only works for some
852
# users, so it's best to just depend on the user spotting an
853
# error by the feedback given to them. RBC 20080227.
854
stacked_on = parent_url
856
raise errors.BzrCommandError(
857
"Could not determine branch to refer to.")
859
# Get the destination location
861
stored_loc = br_from.get_push_location()
862
if stored_loc is None:
863
raise errors.BzrCommandError(
864
"No push location known or specified.")
866
display_url = urlutils.unescape_for_display(stored_loc,
868
self.outf.write("Using saved push location: %s\n" % display_url)
869
location = stored_loc
871
_show_push_branch(br_from, revision_id, location, self.outf,
872
verbose=verbose, overwrite=overwrite, remember=remember,
873
stacked_on=stacked_on, create_prefix=create_prefix,
874
use_existing_dir=use_existing_dir)
877
class cmd_branch(Command):
878
"""Create a new copy of a branch.
880
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
881
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
882
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
883
is derived from the FROM_LOCATION by stripping a leading scheme or drive
884
identifier, if any. For example, "branch lp:foo-bar" will attempt to
887
To retrieve the branch as of a particular revision, supply the --revision
888
parameter, as in "branch foo/bar -r 5".
891
_see_also = ['checkout']
892
takes_args = ['from_location', 'to_location?']
893
takes_options = ['revision', Option('hardlink',
894
help='Hard-link working tree files where possible.'),
896
help='Create a stacked branch referring to the source branch. '
897
'The new branch will depend on the availability of the source '
898
'branch for all operations.'),
900
help='Do not use a shared repository, even if available.'),
902
aliases = ['get', 'clone']
904
def run(self, from_location, to_location=None, revision=None,
905
hardlink=False, stacked=False, standalone=False):
906
from bzrlib.tag import _merge_tags_if_possible
909
elif len(revision) > 1:
910
raise errors.BzrCommandError(
911
'bzr branch --revision takes exactly 1 revision value')
913
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
917
if len(revision) == 1 and revision[0] is not None:
918
revision_id = revision[0].as_revision_id(br_from)
920
# FIXME - wt.last_revision, fallback to branch, fall back to
921
# None or perhaps NULL_REVISION to mean copy nothing
923
revision_id = br_from.last_revision()
924
if to_location is None:
925
to_location = urlutils.derive_to_location(from_location)
926
to_transport = transport.get_transport(to_location)
928
to_transport.mkdir('.')
929
except errors.FileExists:
930
raise errors.BzrCommandError('Target directory "%s" already'
931
' exists.' % to_location)
932
except errors.NoSuchFile:
933
raise errors.BzrCommandError('Parent of "%s" does not exist.'
936
# preserve whatever source format we have.
937
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
938
possible_transports=[to_transport],
939
accelerator_tree=accelerator_tree,
940
hardlink=hardlink, stacked=stacked,
941
force_new_repo=standalone)
942
branch = dir.open_branch()
943
except errors.NoSuchRevision:
944
to_transport.delete_tree('.')
945
msg = "The branch %s has no revision %s." % (from_location,
947
raise errors.BzrCommandError(msg)
948
_merge_tags_if_possible(br_from, branch)
949
# If the source branch is stacked, the new branch may
950
# be stacked whether we asked for that explicitly or not.
951
# We therefore need a try/except here and not just 'if stacked:'
953
note('Created new stacked branch referring to %s.' %
954
branch.get_stacked_on_url())
955
except (errors.NotStacked, errors.UnstackableBranchFormat,
956
errors.UnstackableRepositoryFormat), e:
957
note('Branched %d revision(s).' % branch.revno())
962
class cmd_checkout(Command):
963
"""Create a new checkout of an existing branch.
965
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
966
the branch found in '.'. This is useful if you have removed the working tree
967
or if it was never created - i.e. if you pushed the branch to its current
970
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
971
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
972
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
973
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
974
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
977
To retrieve the branch as of a particular revision, supply the --revision
978
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
979
out of date [so you cannot commit] but it may be useful (i.e. to examine old
983
_see_also = ['checkouts', 'branch']
984
takes_args = ['branch_location?', 'to_location?']
985
takes_options = ['revision',
986
Option('lightweight',
987
help="Perform a lightweight checkout. Lightweight "
988
"checkouts depend on access to the branch for "
989
"every operation. Normal checkouts can perform "
990
"common operations like diff and status without "
991
"such access, and also support local commits."
993
Option('files-from', type=str,
994
help="Get file contents from this tree."),
996
help='Hard-link working tree files where possible.'
1001
def run(self, branch_location=None, to_location=None, revision=None,
1002
lightweight=False, files_from=None, hardlink=False):
1003
if revision is None:
1005
elif len(revision) > 1:
1006
raise errors.BzrCommandError(
1007
'bzr checkout --revision takes exactly 1 revision value')
1008
if branch_location is None:
1009
branch_location = osutils.getcwd()
1010
to_location = branch_location
1011
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1013
if files_from is not None:
1014
accelerator_tree = WorkingTree.open(files_from)
1015
if len(revision) == 1 and revision[0] is not None:
1016
revision_id = revision[0].as_revision_id(source)
1019
if to_location is None:
1020
to_location = urlutils.derive_to_location(branch_location)
1021
# if the source and to_location are the same,
1022
# and there is no working tree,
1023
# then reconstitute a branch
1024
if (osutils.abspath(to_location) ==
1025
osutils.abspath(branch_location)):
1027
source.bzrdir.open_workingtree()
1028
except errors.NoWorkingTree:
1029
source.bzrdir.create_workingtree(revision_id)
1031
source.create_checkout(to_location, revision_id, lightweight,
1032
accelerator_tree, hardlink)
1035
class cmd_renames(Command):
1036
"""Show list of renamed files.
1038
# TODO: Option to show renames between two historical versions.
1040
# TODO: Only show renames under dir, rather than in the whole branch.
1041
_see_also = ['status']
1042
takes_args = ['dir?']
1045
def run(self, dir=u'.'):
1046
tree = WorkingTree.open_containing(dir)[0]
1049
new_inv = tree.inventory
1050
old_tree = tree.basis_tree()
1051
old_tree.lock_read()
1053
old_inv = old_tree.inventory
1054
renames = list(_mod_tree.find_renames(old_inv, new_inv))
1056
for old_name, new_name in renames:
1057
self.outf.write("%s => %s\n" % (old_name, new_name))
1064
class cmd_update(Command):
1065
"""Update a tree to have the latest code committed to its branch.
1067
This will perform a merge into the working tree, and may generate
1068
conflicts. If you have any local changes, you will still
1069
need to commit them after the update for the update to be complete.
1071
If you want to discard your local changes, you can just do a
1072
'bzr revert' instead of 'bzr commit' after the update.
1075
_see_also = ['pull', 'working-trees', 'status-flags']
1076
takes_args = ['dir?']
1079
def run(self, dir='.'):
1080
tree = WorkingTree.open_containing(dir)[0]
1081
possible_transports = []
1082
master = tree.branch.get_master_branch(
1083
possible_transports=possible_transports)
1084
if master is not None:
1087
tree.lock_tree_write()
1089
existing_pending_merges = tree.get_parent_ids()[1:]
1090
last_rev = _mod_revision.ensure_null(tree.last_revision())
1091
if last_rev == _mod_revision.ensure_null(
1092
tree.branch.last_revision()):
1093
# may be up to date, check master too.
1094
if master is None or last_rev == _mod_revision.ensure_null(
1095
master.last_revision()):
1096
revno = tree.branch.revision_id_to_revno(last_rev)
1097
note("Tree is up to date at revision %d." % (revno,))
1099
conflicts = tree.update(
1100
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1101
possible_transports=possible_transports)
1102
revno = tree.branch.revision_id_to_revno(
1103
_mod_revision.ensure_null(tree.last_revision()))
1104
note('Updated to revision %d.' % (revno,))
1105
if tree.get_parent_ids()[1:] != existing_pending_merges:
1106
note('Your local commits will now show as pending merges with '
1107
"'bzr status', and can be committed with 'bzr commit'.")
1116
class cmd_info(Command):
1117
"""Show information about a working tree, branch or repository.
1119
This command will show all known locations and formats associated to the
1120
tree, branch or repository. Statistical information is included with
1123
Branches and working trees will also report any missing revisions.
1125
_see_also = ['revno', 'working-trees', 'repositories']
1126
takes_args = ['location?']
1127
takes_options = ['verbose']
1128
encoding_type = 'replace'
1131
def run(self, location=None, verbose=False):
1136
from bzrlib.info import show_bzrdir_info
1137
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1138
verbose=noise_level, outfile=self.outf)
1141
class cmd_remove(Command):
1142
"""Remove files or directories.
1144
This makes bzr stop tracking changes to the specified files. bzr will delete
1145
them if they can easily be recovered using revert. If no options or
1146
parameters are given bzr will scan for files that are being tracked by bzr
1147
but missing in your tree and stop tracking them for you.
1149
takes_args = ['file*']
1150
takes_options = ['verbose',
1151
Option('new', help='Only remove files that have never been committed.'),
1152
RegistryOption.from_kwargs('file-deletion-strategy',
1153
'The file deletion mode to be used.',
1154
title='Deletion Strategy', value_switches=True, enum_switch=False,
1155
safe='Only delete files if they can be'
1156
' safely recovered (default).',
1157
keep="Don't delete any files.",
1158
force='Delete all the specified files, even if they can not be '
1159
'recovered and even if they are non-empty directories.')]
1160
aliases = ['rm', 'del']
1161
encoding_type = 'replace'
1163
def run(self, file_list, verbose=False, new=False,
1164
file_deletion_strategy='safe'):
1165
tree, file_list = tree_files(file_list)
1167
if file_list is not None:
1168
file_list = [f for f in file_list]
1172
# Heuristics should probably all move into tree.remove_smart or
1175
added = tree.changes_from(tree.basis_tree(),
1176
specific_files=file_list).added
1177
file_list = sorted([f[0] for f in added], reverse=True)
1178
if len(file_list) == 0:
1179
raise errors.BzrCommandError('No matching files.')
1180
elif file_list is None:
1181
# missing files show up in iter_changes(basis) as
1182
# versioned-with-no-kind.
1184
for change in tree.iter_changes(tree.basis_tree()):
1185
# Find paths in the working tree that have no kind:
1186
if change[1][1] is not None and change[6][1] is None:
1187
missing.append(change[1][1])
1188
file_list = sorted(missing, reverse=True)
1189
file_deletion_strategy = 'keep'
1190
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1191
keep_files=file_deletion_strategy=='keep',
1192
force=file_deletion_strategy=='force')
1197
class cmd_file_id(Command):
1198
"""Print file_id of a particular file or directory.
1200
The file_id is assigned when the file is first added and remains the
1201
same through all revisions where the file exists, even when it is
1206
_see_also = ['inventory', 'ls']
1207
takes_args = ['filename']
1210
def run(self, filename):
1211
tree, relpath = WorkingTree.open_containing(filename)
1212
i = tree.path2id(relpath)
1214
raise errors.NotVersionedError(filename)
1216
self.outf.write(i + '\n')
1219
class cmd_file_path(Command):
1220
"""Print path of file_ids to a file or directory.
1222
This prints one line for each directory down to the target,
1223
starting at the branch root.
1227
takes_args = ['filename']
1230
def run(self, filename):
1231
tree, relpath = WorkingTree.open_containing(filename)
1232
fid = tree.path2id(relpath)
1234
raise errors.NotVersionedError(filename)
1235
segments = osutils.splitpath(relpath)
1236
for pos in range(1, len(segments) + 1):
1237
path = osutils.joinpath(segments[:pos])
1238
self.outf.write("%s\n" % tree.path2id(path))
1241
class cmd_reconcile(Command):
1242
"""Reconcile bzr metadata in a branch.
1244
This can correct data mismatches that may have been caused by
1245
previous ghost operations or bzr upgrades. You should only
1246
need to run this command if 'bzr check' or a bzr developer
1247
advises you to run it.
1249
If a second branch is provided, cross-branch reconciliation is
1250
also attempted, which will check that data like the tree root
1251
id which was not present in very early bzr versions is represented
1252
correctly in both branches.
1254
At the same time it is run it may recompress data resulting in
1255
a potential saving in disk space or performance gain.
1257
The branch *MUST* be on a listable system such as local disk or sftp.
1260
_see_also = ['check']
1261
takes_args = ['branch?']
1263
def run(self, branch="."):
1264
from bzrlib.reconcile import reconcile
1265
dir = bzrdir.BzrDir.open(branch)
1269
class cmd_revision_history(Command):
1270
"""Display the list of revision ids on a branch."""
1273
takes_args = ['location?']
1278
def run(self, location="."):
1279
branch = Branch.open_containing(location)[0]
1280
for revid in branch.revision_history():
1281
self.outf.write(revid)
1282
self.outf.write('\n')
1285
class cmd_ancestry(Command):
1286
"""List all revisions merged into this branch."""
1288
_see_also = ['log', 'revision-history']
1289
takes_args = ['location?']
1294
def run(self, location="."):
1296
wt = WorkingTree.open_containing(location)[0]
1297
except errors.NoWorkingTree:
1298
b = Branch.open(location)
1299
last_revision = b.last_revision()
1302
last_revision = wt.last_revision()
1304
revision_ids = b.repository.get_ancestry(last_revision)
1306
for revision_id in revision_ids:
1307
self.outf.write(revision_id + '\n')
1310
class cmd_init(Command):
1311
"""Make a directory into a versioned branch.
1313
Use this to create an empty branch, or before importing an
1316
If there is a repository in a parent directory of the location, then
1317
the history of the branch will be stored in the repository. Otherwise
1318
init creates a standalone branch which carries its own history
1319
in the .bzr directory.
1321
If there is already a branch at the location but it has no working tree,
1322
the tree can be populated with 'bzr checkout'.
1324
Recipe for importing a tree of files::
1330
bzr commit -m "imported project"
1333
_see_also = ['init-repository', 'branch', 'checkout']
1334
takes_args = ['location?']
1336
Option('create-prefix',
1337
help='Create the path leading up to the branch '
1338
'if it does not already exist.'),
1339
RegistryOption('format',
1340
help='Specify a format for this branch. '
1341
'See "help formats".',
1342
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1343
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1344
value_switches=True,
1345
title="Branch Format",
1347
Option('append-revisions-only',
1348
help='Never change revnos or the existing log.'
1349
' Append revisions to it only.')
1351
def run(self, location=None, format=None, append_revisions_only=False,
1352
create_prefix=False):
1354
format = bzrdir.format_registry.make_bzrdir('default')
1355
if location is None:
1358
to_transport = transport.get_transport(location)
1360
# The path has to exist to initialize a
1361
# branch inside of it.
1362
# Just using os.mkdir, since I don't
1363
# believe that we want to create a bunch of
1364
# locations if the user supplies an extended path
1366
to_transport.ensure_base()
1367
except errors.NoSuchFile:
1368
if not create_prefix:
1369
raise errors.BzrCommandError("Parent directory of %s"
1371
"\nYou may supply --create-prefix to create all"
1372
" leading parent directories."
1374
_create_prefix(to_transport)
1377
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1378
except errors.NotBranchError:
1379
# really a NotBzrDir error...
1380
create_branch = bzrdir.BzrDir.create_branch_convenience
1381
branch = create_branch(to_transport.base, format=format,
1382
possible_transports=[to_transport])
1383
a_bzrdir = branch.bzrdir
1385
from bzrlib.transport.local import LocalTransport
1386
if a_bzrdir.has_branch():
1387
if (isinstance(to_transport, LocalTransport)
1388
and not a_bzrdir.has_workingtree()):
1389
raise errors.BranchExistsWithoutWorkingTree(location)
1390
raise errors.AlreadyBranchError(location)
1391
branch = a_bzrdir.create_branch()
1392
a_bzrdir.create_workingtree()
1393
if append_revisions_only:
1395
branch.set_append_revisions_only(True)
1396
except errors.UpgradeRequired:
1397
raise errors.BzrCommandError('This branch format cannot be set'
1398
' to append-revisions-only. Try --experimental-branch6')
1400
from bzrlib.info import show_bzrdir_info
1401
show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1404
class cmd_init_repository(Command):
1405
"""Create a shared repository to hold branches.
1407
New branches created under the repository directory will store their
1408
revisions in the repository, not in the branch directory.
1410
If the --no-trees option is used then the branches in the repository
1411
will not have working trees by default.
1414
Create a shared repositories holding just branches::
1416
bzr init-repo --no-trees repo
1419
Make a lightweight checkout elsewhere::
1421
bzr checkout --lightweight repo/trunk trunk-checkout
1426
_see_also = ['init', 'branch', 'checkout', 'repositories']
1427
takes_args = ["location"]
1428
takes_options = [RegistryOption('format',
1429
help='Specify a format for this repository. See'
1430
' "bzr help formats" for details.',
1431
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1432
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1433
value_switches=True, title='Repository format'),
1435
help='Branches in the repository will default to'
1436
' not having a working tree.'),
1438
aliases = ["init-repo"]
1440
def run(self, location, format=None, no_trees=False):
1442
format = bzrdir.format_registry.make_bzrdir('default')
1444
if location is None:
1447
to_transport = transport.get_transport(location)
1448
to_transport.ensure_base()
1450
newdir = format.initialize_on_transport(to_transport)
1451
repo = newdir.create_repository(shared=True)
1452
repo.set_make_working_trees(not no_trees)
1454
from bzrlib.info import show_bzrdir_info
1455
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1458
class cmd_diff(Command):
1459
"""Show differences in the working tree, between revisions or branches.
1461
If no arguments are given, all changes for the current tree are listed.
1462
If files are given, only the changes in those files are listed.
1463
Remote and multiple branches can be compared by using the --old and
1464
--new options. If not provided, the default for both is derived from
1465
the first argument, if any, or the current tree if no arguments are
1468
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1469
produces patches suitable for "patch -p1".
1473
2 - unrepresentable changes
1478
Shows the difference in the working tree versus the last commit::
1482
Difference between the working tree and revision 1::
1486
Difference between revision 2 and revision 1::
1490
Difference between revision 2 and revision 1 for branch xxx::
1494
Show just the differences for file NEWS::
1498
Show the differences in working tree xxx for file NEWS::
1502
Show the differences from branch xxx to this working tree:
1506
Show the differences between two branches for file NEWS::
1508
bzr diff --old xxx --new yyy NEWS
1510
Same as 'bzr diff' but prefix paths with old/ and new/::
1512
bzr diff --prefix old/:new/
1514
_see_also = ['status']
1515
takes_args = ['file*']
1517
Option('diff-options', type=str,
1518
help='Pass these options to the external diff program.'),
1519
Option('prefix', type=str,
1521
help='Set prefixes added to old and new filenames, as '
1522
'two values separated by a colon. (eg "old/:new/").'),
1524
help='Branch/tree to compare from.',
1528
help='Branch/tree to compare to.',
1534
help='Use this command to compare files.',
1538
aliases = ['di', 'dif']
1539
encoding_type = 'exact'
1542
def run(self, revision=None, file_list=None, diff_options=None,
1543
prefix=None, old=None, new=None, using=None):
1544
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1546
if (prefix is None) or (prefix == '0'):
1554
old_label, new_label = prefix.split(":")
1556
raise errors.BzrCommandError(
1557
'--prefix expects two values separated by a colon'
1558
' (eg "old/:new/")')
1560
if revision and len(revision) > 2:
1561
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1562
' one or two revision specifiers')
1564
old_tree, new_tree, specific_files, extra_trees = \
1565
_get_trees_to_diff(file_list, revision, old, new)
1566
return show_diff_trees(old_tree, new_tree, sys.stdout,
1567
specific_files=specific_files,
1568
external_diff_options=diff_options,
1569
old_label=old_label, new_label=new_label,
1570
extra_trees=extra_trees, using=using)
1573
class cmd_deleted(Command):
1574
"""List files deleted in the working tree.
1576
# TODO: Show files deleted since a previous revision, or
1577
# between two revisions.
1578
# TODO: Much more efficient way to do this: read in new
1579
# directories with readdir, rather than stating each one. Same
1580
# level of effort but possibly much less IO. (Or possibly not,
1581
# if the directories are very large...)
1582
_see_also = ['status', 'ls']
1583
takes_options = ['show-ids']
1586
def run(self, show_ids=False):
1587
tree = WorkingTree.open_containing(u'.')[0]
1590
old = tree.basis_tree()
1593
for path, ie in old.inventory.iter_entries():
1594
if not tree.has_id(ie.file_id):
1595
self.outf.write(path)
1597
self.outf.write(' ')
1598
self.outf.write(ie.file_id)
1599
self.outf.write('\n')
1606
class cmd_modified(Command):
1607
"""List files modified in working tree.
1611
_see_also = ['status', 'ls']
1614
help='Write an ascii NUL (\\0) separator '
1615
'between files rather than a newline.')
1619
def run(self, null=False):
1620
tree = WorkingTree.open_containing(u'.')[0]
1621
td = tree.changes_from(tree.basis_tree())
1622
for path, id, kind, text_modified, meta_modified in td.modified:
1624
self.outf.write(path + '\0')
1626
self.outf.write(osutils.quotefn(path) + '\n')
1629
class cmd_added(Command):
1630
"""List files added in working tree.
1634
_see_also = ['status', 'ls']
1637
help='Write an ascii NUL (\\0) separator '
1638
'between files rather than a newline.')
1642
def run(self, null=False):
1643
wt = WorkingTree.open_containing(u'.')[0]
1646
basis = wt.basis_tree()
1649
basis_inv = basis.inventory
1652
if file_id in basis_inv:
1654
if inv.is_root(file_id) and len(basis_inv) == 0:
1656
path = inv.id2path(file_id)
1657
if not os.access(osutils.abspath(path), os.F_OK):
1660
self.outf.write(path + '\0')
1662
self.outf.write(osutils.quotefn(path) + '\n')
1669
class cmd_root(Command):
1670
"""Show the tree root directory.
1672
The root is the nearest enclosing directory with a .bzr control
1675
takes_args = ['filename?']
1677
def run(self, filename=None):
1678
"""Print the branch root."""
1679
tree = WorkingTree.open_containing(filename)[0]
1680
self.outf.write(tree.basedir + '\n')
1683
def _parse_limit(limitstring):
1685
return int(limitstring)
1687
msg = "The limit argument must be an integer."
1688
raise errors.BzrCommandError(msg)
1691
class cmd_log(Command):
1692
"""Show log of a branch, file, or directory.
1694
By default show the log of the branch containing the working directory.
1696
To request a range of logs, you can use the command -r begin..end
1697
-r revision requests a specific revision, -r ..end or -r begin.. are
1701
Log the current branch::
1709
Log the last 10 revisions of a branch::
1711
bzr log -r -10.. http://server/branch
1714
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1716
takes_args = ['location?']
1719
help='Show from oldest to newest.'),
1721
custom_help('verbose',
1722
help='Show files changed in each revision.'),
1726
type=bzrlib.option._parse_revision_str,
1728
help='Show just the specified revision.'
1729
' See also "help revisionspec".'),
1733
help='Show revisions whose message matches this '
1734
'regular expression.',
1738
help='Limit the output to the first N revisions.',
1742
encoding_type = 'replace'
1745
def run(self, location=None, timezone='original',
1754
from bzrlib.log import show_log
1755
direction = (forward and 'forward') or 'reverse'
1757
if change is not None:
1759
raise errors.RangeInChangeOption()
1760
if revision is not None:
1761
raise errors.BzrCommandError(
1762
'--revision and --change are mutually exclusive')
1769
# find the file id to log:
1771
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1775
tree = b.basis_tree()
1776
file_id = tree.path2id(fp)
1778
raise errors.BzrCommandError(
1779
"Path does not have any revision history: %s" %
1783
# FIXME ? log the current subdir only RBC 20060203
1784
if revision is not None \
1785
and len(revision) > 0 and revision[0].get_branch():
1786
location = revision[0].get_branch()
1789
dir, relpath = bzrdir.BzrDir.open_containing(location)
1790
b = dir.open_branch()
1794
if revision is None:
1797
elif len(revision) == 1:
1798
rev1 = rev2 = revision[0].in_history(b)
1799
elif len(revision) == 2:
1800
if revision[1].get_branch() != revision[0].get_branch():
1801
# b is taken from revision[0].get_branch(), and
1802
# show_log will use its revision_history. Having
1803
# different branches will lead to weird behaviors.
1804
raise errors.BzrCommandError(
1805
"Log doesn't accept two revisions in different"
1807
rev1 = revision[0].in_history(b)
1808
rev2 = revision[1].in_history(b)
1810
raise errors.BzrCommandError(
1811
'bzr log --revision takes one or two values.')
1813
if log_format is None:
1814
log_format = log.log_formatter_registry.get_default(b)
1816
lf = log_format(show_ids=show_ids, to_file=self.outf,
1817
show_timezone=timezone)
1823
direction=direction,
1824
start_revision=rev1,
1832
def get_log_format(long=False, short=False, line=False, default='long'):
1833
log_format = default
1837
log_format = 'short'
1843
class cmd_touching_revisions(Command):
1844
"""Return revision-ids which affected a particular file.
1846
A more user-friendly interface is "bzr log FILE".
1850
takes_args = ["filename"]
1853
def run(self, filename):
1854
tree, relpath = WorkingTree.open_containing(filename)
1856
file_id = tree.path2id(relpath)
1857
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1858
self.outf.write("%6d %s\n" % (revno, what))
1861
class cmd_ls(Command):
1862
"""List files in a tree.
1865
_see_also = ['status', 'cat']
1866
takes_args = ['path?']
1867
# TODO: Take a revision or remote path and list that tree instead.
1871
Option('non-recursive',
1872
help='Don\'t recurse into subdirectories.'),
1874
help='Print paths relative to the root of the branch.'),
1875
Option('unknown', help='Print unknown files.'),
1876
Option('versioned', help='Print versioned files.',
1878
Option('ignored', help='Print ignored files.'),
1880
help='Write an ascii NUL (\\0) separator '
1881
'between files rather than a newline.'),
1883
help='List entries of a particular kind: file, directory, symlink.',
1888
def run(self, revision=None, verbose=False,
1889
non_recursive=False, from_root=False,
1890
unknown=False, versioned=False, ignored=False,
1891
null=False, kind=None, show_ids=False, path=None):
1893
if kind and kind not in ('file', 'directory', 'symlink'):
1894
raise errors.BzrCommandError('invalid kind specified')
1896
if verbose and null:
1897
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1898
all = not (unknown or versioned or ignored)
1900
selection = {'I':ignored, '?':unknown, 'V':versioned}
1907
raise errors.BzrCommandError('cannot specify both --from-root'
1911
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1917
if revision is not None or tree is None:
1918
tree = _get_one_revision_tree('ls', revision, branch=branch)
1922
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1923
if fp.startswith(relpath):
1924
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1925
if non_recursive and '/' in fp:
1927
if not all and not selection[fc]:
1929
if kind is not None and fkind != kind:
1932
kindch = entry.kind_character()
1933
outstring = '%-8s %s%s' % (fc, fp, kindch)
1934
if show_ids and fid is not None:
1935
outstring = "%-50s %s" % (outstring, fid)
1936
self.outf.write(outstring + '\n')
1938
self.outf.write(fp + '\0')
1941
self.outf.write(fid)
1942
self.outf.write('\0')
1950
self.outf.write('%-50s %s\n' % (fp, my_id))
1952
self.outf.write(fp + '\n')
1957
class cmd_unknowns(Command):
1958
"""List unknown files.
1966
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1967
self.outf.write(osutils.quotefn(f) + '\n')
1970
class cmd_ignore(Command):
1971
"""Ignore specified files or patterns.
1973
See ``bzr help patterns`` for details on the syntax of patterns.
1975
To remove patterns from the ignore list, edit the .bzrignore file.
1976
After adding, editing or deleting that file either indirectly by
1977
using this command or directly by using an editor, be sure to commit
1980
Note: ignore patterns containing shell wildcards must be quoted from
1984
Ignore the top level Makefile::
1986
bzr ignore ./Makefile
1988
Ignore class files in all directories::
1990
bzr ignore "*.class"
1992
Ignore .o files under the lib directory::
1994
bzr ignore "lib/**/*.o"
1996
Ignore .o files under the lib directory::
1998
bzr ignore "RE:lib/.*\.o"
2000
Ignore everything but the "debian" toplevel directory::
2002
bzr ignore "RE:(?!debian/).*"
2005
_see_also = ['status', 'ignored', 'patterns']
2006
takes_args = ['name_pattern*']
2008
Option('old-default-rules',
2009
help='Write out the ignore rules bzr < 0.9 always used.')
2012
def run(self, name_pattern_list=None, old_default_rules=None):
2013
from bzrlib import ignores
2014
if old_default_rules is not None:
2015
# dump the rules and exit
2016
for pattern in ignores.OLD_DEFAULTS:
2019
if not name_pattern_list:
2020
raise errors.BzrCommandError("ignore requires at least one "
2021
"NAME_PATTERN or --old-default-rules")
2022
name_pattern_list = [globbing.normalize_pattern(p)
2023
for p in name_pattern_list]
2024
for name_pattern in name_pattern_list:
2025
if (name_pattern[0] == '/' or
2026
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2027
raise errors.BzrCommandError(
2028
"NAME_PATTERN should not be an absolute path")
2029
tree, relpath = WorkingTree.open_containing(u'.')
2030
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2031
ignored = globbing.Globster(name_pattern_list)
2034
for entry in tree.list_files():
2038
if ignored.match(filename):
2039
matches.append(filename.encode('utf-8'))
2041
if len(matches) > 0:
2042
print "Warning: the following files are version controlled and" \
2043
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2046
class cmd_ignored(Command):
2047
"""List ignored files and the patterns that matched them.
2049
List all the ignored files and the ignore pattern that caused the file to
2052
Alternatively, to list just the files::
2057
encoding_type = 'replace'
2058
_see_also = ['ignore', 'ls']
2062
tree = WorkingTree.open_containing(u'.')[0]
2065
for path, file_class, kind, file_id, entry in tree.list_files():
2066
if file_class != 'I':
2068
## XXX: Slightly inefficient since this was already calculated
2069
pat = tree.is_ignored(path)
2070
self.outf.write('%-50s %s\n' % (path, pat))
2075
class cmd_lookup_revision(Command):
2076
"""Lookup the revision-id from a revision-number
2079
bzr lookup-revision 33
2082
takes_args = ['revno']
2085
def run(self, revno):
2089
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2091
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2094
class cmd_export(Command):
2095
"""Export current or past revision to a destination directory or archive.
2097
If no revision is specified this exports the last committed revision.
2099
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2100
given, try to find the format with the extension. If no extension
2101
is found exports to a directory (equivalent to --format=dir).
2103
If root is supplied, it will be used as the root directory inside
2104
container formats (tar, zip, etc). If it is not supplied it will default
2105
to the exported filename. The root option has no effect for 'dir' format.
2107
If branch is omitted then the branch containing the current working
2108
directory will be used.
2110
Note: Export of tree with non-ASCII filenames to zip is not supported.
2112
================= =========================
2113
Supported formats Autodetected by extension
2114
================= =========================
2117
tbz2 .tar.bz2, .tbz2
2120
================= =========================
2122
takes_args = ['dest', 'branch_or_subdir?']
2125
help="Type of file to export to.",
2130
help="Name of the root directory inside the exported file."),
2132
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2134
from bzrlib.export import export
2136
if branch_or_subdir is None:
2137
tree = WorkingTree.open_containing(u'.')[0]
2141
b, subdir = Branch.open_containing(branch_or_subdir)
2144
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2146
export(rev_tree, dest, format, root, subdir)
2147
except errors.NoSuchExportFormat, e:
2148
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2151
class cmd_cat(Command):
2152
"""Write the contents of a file as of a given revision to standard output.
2154
If no revision is nominated, the last revision is used.
2156
Note: Take care to redirect standard output when using this command on a
2162
Option('name-from-revision', help='The path name in the old tree.'),
2165
takes_args = ['filename']
2166
encoding_type = 'exact'
2169
def run(self, filename, revision=None, name_from_revision=False):
2170
if revision is not None and len(revision) != 1:
2171
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2172
" one revision specifier")
2173
tree, branch, relpath = \
2174
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2177
return self._run(tree, branch, relpath, filename, revision,
2182
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2184
tree = b.basis_tree()
2185
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2187
cur_file_id = tree.path2id(relpath)
2188
old_file_id = rev_tree.path2id(relpath)
2190
if name_from_revision:
2191
if old_file_id is None:
2192
raise errors.BzrCommandError(
2193
"%r is not present in revision %s" % (
2194
filename, rev_tree.get_revision_id()))
2196
content = rev_tree.get_file_text(old_file_id)
2197
elif cur_file_id is not None:
2198
content = rev_tree.get_file_text(cur_file_id)
2199
elif old_file_id is not None:
2200
content = rev_tree.get_file_text(old_file_id)
2202
raise errors.BzrCommandError(
2203
"%r is not present in revision %s" % (
2204
filename, rev_tree.get_revision_id()))
2205
self.outf.write(content)
2208
class cmd_local_time_offset(Command):
2209
"""Show the offset in seconds from GMT to local time."""
2213
print osutils.local_time_offset()
2217
class cmd_commit(Command):
2218
"""Commit changes into a new revision.
2220
If no arguments are given, the entire tree is committed.
2222
If selected files are specified, only changes to those files are
2223
committed. If a directory is specified then the directory and everything
2224
within it is committed.
2226
When excludes are given, they take precedence over selected files.
2227
For example, too commit only changes within foo, but not changes within
2230
bzr commit foo -x foo/bar
2232
If author of the change is not the same person as the committer, you can
2233
specify the author's name using the --author option. The name should be
2234
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2236
A selected-file commit may fail in some cases where the committed
2237
tree would be invalid. Consider::
2242
bzr commit foo -m "committing foo"
2243
bzr mv foo/bar foo/baz
2246
bzr commit foo/bar -m "committing bar but not baz"
2248
In the example above, the last commit will fail by design. This gives
2249
the user the opportunity to decide whether they want to commit the
2250
rename at the same time, separately first, or not at all. (As a general
2251
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2253
Note: A selected-file commit after a merge is not yet supported.
2255
# TODO: Run hooks on tree to-be-committed, and after commit.
2257
# TODO: Strict commit that fails if there are deleted files.
2258
# (what does "deleted files" mean ??)
2260
# TODO: Give better message for -s, --summary, used by tla people
2262
# XXX: verbose currently does nothing
2264
_see_also = ['bugs', 'uncommit']
2265
takes_args = ['selected*']
2267
ListOption('exclude', type=str, short_name='x',
2268
help="Do not consider changes made to a given path."),
2269
Option('message', type=unicode,
2271
help="Description of the new revision."),
2274
help='Commit even if nothing has changed.'),
2275
Option('file', type=str,
2278
help='Take commit message from this file.'),
2280
help="Refuse to commit if there are unknown "
2281
"files in the working tree."),
2282
ListOption('fixes', type=str,
2283
help="Mark a bug as being fixed by this revision."),
2284
Option('author', type=unicode,
2285
help="Set the author's name, if it's different "
2286
"from the committer."),
2288
help="Perform a local commit in a bound "
2289
"branch. Local commits are not pushed to "
2290
"the master branch until a normal commit "
2294
help='When no message is supplied, show the diff along'
2295
' with the status summary in the message editor.'),
2297
aliases = ['ci', 'checkin']
2299
def _get_bug_fix_properties(self, fixes, branch):
2301
# Configure the properties for bug fixing attributes.
2302
for fixed_bug in fixes:
2303
tokens = fixed_bug.split(':')
2304
if len(tokens) != 2:
2305
raise errors.BzrCommandError(
2306
"Invalid bug %s. Must be in the form of 'tag:id'. "
2307
"Commit refused." % fixed_bug)
2308
tag, bug_id = tokens
2310
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2311
except errors.UnknownBugTrackerAbbreviation:
2312
raise errors.BzrCommandError(
2313
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2314
except errors.MalformedBugIdentifier:
2315
raise errors.BzrCommandError(
2316
"Invalid bug identifier for %s. Commit refused."
2318
properties.append('%s fixed' % bug_url)
2319
return '\n'.join(properties)
2321
def run(self, message=None, file=None, verbose=False, selected_list=None,
2322
unchanged=False, strict=False, local=False, fixes=None,
2323
author=None, show_diff=False, exclude=None):
2324
from bzrlib.errors import (
2329
from bzrlib.msgeditor import (
2330
edit_commit_message_encoded,
2331
make_commit_message_template_encoded
2334
# TODO: Need a blackbox test for invoking the external editor; may be
2335
# slightly problematic to run this cross-platform.
2337
# TODO: do more checks that the commit will succeed before
2338
# spending the user's valuable time typing a commit message.
2342
tree, selected_list = tree_files(selected_list)
2343
if selected_list == ['']:
2344
# workaround - commit of root of tree should be exactly the same
2345
# as just default commit in that tree, and succeed even though
2346
# selected-file merge commit is not done yet
2351
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2353
properties['bugs'] = bug_property
2355
if local and not tree.branch.get_bound_location():
2356
raise errors.LocalRequiresBoundBranch()
2358
def get_message(commit_obj):
2359
"""Callback to get commit message"""
2360
my_message = message
2361
if my_message is None and not file:
2362
t = make_commit_message_template_encoded(tree,
2363
selected_list, diff=show_diff,
2364
output_encoding=osutils.get_user_encoding())
2365
my_message = edit_commit_message_encoded(t)
2366
if my_message is None:
2367
raise errors.BzrCommandError("please specify a commit"
2368
" message with either --message or --file")
2369
elif my_message and file:
2370
raise errors.BzrCommandError(
2371
"please specify either --message or --file")
2373
my_message = codecs.open(file, 'rt',
2374
osutils.get_user_encoding()).read()
2375
if my_message == "":
2376
raise errors.BzrCommandError("empty commit message specified")
2380
tree.commit(message_callback=get_message,
2381
specific_files=selected_list,
2382
allow_pointless=unchanged, strict=strict, local=local,
2383
reporter=None, verbose=verbose, revprops=properties,
2385
exclude=safe_relpath_files(tree, exclude))
2386
except PointlessCommit:
2387
# FIXME: This should really happen before the file is read in;
2388
# perhaps prepare the commit; get the message; then actually commit
2389
raise errors.BzrCommandError("no changes to commit."
2390
" use --unchanged to commit anyhow")
2391
except ConflictsInTree:
2392
raise errors.BzrCommandError('Conflicts detected in working '
2393
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2395
except StrictCommitFailed:
2396
raise errors.BzrCommandError("Commit refused because there are"
2397
" unknown files in the working tree.")
2398
except errors.BoundBranchOutOfDate, e:
2399
raise errors.BzrCommandError(str(e) + "\n"
2400
'To commit to master branch, run update and then commit.\n'
2401
'You can also pass --local to commit to continue working '
2405
class cmd_check(Command):
2406
"""Validate working tree structure, branch consistency and repository history.
2408
This command checks various invariants about branch and repository storage
2409
to detect data corruption or bzr bugs.
2411
The working tree and branch checks will only give output if a problem is
2412
detected. The output fields of the repository check are:
2414
revisions: This is just the number of revisions checked. It doesn't
2416
versionedfiles: This is just the number of versionedfiles checked. It
2417
doesn't indicate a problem.
2418
unreferenced ancestors: Texts that are ancestors of other texts, but
2419
are not properly referenced by the revision ancestry. This is a
2420
subtle problem that Bazaar can work around.
2421
unique file texts: This is the total number of unique file contents
2422
seen in the checked revisions. It does not indicate a problem.
2423
repeated file texts: This is the total number of repeated texts seen
2424
in the checked revisions. Texts can be repeated when their file
2425
entries are modified, but the file contents are not. It does not
2428
If no restrictions are specified, all Bazaar data that is found at the given
2429
location will be checked.
2433
Check the tree and branch at 'foo'::
2435
bzr check --tree --branch foo
2437
Check only the repository at 'bar'::
2439
bzr check --repo bar
2441
Check everything at 'baz'::
2446
_see_also = ['reconcile']
2447
takes_args = ['path?']
2448
takes_options = ['verbose',
2449
Option('branch', help="Check the branch related to the"
2450
" current directory."),
2451
Option('repo', help="Check the repository related to the"
2452
" current directory."),
2453
Option('tree', help="Check the working tree related to"
2454
" the current directory.")]
2456
def run(self, path=None, verbose=False, branch=False, repo=False,
2458
from bzrlib.check import check_dwim
2461
if not branch and not repo and not tree:
2462
branch = repo = tree = True
2463
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2466
class cmd_upgrade(Command):
2467
"""Upgrade branch storage to current format.
2469
The check command or bzr developers may sometimes advise you to run
2470
this command. When the default format has changed you may also be warned
2471
during other operations to upgrade.
2474
_see_also = ['check']
2475
takes_args = ['url?']
2477
RegistryOption('format',
2478
help='Upgrade to a specific format. See "bzr help'
2479
' formats" for details.',
2480
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2481
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2482
value_switches=True, title='Branch format'),
2485
def run(self, url='.', format=None):
2486
from bzrlib.upgrade import upgrade
2488
format = bzrdir.format_registry.make_bzrdir('default')
2489
upgrade(url, format)
2492
class cmd_whoami(Command):
2493
"""Show or set bzr user id.
2496
Show the email of the current user::
2500
Set the current user::
2502
bzr whoami "Frank Chu <fchu@example.com>"
2504
takes_options = [ Option('email',
2505
help='Display email address only.'),
2507
help='Set identity for the current branch instead of '
2510
takes_args = ['name?']
2511
encoding_type = 'replace'
2514
def run(self, email=False, branch=False, name=None):
2516
# use branch if we're inside one; otherwise global config
2518
c = Branch.open_containing('.')[0].get_config()
2519
except errors.NotBranchError:
2520
c = config.GlobalConfig()
2522
self.outf.write(c.user_email() + '\n')
2524
self.outf.write(c.username() + '\n')
2527
# display a warning if an email address isn't included in the given name.
2529
config.extract_email_address(name)
2530
except errors.NoEmailInUsername, e:
2531
warning('"%s" does not seem to contain an email address. '
2532
'This is allowed, but not recommended.', name)
2534
# use global config unless --branch given
2536
c = Branch.open_containing('.')[0].get_config()
2538
c = config.GlobalConfig()
2539
c.set_user_option('email', name)
2542
class cmd_nick(Command):
2543
"""Print or set the branch nickname.
2545
If unset, the tree root directory name is used as the nickname
2546
To print the current nickname, execute with no argument.
2549
_see_also = ['info']
2550
takes_args = ['nickname?']
2551
def run(self, nickname=None):
2552
branch = Branch.open_containing(u'.')[0]
2553
if nickname is None:
2554
self.printme(branch)
2556
branch.nick = nickname
2559
def printme(self, branch):
2563
class cmd_alias(Command):
2564
"""Set/unset and display aliases.
2567
Show the current aliases::
2571
Show the alias specified for 'll'::
2575
Set an alias for 'll'::
2577
bzr alias ll="log --line -r-10..-1"
2579
To remove an alias for 'll'::
2581
bzr alias --remove ll
2584
takes_args = ['name?']
2586
Option('remove', help='Remove the alias.'),
2589
def run(self, name=None, remove=False):
2591
self.remove_alias(name)
2593
self.print_aliases()
2595
equal_pos = name.find('=')
2597
self.print_alias(name)
2599
self.set_alias(name[:equal_pos], name[equal_pos+1:])
2601
def remove_alias(self, alias_name):
2602
if alias_name is None:
2603
raise errors.BzrCommandError(
2604
'bzr alias --remove expects an alias to remove.')
2605
# If alias is not found, print something like:
2606
# unalias: foo: not found
2607
c = config.GlobalConfig()
2608
c.unset_alias(alias_name)
2611
def print_aliases(self):
2612
"""Print out the defined aliases in a similar format to bash."""
2613
aliases = config.GlobalConfig().get_aliases()
2614
for key, value in sorted(aliases.iteritems()):
2615
self.outf.write('bzr alias %s="%s"\n' % (key, value))
2618
def print_alias(self, alias_name):
2619
from bzrlib.commands import get_alias
2620
alias = get_alias(alias_name)
2622
self.outf.write("bzr alias: %s: not found\n" % alias_name)
2625
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2627
def set_alias(self, alias_name, alias_command):
2628
"""Save the alias in the global config."""
2629
c = config.GlobalConfig()
2630
c.set_alias(alias_name, alias_command)
2633
class cmd_selftest(Command):
2634
"""Run internal test suite.
2636
If arguments are given, they are regular expressions that say which tests
2637
should run. Tests matching any expression are run, and other tests are
2640
Alternatively if --first is given, matching tests are run first and then
2641
all other tests are run. This is useful if you have been working in a
2642
particular area, but want to make sure nothing else was broken.
2644
If --exclude is given, tests that match that regular expression are
2645
excluded, regardless of whether they match --first or not.
2647
To help catch accidential dependencies between tests, the --randomize
2648
option is useful. In most cases, the argument used is the word 'now'.
2649
Note that the seed used for the random number generator is displayed
2650
when this option is used. The seed can be explicitly passed as the
2651
argument to this option if required. This enables reproduction of the
2652
actual ordering used if and when an order sensitive problem is encountered.
2654
If --list-only is given, the tests that would be run are listed. This is
2655
useful when combined with --first, --exclude and/or --randomize to
2656
understand their impact. The test harness reports "Listed nn tests in ..."
2657
instead of "Ran nn tests in ..." when list mode is enabled.
2659
If the global option '--no-plugins' is given, plugins are not loaded
2660
before running the selftests. This has two effects: features provided or
2661
modified by plugins will not be tested, and tests provided by plugins will
2664
Tests that need working space on disk use a common temporary directory,
2665
typically inside $TMPDIR or /tmp.
2668
Run only tests relating to 'ignore'::
2672
Disable plugins and list tests as they're run::
2674
bzr --no-plugins selftest -v
2676
# NB: this is used from the class without creating an instance, which is
2677
# why it does not have a self parameter.
2678
def get_transport_type(typestring):
2679
"""Parse and return a transport specifier."""
2680
if typestring == "sftp":
2681
from bzrlib.transport.sftp import SFTPAbsoluteServer
2682
return SFTPAbsoluteServer
2683
if typestring == "memory":
2684
from bzrlib.transport.memory import MemoryServer
2686
if typestring == "fakenfs":
2687
from bzrlib.transport.fakenfs import FakeNFSServer
2688
return FakeNFSServer
2689
msg = "No known transport type %s. Supported types are: sftp\n" %\
2691
raise errors.BzrCommandError(msg)
2694
takes_args = ['testspecs*']
2695
takes_options = ['verbose',
2697
help='Stop when one test fails.',
2701
help='Use a different transport by default '
2702
'throughout the test suite.',
2703
type=get_transport_type),
2705
help='Run the benchmarks rather than selftests.'),
2706
Option('lsprof-timed',
2707
help='Generate lsprof output for benchmarked'
2708
' sections of code.'),
2709
Option('cache-dir', type=str,
2710
help='Cache intermediate benchmark output in this '
2713
help='Run all tests, but run specified tests first.',
2717
help='List the tests instead of running them.'),
2718
Option('randomize', type=str, argname="SEED",
2719
help='Randomize the order of tests using the given'
2720
' seed or "now" for the current time.'),
2721
Option('exclude', type=str, argname="PATTERN",
2723
help='Exclude tests that match this regular'
2725
Option('strict', help='Fail on missing dependencies or '
2727
Option('load-list', type=str, argname='TESTLISTFILE',
2728
help='Load a test id list from a text file.'),
2729
ListOption('debugflag', type=str, short_name='E',
2730
help='Turn on a selftest debug flag.'),
2731
ListOption('starting-with', type=str, argname='TESTID',
2732
param_name='starting_with', short_name='s',
2734
'Load only the tests starting with TESTID.'),
2736
encoding_type = 'replace'
2738
def run(self, testspecs_list=None, verbose=False, one=False,
2739
transport=None, benchmark=None,
2740
lsprof_timed=None, cache_dir=None,
2741
first=False, list_only=False,
2742
randomize=None, exclude=None, strict=False,
2743
load_list=None, debugflag=None, starting_with=None):
2744
from bzrlib.tests import selftest
2745
import bzrlib.benchmarks as benchmarks
2746
from bzrlib.benchmarks import tree_creator
2748
# Make deprecation warnings visible, unless -Werror is set
2749
symbol_versioning.activate_deprecation_warnings(override=False)
2751
if cache_dir is not None:
2752
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2754
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2755
print ' %s (%s python%s)' % (
2757
bzrlib.version_string,
2758
bzrlib._format_version_tuple(sys.version_info),
2761
if testspecs_list is not None:
2762
pattern = '|'.join(testspecs_list)
2766
test_suite_factory = benchmarks.test_suite
2767
# Unless user explicitly asks for quiet, be verbose in benchmarks
2768
verbose = not is_quiet()
2769
# TODO: should possibly lock the history file...
2770
benchfile = open(".perf_history", "at", buffering=1)
2772
test_suite_factory = None
2775
result = selftest(verbose=verbose,
2777
stop_on_failure=one,
2778
transport=transport,
2779
test_suite_factory=test_suite_factory,
2780
lsprof_timed=lsprof_timed,
2781
bench_history=benchfile,
2782
matching_tests_first=first,
2783
list_only=list_only,
2784
random_seed=randomize,
2785
exclude_pattern=exclude,
2787
load_list=load_list,
2788
debug_flags=debugflag,
2789
starting_with=starting_with,
2792
if benchfile is not None:
2795
note('tests passed')
2797
note('tests failed')
2798
return int(not result)
2801
class cmd_version(Command):
2802
"""Show version of bzr."""
2804
encoding_type = 'replace'
2806
Option("short", help="Print just the version number."),
2810
def run(self, short=False):
2811
from bzrlib.version import show_version
2813
self.outf.write(bzrlib.version_string + '\n')
2815
show_version(to_file=self.outf)
2818
class cmd_rocks(Command):
2819
"""Statement of optimism."""
2825
print "It sure does!"
2828
class cmd_find_merge_base(Command):
2829
"""Find and print a base revision for merging two branches."""
2830
# TODO: Options to specify revisions on either side, as if
2831
# merging only part of the history.
2832
takes_args = ['branch', 'other']
2836
def run(self, branch, other):
2837
from bzrlib.revision import ensure_null
2839
branch1 = Branch.open_containing(branch)[0]
2840
branch2 = Branch.open_containing(other)[0]
2845
last1 = ensure_null(branch1.last_revision())
2846
last2 = ensure_null(branch2.last_revision())
2848
graph = branch1.repository.get_graph(branch2.repository)
2849
base_rev_id = graph.find_unique_lca(last1, last2)
2851
print 'merge base is revision %s' % base_rev_id
2858
class cmd_merge(Command):
2859
"""Perform a three-way merge.
2861
The source of the merge can be specified either in the form of a branch,
2862
or in the form of a path to a file containing a merge directive generated
2863
with bzr send. If neither is specified, the default is the upstream branch
2864
or the branch most recently merged using --remember.
2866
When merging a branch, by default the tip will be merged. To pick a different
2867
revision, pass --revision. If you specify two values, the first will be used as
2868
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2869
available revisions, like this is commonly referred to as "cherrypicking".
2871
Revision numbers are always relative to the branch being merged.
2873
By default, bzr will try to merge in all new work from the other
2874
branch, automatically determining an appropriate base. If this
2875
fails, you may need to give an explicit base.
2877
Merge will do its best to combine the changes in two branches, but there
2878
are some kinds of problems only a human can fix. When it encounters those,
2879
it will mark a conflict. A conflict means that you need to fix something,
2880
before you should commit.
2882
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2884
If there is no default branch set, the first merge will set it. After
2885
that, you can omit the branch to use the default. To change the
2886
default, use --remember. The value will only be saved if the remote
2887
location can be accessed.
2889
The results of the merge are placed into the destination working
2890
directory, where they can be reviewed (with bzr diff), tested, and then
2891
committed to record the result of the merge.
2893
merge refuses to run if there are any uncommitted changes, unless
2897
To merge the latest revision from bzr.dev::
2899
bzr merge ../bzr.dev
2901
To merge changes up to and including revision 82 from bzr.dev::
2903
bzr merge -r 82 ../bzr.dev
2905
To merge the changes introduced by 82, without previous changes::
2907
bzr merge -r 81..82 ../bzr.dev
2909
To apply a merge directive contained in in /tmp/merge:
2911
bzr merge /tmp/merge
2914
encoding_type = 'exact'
2915
_see_also = ['update', 'remerge', 'status-flags']
2916
takes_args = ['location?']
2921
help='Merge even if the destination tree has uncommitted changes.'),
2925
Option('show-base', help="Show base revision text in "
2927
Option('uncommitted', help='Apply uncommitted changes'
2928
' from a working copy, instead of branch changes.'),
2929
Option('pull', help='If the destination is already'
2930
' completely merged into the source, pull from the'
2931
' source rather than merging. When this happens,'
2932
' you do not need to commit the result.'),
2934
help='Branch to merge into, '
2935
'rather than the one containing the working directory.',
2939
Option('preview', help='Instead of merging, show a diff of the merge.')
2942
def run(self, location=None, revision=None, force=False,
2943
merge_type=None, show_base=False, reprocess=None, remember=False,
2944
uncommitted=False, pull=False,
2948
if merge_type is None:
2949
merge_type = _mod_merge.Merge3Merger
2951
if directory is None: directory = u'.'
2952
possible_transports = []
2954
allow_pending = True
2955
verified = 'inapplicable'
2956
tree = WorkingTree.open_containing(directory)[0]
2957
change_reporter = delta._ChangeReporter(
2958
unversioned_filter=tree.is_ignored)
2961
pb = ui.ui_factory.nested_progress_bar()
2962
cleanups.append(pb.finished)
2964
cleanups.append(tree.unlock)
2965
if location is not None:
2967
mergeable = bundle.read_mergeable_from_url(location,
2968
possible_transports=possible_transports)
2969
except errors.NotABundle:
2973
raise errors.BzrCommandError('Cannot use --uncommitted'
2974
' with bundles or merge directives.')
2976
if revision is not None:
2977
raise errors.BzrCommandError(
2978
'Cannot use -r with merge directives or bundles')
2979
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2982
if merger is None and uncommitted:
2983
if revision is not None and len(revision) > 0:
2984
raise errors.BzrCommandError('Cannot use --uncommitted and'
2985
' --revision at the same time.')
2986
location = self._select_branch_location(tree, location)[0]
2987
other_tree, other_path = WorkingTree.open_containing(location)
2988
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2990
allow_pending = False
2991
if other_path != '':
2992
merger.interesting_files = [other_path]
2995
merger, allow_pending = self._get_merger_from_branch(tree,
2996
location, revision, remember, possible_transports, pb)
2998
merger.merge_type = merge_type
2999
merger.reprocess = reprocess
3000
merger.show_base = show_base
3001
self.sanity_check_merger(merger)
3002
if (merger.base_rev_id == merger.other_rev_id and
3003
merger.other_rev_id is not None):
3004
note('Nothing to do.')
3007
if merger.interesting_files is not None:
3008
raise errors.BzrCommandError('Cannot pull individual files')
3009
if (merger.base_rev_id == tree.last_revision()):
3010
result = tree.pull(merger.other_branch, False,
3011
merger.other_rev_id)
3012
result.report(self.outf)
3014
merger.check_basis(not force)
3016
return self._do_preview(merger)
3018
return self._do_merge(merger, change_reporter, allow_pending,
3021
for cleanup in reversed(cleanups):
3024
def _do_preview(self, merger):
3025
from bzrlib.diff import show_diff_trees
3026
tree_merger = merger.make_merger()
3027
tt = tree_merger.make_preview_transform()
3029
result_tree = tt.get_preview_tree()
3030
show_diff_trees(merger.this_tree, result_tree, self.outf,
3031
old_label='', new_label='')
3035
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3036
merger.change_reporter = change_reporter
3037
conflict_count = merger.do_merge()
3039
merger.set_pending()
3040
if verified == 'failed':
3041
warning('Preview patch does not match changes')
3042
if conflict_count != 0:
3047
def sanity_check_merger(self, merger):
3048
if (merger.show_base and
3049
not merger.merge_type is _mod_merge.Merge3Merger):
3050
raise errors.BzrCommandError("Show-base is not supported for this"
3051
" merge type. %s" % merger.merge_type)
3052
if merger.reprocess is None:
3053
if merger.show_base:
3054
merger.reprocess = False
3056
# Use reprocess if the merger supports it
3057
merger.reprocess = merger.merge_type.supports_reprocess
3058
if merger.reprocess and not merger.merge_type.supports_reprocess:
3059
raise errors.BzrCommandError("Conflict reduction is not supported"
3060
" for merge type %s." %
3062
if merger.reprocess and merger.show_base:
3063
raise errors.BzrCommandError("Cannot do conflict reduction and"
3066
def _get_merger_from_branch(self, tree, location, revision, remember,
3067
possible_transports, pb):
3068
"""Produce a merger from a location, assuming it refers to a branch."""
3069
from bzrlib.tag import _merge_tags_if_possible
3070
# find the branch locations
3071
other_loc, user_location = self._select_branch_location(tree, location,
3073
if revision is not None and len(revision) == 2:
3074
base_loc, _unused = self._select_branch_location(tree,
3075
location, revision, 0)
3077
base_loc = other_loc
3079
other_branch, other_path = Branch.open_containing(other_loc,
3080
possible_transports)
3081
if base_loc == other_loc:
3082
base_branch = other_branch
3084
base_branch, base_path = Branch.open_containing(base_loc,
3085
possible_transports)
3086
# Find the revision ids
3087
if revision is None or len(revision) < 1 or revision[-1] is None:
3088
other_revision_id = _mod_revision.ensure_null(
3089
other_branch.last_revision())
3091
other_revision_id = revision[-1].as_revision_id(other_branch)
3092
if (revision is not None and len(revision) == 2
3093
and revision[0] is not None):
3094
base_revision_id = revision[0].as_revision_id(base_branch)
3096
base_revision_id = None
3097
# Remember where we merge from
3098
if ((remember or tree.branch.get_submit_branch() is None) and
3099
user_location is not None):
3100
tree.branch.set_submit_branch(other_branch.base)
3101
_merge_tags_if_possible(other_branch, tree.branch)
3102
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3103
other_revision_id, base_revision_id, other_branch, base_branch)
3104
if other_path != '':
3105
allow_pending = False
3106
merger.interesting_files = [other_path]
3108
allow_pending = True
3109
return merger, allow_pending
3111
def _select_branch_location(self, tree, user_location, revision=None,
3113
"""Select a branch location, according to possible inputs.
3115
If provided, branches from ``revision`` are preferred. (Both
3116
``revision`` and ``index`` must be supplied.)
3118
Otherwise, the ``location`` parameter is used. If it is None, then the
3119
``submit`` or ``parent`` location is used, and a note is printed.
3121
:param tree: The working tree to select a branch for merging into
3122
:param location: The location entered by the user
3123
:param revision: The revision parameter to the command
3124
:param index: The index to use for the revision parameter. Negative
3125
indices are permitted.
3126
:return: (selected_location, user_location). The default location
3127
will be the user-entered location.
3129
if (revision is not None and index is not None
3130
and revision[index] is not None):
3131
branch = revision[index].get_branch()
3132
if branch is not None:
3133
return branch, branch
3134
if user_location is None:
3135
location = self._get_remembered(tree, 'Merging from')
3137
location = user_location
3138
return location, user_location
3140
def _get_remembered(self, tree, verb_string):
3141
"""Use tree.branch's parent if none was supplied.
3143
Report if the remembered location was used.
3145
stored_location = tree.branch.get_submit_branch()
3146
stored_location_type = "submit"
3147
if stored_location is None:
3148
stored_location = tree.branch.get_parent()
3149
stored_location_type = "parent"
3150
mutter("%s", stored_location)
3151
if stored_location is None:
3152
raise errors.BzrCommandError("No location specified or remembered")
3153
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3154
note(u"%s remembered %s location %s", verb_string,
3155
stored_location_type, display_url)
3156
return stored_location
3159
class cmd_remerge(Command):
3162
Use this if you want to try a different merge technique while resolving
3163
conflicts. Some merge techniques are better than others, and remerge
3164
lets you try different ones on different files.
3166
The options for remerge have the same meaning and defaults as the ones for
3167
merge. The difference is that remerge can (only) be run when there is a
3168
pending merge, and it lets you specify particular files.
3171
Re-do the merge of all conflicted files, and show the base text in
3172
conflict regions, in addition to the usual THIS and OTHER texts::
3174
bzr remerge --show-base
3176
Re-do the merge of "foobar", using the weave merge algorithm, with
3177
additional processing to reduce the size of conflict regions::
3179
bzr remerge --merge-type weave --reprocess foobar
3181
takes_args = ['file*']
3186
help="Show base revision text in conflicts."),
3189
def run(self, file_list=None, merge_type=None, show_base=False,
3191
if merge_type is None:
3192
merge_type = _mod_merge.Merge3Merger
3193
tree, file_list = tree_files(file_list)
3196
parents = tree.get_parent_ids()
3197
if len(parents) != 2:
3198
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3199
" merges. Not cherrypicking or"
3201
repository = tree.branch.repository
3202
interesting_ids = None
3204
conflicts = tree.conflicts()
3205
if file_list is not None:
3206
interesting_ids = set()
3207
for filename in file_list:
3208
file_id = tree.path2id(filename)
3210
raise errors.NotVersionedError(filename)
3211
interesting_ids.add(file_id)
3212
if tree.kind(file_id) != "directory":
3215
for name, ie in tree.inventory.iter_entries(file_id):
3216
interesting_ids.add(ie.file_id)
3217
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3219
# Remerge only supports resolving contents conflicts
3220
allowed_conflicts = ('text conflict', 'contents conflict')
3221
restore_files = [c.path for c in conflicts
3222
if c.typestring in allowed_conflicts]
3223
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3224
tree.set_conflicts(ConflictList(new_conflicts))
3225
if file_list is not None:
3226
restore_files = file_list
3227
for filename in restore_files:
3229
restore(tree.abspath(filename))
3230
except errors.NotConflicted:
3232
# Disable pending merges, because the file texts we are remerging
3233
# have not had those merges performed. If we use the wrong parents
3234
# list, we imply that the working tree text has seen and rejected
3235
# all the changes from the other tree, when in fact those changes
3236
# have not yet been seen.
3237
pb = ui.ui_factory.nested_progress_bar()
3238
tree.set_parent_ids(parents[:1])
3240
merger = _mod_merge.Merger.from_revision_ids(pb,
3242
merger.interesting_ids = interesting_ids
3243
merger.merge_type = merge_type
3244
merger.show_base = show_base
3245
merger.reprocess = reprocess
3246
conflicts = merger.do_merge()
3248
tree.set_parent_ids(parents)
3258
class cmd_revert(Command):
3259
"""Revert files to a previous revision.
3261
Giving a list of files will revert only those files. Otherwise, all files
3262
will be reverted. If the revision is not specified with '--revision', the
3263
last committed revision is used.
3265
To remove only some changes, without reverting to a prior version, use
3266
merge instead. For example, "merge . --revision -2..-3" will remove the
3267
changes introduced by -2, without affecting the changes introduced by -1.
3268
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3270
By default, any files that have been manually changed will be backed up
3271
first. (Files changed only by merge are not backed up.) Backup files have
3272
'.~#~' appended to their name, where # is a number.
3274
When you provide files, you can use their current pathname or the pathname
3275
from the target revision. So you can use revert to "undelete" a file by
3276
name. If you name a directory, all the contents of that directory will be
3279
Any files that have been newly added since that revision will be deleted,
3280
with a backup kept if appropriate. Directories containing unknown files
3281
will not be deleted.
3283
The working tree contains a list of pending merged revisions, which will
3284
be included as parents in the next commit. Normally, revert clears that
3285
list as well as reverting the files. If any files are specified, revert
3286
leaves the pending merge list alone and reverts only the files. Use "bzr
3287
revert ." in the tree root to revert all files but keep the merge record,
3288
and "bzr revert --forget-merges" to clear the pending merge list without
3289
reverting any files.
3292
_see_also = ['cat', 'export']
3295
Option('no-backup', "Do not save backups of reverted files."),
3296
Option('forget-merges',
3297
'Remove pending merge marker, without changing any files.'),
3299
takes_args = ['file*']
3301
def run(self, revision=None, no_backup=False, file_list=None,
3302
forget_merges=None):
3303
tree, file_list = tree_files(file_list)
3307
tree.set_parent_ids(tree.get_parent_ids()[:1])
3309
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3314
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3315
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3316
pb = ui.ui_factory.nested_progress_bar()
3318
tree.revert(file_list, rev_tree, not no_backup, pb,
3319
report_changes=True)
3324
class cmd_assert_fail(Command):
3325
"""Test reporting of assertion failures"""
3326
# intended just for use in testing
3331
raise AssertionError("always fails")
3334
class cmd_help(Command):
3335
"""Show help on a command or other topic.
3338
_see_also = ['topics']
3340
Option('long', 'Show help on all commands.'),
3342
takes_args = ['topic?']
3343
aliases = ['?', '--help', '-?', '-h']
3346
def run(self, topic=None, long=False):
3348
if topic is None and long:
3350
bzrlib.help.help(topic)
3353
class cmd_shell_complete(Command):
3354
"""Show appropriate completions for context.
3356
For a list of all available commands, say 'bzr shell-complete'.
3358
takes_args = ['context?']
3363
def run(self, context=None):
3364
import shellcomplete
3365
shellcomplete.shellcomplete(context)
3368
class cmd_missing(Command):
3369
"""Show unmerged/unpulled revisions between two branches.
3371
OTHER_BRANCH may be local or remote.
3374
_see_also = ['merge', 'pull']
3375
takes_args = ['other_branch?']
3377
Option('reverse', 'Reverse the order of revisions.'),
3379
'Display changes in the local branch only.'),
3380
Option('this' , 'Same as --mine-only.'),
3381
Option('theirs-only',
3382
'Display changes in the remote branch only.'),
3383
Option('other', 'Same as --theirs-only.'),
3387
Option('include-merges', 'Show merged revisions.'),
3389
encoding_type = 'replace'
3392
def run(self, other_branch=None, reverse=False, mine_only=False,
3394
log_format=None, long=False, short=False, line=False,
3395
show_ids=False, verbose=False, this=False, other=False,
3396
include_merges=False):
3397
from bzrlib.missing import find_unmerged, iter_log_revisions
3403
# TODO: We should probably check that we don't have mine-only and
3404
# theirs-only set, but it gets complicated because we also have
3405
# this and other which could be used.
3412
local_branch = Branch.open_containing(u".")[0]
3413
parent = local_branch.get_parent()
3414
if other_branch is None:
3415
other_branch = parent
3416
if other_branch is None:
3417
raise errors.BzrCommandError("No peer location known"
3419
display_url = urlutils.unescape_for_display(parent,
3421
self.outf.write("Using saved parent location: "
3422
+ display_url + "\n")
3424
remote_branch = Branch.open(other_branch)
3425
if remote_branch.base == local_branch.base:
3426
remote_branch = local_branch
3427
local_branch.lock_read()
3429
remote_branch.lock_read()
3431
local_extra, remote_extra = find_unmerged(
3432
local_branch, remote_branch, restrict,
3433
backward=not reverse,
3434
include_merges=include_merges)
3436
if log_format is None:
3437
registry = log.log_formatter_registry
3438
log_format = registry.get_default(local_branch)
3439
lf = log_format(to_file=self.outf,
3441
show_timezone='original')
3444
if local_extra and not theirs_only:
3445
self.outf.write("You have %d extra revision(s):\n" %
3447
for revision in iter_log_revisions(local_extra,
3448
local_branch.repository,
3450
lf.log_revision(revision)
3451
printed_local = True
3454
printed_local = False
3456
if remote_extra and not mine_only:
3457
if printed_local is True:
3458
self.outf.write("\n\n\n")
3459
self.outf.write("You are missing %d revision(s):\n" %
3461
for revision in iter_log_revisions(remote_extra,
3462
remote_branch.repository,
3464
lf.log_revision(revision)
3467
if mine_only and not local_extra:
3468
# We checked local, and found nothing extra
3469
self.outf.write('This branch is up to date.\n')
3470
elif theirs_only and not remote_extra:
3471
# We checked remote, and found nothing extra
3472
self.outf.write('Other branch is up to date.\n')
3473
elif not (mine_only or theirs_only or local_extra or
3475
# We checked both branches, and neither one had extra
3477
self.outf.write("Branches are up to date.\n")
3479
remote_branch.unlock()
3481
local_branch.unlock()
3482
if not status_code and parent is None and other_branch is not None:
3483
local_branch.lock_write()
3485
# handle race conditions - a parent might be set while we run.
3486
if local_branch.get_parent() is None:
3487
local_branch.set_parent(remote_branch.base)
3489
local_branch.unlock()
3493
class cmd_pack(Command):
3494
"""Compress the data within a repository."""
3496
_see_also = ['repositories']
3497
takes_args = ['branch_or_repo?']
3499
def run(self, branch_or_repo='.'):
3500
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3502
branch = dir.open_branch()
3503
repository = branch.repository
3504
except errors.NotBranchError:
3505
repository = dir.open_repository()
3509
class cmd_plugins(Command):
3510
"""List the installed plugins.
3512
This command displays the list of installed plugins including
3513
version of plugin and a short description of each.
3515
--verbose shows the path where each plugin is located.
3517
A plugin is an external component for Bazaar that extends the
3518
revision control system, by adding or replacing code in Bazaar.
3519
Plugins can do a variety of things, including overriding commands,
3520
adding new commands, providing additional network transports and
3521
customizing log output.
3523
See the Bazaar web site, http://bazaar-vcs.org, for further
3524
information on plugins including where to find them and how to
3525
install them. Instructions are also provided there on how to
3526
write new plugins using the Python programming language.
3528
takes_options = ['verbose']
3531
def run(self, verbose=False):
3532
import bzrlib.plugin
3533
from inspect import getdoc
3535
for name, plugin in bzrlib.plugin.plugins().items():
3536
version = plugin.__version__
3537
if version == 'unknown':
3539
name_ver = '%s %s' % (name, version)
3540
d = getdoc(plugin.module)
3542
doc = d.split('\n')[0]
3544
doc = '(no description)'
3545
result.append((name_ver, doc, plugin.path()))
3546
for name_ver, doc, path in sorted(result):
3554
class cmd_testament(Command):
3555
"""Show testament (signing-form) of a revision."""
3558
Option('long', help='Produce long-format testament.'),
3560
help='Produce a strict-format testament.')]
3561
takes_args = ['branch?']
3563
def run(self, branch=u'.', revision=None, long=False, strict=False):
3564
from bzrlib.testament import Testament, StrictTestament
3566
testament_class = StrictTestament
3568
testament_class = Testament
3570
b = Branch.open_containing(branch)[0]
3572
b = Branch.open(branch)
3575
if revision is None:
3576
rev_id = b.last_revision()
3578
rev_id = revision[0].as_revision_id(b)
3579
t = testament_class.from_revision(b.repository, rev_id)
3581
sys.stdout.writelines(t.as_text_lines())
3583
sys.stdout.write(t.as_short_text())
3588
class cmd_annotate(Command):
3589
"""Show the origin of each line in a file.
3591
This prints out the given file with an annotation on the left side
3592
indicating which revision, author and date introduced the change.
3594
If the origin is the same for a run of consecutive lines, it is
3595
shown only at the top, unless the --all option is given.
3597
# TODO: annotate directories; showing when each file was last changed
3598
# TODO: if the working copy is modified, show annotations on that
3599
# with new uncommitted lines marked
3600
aliases = ['ann', 'blame', 'praise']
3601
takes_args = ['filename']
3602
takes_options = [Option('all', help='Show annotations on all lines.'),
3603
Option('long', help='Show commit date in annotations.'),
3607
encoding_type = 'exact'
3610
def run(self, filename, all=False, long=False, revision=None,
3612
from bzrlib.annotate import annotate_file, annotate_file_tree
3613
wt, branch, relpath = \
3614
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3620
tree = _get_one_revision_tree('annotate', revision, branch=branch)
3622
file_id = wt.path2id(relpath)
3624
file_id = tree.path2id(relpath)
3626
raise errors.NotVersionedError(filename)
3627
file_version = tree.inventory[file_id].revision
3628
if wt is not None and revision is None:
3629
# If there is a tree and we're not annotating historical
3630
# versions, annotate the working tree's content.
3631
annotate_file_tree(wt, file_id, self.outf, long, all,
3634
annotate_file(branch, file_version, file_id, long, all, self.outf,
3643
class cmd_re_sign(Command):
3644
"""Create a digital signature for an existing revision."""
3645
# TODO be able to replace existing ones.
3647
hidden = True # is this right ?
3648
takes_args = ['revision_id*']
3649
takes_options = ['revision']
3651
def run(self, revision_id_list=None, revision=None):
3652
if revision_id_list is not None and revision is not None:
3653
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3654
if revision_id_list is None and revision is None:
3655
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3656
b = WorkingTree.open_containing(u'.')[0].branch
3659
return self._run(b, revision_id_list, revision)
3663
def _run(self, b, revision_id_list, revision):
3664
import bzrlib.gpg as gpg
3665
gpg_strategy = gpg.GPGStrategy(b.get_config())
3666
if revision_id_list is not None:
3667
b.repository.start_write_group()
3669
for revision_id in revision_id_list:
3670
b.repository.sign_revision(revision_id, gpg_strategy)
3672
b.repository.abort_write_group()
3675
b.repository.commit_write_group()
3676
elif revision is not None:
3677
if len(revision) == 1:
3678
revno, rev_id = revision[0].in_history(b)
3679
b.repository.start_write_group()
3681
b.repository.sign_revision(rev_id, gpg_strategy)
3683
b.repository.abort_write_group()
3686
b.repository.commit_write_group()
3687
elif len(revision) == 2:
3688
# are they both on rh- if so we can walk between them
3689
# might be nice to have a range helper for arbitrary
3690
# revision paths. hmm.
3691
from_revno, from_revid = revision[0].in_history(b)
3692
to_revno, to_revid = revision[1].in_history(b)
3693
if to_revid is None:
3694
to_revno = b.revno()
3695
if from_revno is None or to_revno is None:
3696
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3697
b.repository.start_write_group()
3699
for revno in range(from_revno, to_revno + 1):
3700
b.repository.sign_revision(b.get_rev_id(revno),
3703
b.repository.abort_write_group()
3706
b.repository.commit_write_group()
3708
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3711
class cmd_bind(Command):
3712
"""Convert the current branch into a checkout of the supplied branch.
3714
Once converted into a checkout, commits must succeed on the master branch
3715
before they will be applied to the local branch.
3718
_see_also = ['checkouts', 'unbind']
3719
takes_args = ['location?']
3722
def run(self, location=None):
3723
b, relpath = Branch.open_containing(u'.')
3724
if location is None:
3726
location = b.get_old_bound_location()
3727
except errors.UpgradeRequired:
3728
raise errors.BzrCommandError('No location supplied. '
3729
'This format does not remember old locations.')
3731
if location is None:
3732
raise errors.BzrCommandError('No location supplied and no '
3733
'previous location known')
3734
b_other = Branch.open(location)
3737
except errors.DivergedBranches:
3738
raise errors.BzrCommandError('These branches have diverged.'
3739
' Try merging, and then bind again.')
3742
class cmd_unbind(Command):
3743
"""Convert the current checkout into a regular branch.
3745
After unbinding, the local branch is considered independent and subsequent
3746
commits will be local only.
3749
_see_also = ['checkouts', 'bind']
3754
b, relpath = Branch.open_containing(u'.')
3756
raise errors.BzrCommandError('Local branch is not bound')
3759
class cmd_uncommit(Command):
3760
"""Remove the last committed revision.
3762
--verbose will print out what is being removed.
3763
--dry-run will go through all the motions, but not actually
3766
If --revision is specified, uncommit revisions to leave the branch at the
3767
specified revision. For example, "bzr uncommit -r 15" will leave the
3768
branch at revision 15.
3770
Uncommit leaves the working tree ready for a new commit. The only change
3771
it may make is to restore any pending merges that were present before
3775
# TODO: jam 20060108 Add an option to allow uncommit to remove
3776
# unreferenced information in 'branch-as-repository' branches.
3777
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3778
# information in shared branches as well.
3779
_see_also = ['commit']
3780
takes_options = ['verbose', 'revision',
3781
Option('dry-run', help='Don\'t actually make changes.'),
3782
Option('force', help='Say yes to all questions.'),
3784
help="Only remove the commits from the local branch"
3785
" when in a checkout."
3788
takes_args = ['location?']
3790
encoding_type = 'replace'
3792
def run(self, location=None,
3793
dry_run=False, verbose=False,
3794
revision=None, force=False, local=False):
3795
if location is None:
3797
control, relpath = bzrdir.BzrDir.open_containing(location)
3799
tree = control.open_workingtree()
3801
except (errors.NoWorkingTree, errors.NotLocalUrl):
3803
b = control.open_branch()
3805
if tree is not None:
3810
return self._run(b, tree, dry_run, verbose, revision, force,
3813
if tree is not None:
3818
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3819
from bzrlib.log import log_formatter, show_log
3820
from bzrlib.uncommit import uncommit
3822
last_revno, last_rev_id = b.last_revision_info()
3825
if revision is None:
3827
rev_id = last_rev_id
3829
# 'bzr uncommit -r 10' actually means uncommit
3830
# so that the final tree is at revno 10.
3831
# but bzrlib.uncommit.uncommit() actually uncommits
3832
# the revisions that are supplied.
3833
# So we need to offset it by one
3834
revno = revision[0].in_history(b).revno + 1
3835
if revno <= last_revno:
3836
rev_id = b.get_rev_id(revno)
3838
if rev_id is None or _mod_revision.is_null(rev_id):
3839
self.outf.write('No revisions to uncommit.\n')
3842
lf = log_formatter('short',
3844
show_timezone='original')
3849
direction='forward',
3850
start_revision=revno,
3851
end_revision=last_revno)
3854
print 'Dry-run, pretending to remove the above revisions.'
3856
val = raw_input('Press <enter> to continue')
3858
print 'The above revision(s) will be removed.'
3860
val = raw_input('Are you sure [y/N]? ')
3861
if val.lower() not in ('y', 'yes'):
3865
mutter('Uncommitting from {%s} to {%s}',
3866
last_rev_id, rev_id)
3867
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3868
revno=revno, local=local)
3869
note('You can restore the old tip by running:\n'
3870
' bzr pull . -r revid:%s', last_rev_id)
3873
class cmd_break_lock(Command):
3874
"""Break a dead lock on a repository, branch or working directory.
3876
CAUTION: Locks should only be broken when you are sure that the process
3877
holding the lock has been stopped.
3879
You can get information on what locks are open via the 'bzr info' command.
3884
takes_args = ['location?']
3886
def run(self, location=None, show=False):
3887
if location is None:
3889
control, relpath = bzrdir.BzrDir.open_containing(location)
3891
control.break_lock()
3892
except NotImplementedError:
3896
class cmd_wait_until_signalled(Command):
3897
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3899
This just prints a line to signal when it is ready, then blocks on stdin.
3905
sys.stdout.write("running\n")
3907
sys.stdin.readline()
3910
class cmd_serve(Command):
3911
"""Run the bzr server."""
3913
aliases = ['server']
3917
help='Serve on stdin/out for use from inetd or sshd.'),
3919
help='Listen for connections on nominated port of the form '
3920
'[hostname:]portnumber. Passing 0 as the port number will '
3921
'result in a dynamically allocated port. The default port is '
3925
help='Serve contents of this directory.',
3927
Option('allow-writes',
3928
help='By default the server is a readonly server. Supplying '
3929
'--allow-writes enables write access to the contents of '
3930
'the served directory and below.'
3934
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3935
from bzrlib import lockdir
3936
from bzrlib.smart import medium, server
3937
from bzrlib.transport import get_transport
3938
from bzrlib.transport.chroot import ChrootServer
3939
if directory is None:
3940
directory = os.getcwd()
3941
url = urlutils.local_path_to_url(directory)
3942
if not allow_writes:
3943
url = 'readonly+' + url
3944
chroot_server = ChrootServer(get_transport(url))
3945
chroot_server.setUp()
3946
t = get_transport(chroot_server.get_url())
3948
smart_server = medium.SmartServerPipeStreamMedium(
3949
sys.stdin, sys.stdout, t)
3951
host = medium.BZR_DEFAULT_INTERFACE
3953
port = medium.BZR_DEFAULT_PORT
3956
host, port = port.split(':')
3958
smart_server = server.SmartTCPServer(t, host=host, port=port)
3959
print 'listening on port: ', smart_server.port
3961
# for the duration of this server, no UI output is permitted.
3962
# note that this may cause problems with blackbox tests. This should
3963
# be changed with care though, as we dont want to use bandwidth sending
3964
# progress over stderr to smart server clients!
3965
old_factory = ui.ui_factory
3966
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
3968
ui.ui_factory = ui.SilentUIFactory()
3969
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3970
smart_server.serve()
3972
ui.ui_factory = old_factory
3973
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
3976
class cmd_join(Command):
3977
"""Combine a subtree into its containing tree.
3979
This command is for experimental use only. It requires the target tree
3980
to be in dirstate-with-subtree format, which cannot be converted into
3983
The TREE argument should be an independent tree, inside another tree, but
3984
not part of it. (Such trees can be produced by "bzr split", but also by
3985
running "bzr branch" with the target inside a tree.)
3987
The result is a combined tree, with the subtree no longer an independant
3988
part. This is marked as a merge of the subtree into the containing tree,
3989
and all history is preserved.
3991
If --reference is specified, the subtree retains its independence. It can
3992
be branched by itself, and can be part of multiple projects at the same
3993
time. But operations performed in the containing tree, such as commit
3994
and merge, will recurse into the subtree.
3997
_see_also = ['split']
3998
takes_args = ['tree']
4000
Option('reference', help='Join by reference.'),
4004
def run(self, tree, reference=False):
4005
sub_tree = WorkingTree.open(tree)
4006
parent_dir = osutils.dirname(sub_tree.basedir)
4007
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4008
repo = containing_tree.branch.repository
4009
if not repo.supports_rich_root():
4010
raise errors.BzrCommandError(
4011
"Can't join trees because %s doesn't support rich root data.\n"
4012
"You can use bzr upgrade on the repository."
4016
containing_tree.add_reference(sub_tree)
4017
except errors.BadReferenceTarget, e:
4018
# XXX: Would be better to just raise a nicely printable
4019
# exception from the real origin. Also below. mbp 20070306
4020
raise errors.BzrCommandError("Cannot join %s. %s" %
4024
containing_tree.subsume(sub_tree)
4025
except errors.BadSubsumeSource, e:
4026
raise errors.BzrCommandError("Cannot join %s. %s" %
4030
class cmd_split(Command):
4031
"""Split a subdirectory of a tree into a separate tree.
4033
This command will produce a target tree in a format that supports
4034
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4035
converted into earlier formats like 'dirstate-tags'.
4037
The TREE argument should be a subdirectory of a working tree. That
4038
subdirectory will be converted into an independent tree, with its own
4039
branch. Commits in the top-level tree will not apply to the new subtree.
4042
# join is not un-hidden yet
4043
#_see_also = ['join']
4044
takes_args = ['tree']
4046
def run(self, tree):
4047
containing_tree, subdir = WorkingTree.open_containing(tree)
4048
sub_id = containing_tree.path2id(subdir)
4050
raise errors.NotVersionedError(subdir)
4052
containing_tree.extract(sub_id)
4053
except errors.RootNotRich:
4054
raise errors.UpgradeRequired(containing_tree.branch.base)
4057
class cmd_merge_directive(Command):
4058
"""Generate a merge directive for auto-merge tools.
4060
A directive requests a merge to be performed, and also provides all the
4061
information necessary to do so. This means it must either include a
4062
revision bundle, or the location of a branch containing the desired
4065
A submit branch (the location to merge into) must be supplied the first
4066
time the command is issued. After it has been supplied once, it will
4067
be remembered as the default.
4069
A public branch is optional if a revision bundle is supplied, but required
4070
if --diff or --plain is specified. It will be remembered as the default
4071
after the first use.
4074
takes_args = ['submit_branch?', 'public_branch?']
4078
_see_also = ['send']
4081
RegistryOption.from_kwargs('patch-type',
4082
'The type of patch to include in the directive.',
4084
value_switches=True,
4086
bundle='Bazaar revision bundle (default).',
4087
diff='Normal unified diff.',
4088
plain='No patch, just directive.'),
4089
Option('sign', help='GPG-sign the directive.'), 'revision',
4090
Option('mail-to', type=str,
4091
help='Instead of printing the directive, email to this address.'),
4092
Option('message', type=str, short_name='m',
4093
help='Message to use when committing this merge.')
4096
encoding_type = 'exact'
4098
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4099
sign=False, revision=None, mail_to=None, message=None):
4100
from bzrlib.revision import ensure_null, NULL_REVISION
4101
include_patch, include_bundle = {
4102
'plain': (False, False),
4103
'diff': (True, False),
4104
'bundle': (True, True),
4106
branch = Branch.open('.')
4107
stored_submit_branch = branch.get_submit_branch()
4108
if submit_branch is None:
4109
submit_branch = stored_submit_branch
4111
if stored_submit_branch is None:
4112
branch.set_submit_branch(submit_branch)
4113
if submit_branch is None:
4114
submit_branch = branch.get_parent()
4115
if submit_branch is None:
4116
raise errors.BzrCommandError('No submit branch specified or known')
4118
stored_public_branch = branch.get_public_branch()
4119
if public_branch is None:
4120
public_branch = stored_public_branch
4121
elif stored_public_branch is None:
4122
branch.set_public_branch(public_branch)
4123
if not include_bundle and public_branch is None:
4124
raise errors.BzrCommandError('No public branch specified or'
4126
base_revision_id = None
4127
if revision is not None:
4128
if len(revision) > 2:
4129
raise errors.BzrCommandError('bzr merge-directive takes '
4130
'at most two one revision identifiers')
4131
revision_id = revision[-1].as_revision_id(branch)
4132
if len(revision) == 2:
4133
base_revision_id = revision[0].as_revision_id(branch)
4135
revision_id = branch.last_revision()
4136
revision_id = ensure_null(revision_id)
4137
if revision_id == NULL_REVISION:
4138
raise errors.BzrCommandError('No revisions to bundle.')
4139
directive = merge_directive.MergeDirective2.from_objects(
4140
branch.repository, revision_id, time.time(),
4141
osutils.local_time_offset(), submit_branch,
4142
public_branch=public_branch, include_patch=include_patch,
4143
include_bundle=include_bundle, message=message,
4144
base_revision_id=base_revision_id)
4147
self.outf.write(directive.to_signed(branch))
4149
self.outf.writelines(directive.to_lines())
4151
message = directive.to_email(mail_to, branch, sign)
4152
s = SMTPConnection(branch.get_config())
4153
s.send_email(message)
4156
class cmd_send(Command):
4157
"""Mail or create a merge-directive for submiting changes.
4159
A merge directive provides many things needed for requesting merges:
4161
* A machine-readable description of the merge to perform
4163
* An optional patch that is a preview of the changes requested
4165
* An optional bundle of revision data, so that the changes can be applied
4166
directly from the merge directive, without retrieving data from a
4169
If --no-bundle is specified, then public_branch is needed (and must be
4170
up-to-date), so that the receiver can perform the merge using the
4171
public_branch. The public_branch is always included if known, so that
4172
people can check it later.
4174
The submit branch defaults to the parent, but can be overridden. Both
4175
submit branch and public branch will be remembered if supplied.
4177
If a public_branch is known for the submit_branch, that public submit
4178
branch is used in the merge instructions. This means that a local mirror
4179
can be used as your actual submit branch, once you have set public_branch
4182
Mail is sent using your preferred mail program. This should be transparent
4183
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4184
If the preferred client can't be found (or used), your editor will be used.
4186
To use a specific mail program, set the mail_client configuration option.
4187
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4188
specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4189
generic options are "default", "editor", "emacsclient", "mapi", and
4190
"xdg-email". Plugins may also add supported clients.
4192
If mail is being sent, a to address is required. This can be supplied
4193
either on the commandline, by setting the submit_to configuration
4194
option in the branch itself or the child_submit_to configuration option
4195
in the submit branch.
4197
Two formats are currently supported: "4" uses revision bundle format 4 and
4198
merge directive format 2. It is significantly faster and smaller than
4199
older formats. It is compatible with Bazaar 0.19 and later. It is the
4200
default. "0.9" uses revision bundle format 0.9 and merge directive
4201
format 1. It is compatible with Bazaar 0.12 - 0.18.
4203
Merge directives are applied using the merge command or the pull command.
4206
encoding_type = 'exact'
4208
_see_also = ['merge', 'pull']
4210
takes_args = ['submit_branch?', 'public_branch?']
4214
help='Do not include a bundle in the merge directive.'),
4215
Option('no-patch', help='Do not include a preview patch in the merge'
4218
help='Remember submit and public branch.'),
4220
help='Branch to generate the submission from, '
4221
'rather than the one containing the working directory.',
4224
Option('output', short_name='o',
4225
help='Write merge directive to this file; '
4226
'use - for stdout.',
4228
Option('mail-to', help='Mail the request to this address.',
4232
RegistryOption.from_kwargs('format',
4233
'Use the specified output format.',
4234
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4235
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4238
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4239
no_patch=False, revision=None, remember=False, output=None,
4240
format='4', mail_to=None, message=None, **kwargs):
4241
return self._run(submit_branch, revision, public_branch, remember,
4242
format, no_bundle, no_patch, output,
4243
kwargs.get('from', '.'), mail_to, message)
4245
def _run(self, submit_branch, revision, public_branch, remember, format,
4246
no_bundle, no_patch, output, from_, mail_to, message):
4247
from bzrlib.revision import NULL_REVISION
4248
branch = Branch.open_containing(from_)[0]
4250
outfile = cStringIO.StringIO()
4254
outfile = open(output, 'wb')
4255
# we may need to write data into branch's repository to calculate
4260
config = branch.get_config()
4262
mail_to = config.get_user_option('submit_to')
4263
mail_client = config.get_mail_client()
4264
if remember and submit_branch is None:
4265
raise errors.BzrCommandError(
4266
'--remember requires a branch to be specified.')
4267
stored_submit_branch = branch.get_submit_branch()
4268
remembered_submit_branch = None
4269
if submit_branch is None:
4270
submit_branch = stored_submit_branch
4271
remembered_submit_branch = "submit"
4273
if stored_submit_branch is None or remember:
4274
branch.set_submit_branch(submit_branch)
4275
if submit_branch is None:
4276
submit_branch = branch.get_parent()
4277
remembered_submit_branch = "parent"
4278
if submit_branch is None:
4279
raise errors.BzrCommandError('No submit branch known or'
4281
if remembered_submit_branch is not None:
4282
note('Using saved %s location "%s" to determine what '
4283
'changes to submit.', remembered_submit_branch,
4287
submit_config = Branch.open(submit_branch).get_config()
4288
mail_to = submit_config.get_user_option("child_submit_to")
4290
stored_public_branch = branch.get_public_branch()
4291
if public_branch is None:
4292
public_branch = stored_public_branch
4293
elif stored_public_branch is None or remember:
4294
branch.set_public_branch(public_branch)
4295
if no_bundle and public_branch is None:
4296
raise errors.BzrCommandError('No public branch specified or'
4298
base_revision_id = None
4300
if revision is not None:
4301
if len(revision) > 2:
4302
raise errors.BzrCommandError('bzr send takes '
4303
'at most two one revision identifiers')
4304
revision_id = revision[-1].as_revision_id(branch)
4305
if len(revision) == 2:
4306
base_revision_id = revision[0].as_revision_id(branch)
4307
if revision_id is None:
4308
revision_id = branch.last_revision()
4309
if revision_id == NULL_REVISION:
4310
raise errors.BzrCommandError('No revisions to submit.')
4312
directive = merge_directive.MergeDirective2.from_objects(
4313
branch.repository, revision_id, time.time(),
4314
osutils.local_time_offset(), submit_branch,
4315
public_branch=public_branch, include_patch=not no_patch,
4316
include_bundle=not no_bundle, message=message,
4317
base_revision_id=base_revision_id)
4318
elif format == '0.9':
4321
patch_type = 'bundle'
4323
raise errors.BzrCommandError('Format 0.9 does not'
4324
' permit bundle with no patch')
4330
directive = merge_directive.MergeDirective.from_objects(
4331
branch.repository, revision_id, time.time(),
4332
osutils.local_time_offset(), submit_branch,
4333
public_branch=public_branch, patch_type=patch_type,
4336
outfile.writelines(directive.to_lines())
4338
subject = '[MERGE] '
4339
if message is not None:
4342
revision = branch.repository.get_revision(revision_id)
4343
subject += revision.get_summary()
4344
basename = directive.get_disk_name(branch)
4345
mail_client.compose_merge_request(mail_to, subject,
4346
outfile.getvalue(), basename)
4353
class cmd_bundle_revisions(cmd_send):
4355
"""Create a merge-directive for submiting changes.
4357
A merge directive provides many things needed for requesting merges:
4359
* A machine-readable description of the merge to perform
4361
* An optional patch that is a preview of the changes requested
4363
* An optional bundle of revision data, so that the changes can be applied
4364
directly from the merge directive, without retrieving data from a
4367
If --no-bundle is specified, then public_branch is needed (and must be
4368
up-to-date), so that the receiver can perform the merge using the
4369
public_branch. The public_branch is always included if known, so that
4370
people can check it later.
4372
The submit branch defaults to the parent, but can be overridden. Both
4373
submit branch and public branch will be remembered if supplied.
4375
If a public_branch is known for the submit_branch, that public submit
4376
branch is used in the merge instructions. This means that a local mirror
4377
can be used as your actual submit branch, once you have set public_branch
4380
Two formats are currently supported: "4" uses revision bundle format 4 and
4381
merge directive format 2. It is significantly faster and smaller than
4382
older formats. It is compatible with Bazaar 0.19 and later. It is the
4383
default. "0.9" uses revision bundle format 0.9 and merge directive
4384
format 1. It is compatible with Bazaar 0.12 - 0.18.
4389
help='Do not include a bundle in the merge directive.'),
4390
Option('no-patch', help='Do not include a preview patch in the merge'
4393
help='Remember submit and public branch.'),
4395
help='Branch to generate the submission from, '
4396
'rather than the one containing the working directory.',
4399
Option('output', short_name='o', help='Write directive to this file.',
4402
RegistryOption.from_kwargs('format',
4403
'Use the specified output format.',
4404
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4405
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4407
aliases = ['bundle']
4409
_see_also = ['send', 'merge']
4413
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4414
no_patch=False, revision=None, remember=False, output=None,
4415
format='4', **kwargs):
4418
return self._run(submit_branch, revision, public_branch, remember,
4419
format, no_bundle, no_patch, output,
4420
kwargs.get('from', '.'), None, None)
4423
class cmd_tag(Command):
4424
"""Create, remove or modify a tag naming a revision.
4426
Tags give human-meaningful names to revisions. Commands that take a -r
4427
(--revision) option can be given -rtag:X, where X is any previously
4430
Tags are stored in the branch. Tags are copied from one branch to another
4431
along when you branch, push, pull or merge.
4433
It is an error to give a tag name that already exists unless you pass
4434
--force, in which case the tag is moved to point to the new revision.
4436
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4437
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4440
_see_also = ['commit', 'tags']
4441
takes_args = ['tag_name']
4444
help='Delete this tag rather than placing it.',
4447
help='Branch in which to place the tag.',
4452
help='Replace existing tags.',
4457
def run(self, tag_name,
4463
branch, relpath = Branch.open_containing(directory)
4467
branch.tags.delete_tag(tag_name)
4468
self.outf.write('Deleted tag %s.\n' % tag_name)
4471
if len(revision) != 1:
4472
raise errors.BzrCommandError(
4473
"Tags can only be placed on a single revision, "
4475
revision_id = revision[0].as_revision_id(branch)
4477
revision_id = branch.last_revision()
4478
if (not force) and branch.tags.has_tag(tag_name):
4479
raise errors.TagAlreadyExists(tag_name)
4480
branch.tags.set_tag(tag_name, revision_id)
4481
self.outf.write('Created tag %s.\n' % tag_name)
4486
class cmd_tags(Command):
4489
This command shows a table of tag names and the revisions they reference.
4495
help='Branch whose tags should be displayed.',
4499
RegistryOption.from_kwargs('sort',
4500
'Sort tags by different criteria.', title='Sorting',
4501
alpha='Sort tags lexicographically (default).',
4502
time='Sort tags chronologically.',
4513
branch, relpath = Branch.open_containing(directory)
4514
tags = branch.tags.get_tag_dict().items()
4519
elif sort == 'time':
4521
for tag, revid in tags:
4523
revobj = branch.repository.get_revision(revid)
4524
except errors.NoSuchRevision:
4525
timestamp = sys.maxint # place them at the end
4527
timestamp = revobj.timestamp
4528
timestamps[revid] = timestamp
4529
tags.sort(key=lambda x: timestamps[x[1]])
4531
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4532
revno_map = branch.get_revision_id_to_revno_map()
4533
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4534
for tag, revid in tags ]
4535
for tag, revspec in tags:
4536
self.outf.write('%-20s %s\n' % (tag, revspec))
4539
class cmd_reconfigure(Command):
4540
"""Reconfigure the type of a bzr directory.
4542
A target configuration must be specified.
4544
For checkouts, the bind-to location will be auto-detected if not specified.
4545
The order of preference is
4546
1. For a lightweight checkout, the current bound location.
4547
2. For branches that used to be checkouts, the previously-bound location.
4548
3. The push location.
4549
4. The parent location.
4550
If none of these is available, --bind-to must be specified.
4553
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4554
takes_args = ['location?']
4555
takes_options = [RegistryOption.from_kwargs('target_type',
4556
title='Target type',
4557
help='The type to reconfigure the directory to.',
4558
value_switches=True, enum_switch=False,
4559
branch='Reconfigure to be an unbound branch '
4560
'with no working tree.',
4561
tree='Reconfigure to be an unbound branch '
4562
'with a working tree.',
4563
checkout='Reconfigure to be a bound branch '
4564
'with a working tree.',
4565
lightweight_checkout='Reconfigure to be a lightweight'
4566
' checkout (with no local history).',
4567
standalone='Reconfigure to be a standalone branch '
4568
'(i.e. stop using shared repository).',
4569
use_shared='Reconfigure to use a shared repository.'),
4570
Option('bind-to', help='Branch to bind checkout to.',
4573
help='Perform reconfiguration even if local changes'
4577
def run(self, location=None, target_type=None, bind_to=None, force=False):
4578
directory = bzrdir.BzrDir.open(location)
4579
if target_type is None:
4580
raise errors.BzrCommandError('No target configuration specified')
4581
elif target_type == 'branch':
4582
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4583
elif target_type == 'tree':
4584
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4585
elif target_type == 'checkout':
4586
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4588
elif target_type == 'lightweight-checkout':
4589
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4591
elif target_type == 'use-shared':
4592
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4593
elif target_type == 'standalone':
4594
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4595
reconfiguration.apply(force)
4598
class cmd_switch(Command):
4599
"""Set the branch of a checkout and update.
4601
For lightweight checkouts, this changes the branch being referenced.
4602
For heavyweight checkouts, this checks that there are no local commits
4603
versus the current bound branch, then it makes the local branch a mirror
4604
of the new location and binds to it.
4606
In both cases, the working tree is updated and uncommitted changes
4607
are merged. The user can commit or revert these as they desire.
4609
Pending merges need to be committed or reverted before using switch.
4611
The path to the branch to switch to can be specified relative to the parent
4612
directory of the current branch. For example, if you are currently in a
4613
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4617
takes_args = ['to_location']
4618
takes_options = [Option('force',
4619
help='Switch even if local commits will be lost.')
4622
def run(self, to_location, force=False):
4623
from bzrlib import switch
4625
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4627
to_branch = Branch.open(to_location)
4628
except errors.NotBranchError:
4629
this_branch = control_dir.open_branch()
4630
# This may be a heavy checkout, where we want the master branch
4631
this_url = this_branch.get_bound_location()
4632
# If not, use a local sibling
4633
if this_url is None:
4634
this_url = this_branch.base
4635
to_branch = Branch.open(
4636
urlutils.join(this_url, '..', to_location))
4637
switch.switch(control_dir, to_branch, force)
4638
note('Switched to branch: %s',
4639
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4642
class cmd_hooks(Command):
4643
"""Show a branch's currently registered hooks.
4647
takes_args = ['path?']
4649
def run(self, path=None):
4652
branch_hooks = Branch.open(path).hooks
4653
for hook_type in branch_hooks:
4654
hooks = branch_hooks[hook_type]
4655
self.outf.write("%s:\n" % (hook_type,))
4658
self.outf.write(" %s\n" %
4659
(branch_hooks.get_hook_name(hook),))
4661
self.outf.write(" <no hooks installed>\n")
4664
def _create_prefix(cur_transport):
4665
needed = [cur_transport]
4666
# Recurse upwards until we can create a directory successfully
4668
new_transport = cur_transport.clone('..')
4669
if new_transport.base == cur_transport.base:
4670
raise errors.BzrCommandError(
4671
"Failed to create path prefix for %s."
4672
% cur_transport.base)
4674
new_transport.mkdir('.')
4675
except errors.NoSuchFile:
4676
needed.append(new_transport)
4677
cur_transport = new_transport
4680
# Now we only need to create child directories
4682
cur_transport = needed.pop()
4683
cur_transport.ensure_base()
4686
# these get imported and then picked up by the scan for cmd_*
4687
# TODO: Some more consistent way to split command definitions across files;
4688
# we do need to load at least some information about them to know of
4689
# aliases. ideally we would avoid loading the implementation until the
4690
# details were needed.
4691
from bzrlib.cmd_version_info import cmd_version_info
4692
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4693
from bzrlib.bundle.commands import (
4696
from bzrlib.sign_my_commits import cmd_sign_my_commits
4697
from bzrlib.weave_commands import cmd_versionedfile_list, \
4698
cmd_weave_plan_merge, cmd_weave_merge_text