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(), """
43
revision as _mod_revision,
50
from bzrlib.branch import Branch
51
from bzrlib.conflicts import ConflictList
52
from bzrlib.revisionspec import RevisionSpec
53
from bzrlib.smtp_connection import SMTPConnection
54
from bzrlib.workingtree import WorkingTree
57
from bzrlib.commands import Command, display_command
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
59
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
62
def tree_files(file_list, default_branch=u'.'):
64
return internal_tree_files(file_list, default_branch)
65
except errors.FileInWrongBranch, e:
66
raise errors.BzrCommandError("%s is not in the same branch as %s" %
67
(e.path, file_list[0]))
70
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
75
rev_tree = tree.basis_tree()
77
rev_tree = branch.basis_tree()
79
if len(revisions) != 1:
80
raise errors.BzrCommandError(
81
'bzr %s --revision takes exactly one revision identifier' % (
83
rev_tree = revisions[0].as_tree(branch)
87
# XXX: Bad function name; should possibly also be a class method of
88
# WorkingTree rather than a function.
89
def internal_tree_files(file_list, default_branch=u'.'):
90
"""Convert command-line paths to a WorkingTree and relative paths.
92
This is typically used for command-line processors that take one or
93
more filenames, and infer the workingtree that contains them.
95
The filenames given are not required to exist.
97
:param file_list: Filenames to convert.
99
:param default_branch: Fallback tree path to use if file_list is empty or
102
:return: workingtree, [relative_paths]
104
if file_list is None or len(file_list) == 0:
105
return WorkingTree.open_containing(default_branch)[0], file_list
106
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
107
return tree, safe_relpath_files(tree, file_list)
110
def safe_relpath_files(tree, file_list):
111
"""Convert file_list into a list of relpaths in tree.
113
:param tree: A tree to operate on.
114
:param file_list: A list of user provided paths or None.
115
:return: A list of relative paths.
116
:raises errors.PathNotChild: When a provided path is in a different tree
119
if file_list is None:
122
for filename in file_list:
124
new_list.append(tree.relpath(osutils.dereference_path(filename)))
125
except errors.PathNotChild:
126
raise errors.FileInWrongBranch(tree.branch, filename)
130
# TODO: Make sure no commands unconditionally use the working directory as a
131
# branch. If a filename argument is used, the first of them should be used to
132
# specify the branch. (Perhaps this can be factored out into some kind of
133
# Argument class, representing a file in a branch, where the first occurrence
136
class cmd_status(Command):
137
"""Display status summary.
139
This reports on versioned and unknown files, reporting them
140
grouped by state. Possible states are:
143
Versioned in the working copy but not in the previous revision.
146
Versioned in the previous revision but removed or deleted
150
Path of this file changed from the previous revision;
151
the text may also have changed. This includes files whose
152
parent directory was renamed.
155
Text has changed since the previous revision.
158
File kind has been changed (e.g. from file to directory).
161
Not versioned and not matching an ignore pattern.
163
To see ignored files use 'bzr ignored'. For details on the
164
changes to file texts, use 'bzr diff'.
166
Note that --short or -S gives status flags for each item, similar
167
to Subversion's status command. To get output similar to svn -q,
170
If no arguments are specified, the status of the entire working
171
directory is shown. Otherwise, only the status of the specified
172
files or directories is reported. If a directory is given, status
173
is reported for everything inside that directory.
175
If a revision argument is given, the status is calculated against
176
that revision, or between two revisions if two are provided.
179
# TODO: --no-recurse, --recurse options
181
takes_args = ['file*']
182
takes_options = ['show-ids', 'revision', 'change',
183
Option('short', help='Use short status indicators.',
185
Option('versioned', help='Only show versioned files.',
187
Option('no-pending', help='Don\'t show pending merges.',
190
aliases = ['st', 'stat']
192
encoding_type = 'replace'
193
_see_also = ['diff', 'revert', 'status-flags']
196
def run(self, show_ids=False, file_list=None, revision=None, short=False,
197
versioned=False, no_pending=False):
198
from bzrlib.status import show_tree_status
200
if revision and len(revision) > 2:
201
raise errors.BzrCommandError('bzr status --revision takes exactly'
202
' one or two revision specifiers')
204
tree, relfile_list = tree_files(file_list)
205
# Avoid asking for specific files when that is not needed.
206
if relfile_list == ['']:
208
# Don't disable pending merges for full trees other than '.'.
209
if file_list == ['.']:
211
# A specific path within a tree was given.
212
elif relfile_list is not None:
213
# convert the names to canonical versions stored in the inventory
214
relfile_list = tree.get_canonical_inventory_paths(relfile_list)
216
show_tree_status(tree, show_ids=show_ids,
217
specific_files=relfile_list, revision=revision,
218
to_file=self.outf, short=short, versioned=versioned,
219
show_pending=(not no_pending))
222
class cmd_cat_revision(Command):
223
"""Write out metadata for a revision.
225
The revision to print can either be specified by a specific
226
revision identifier, or you can use --revision.
230
takes_args = ['revision_id?']
231
takes_options = ['revision']
232
# cat-revision is more for frontends so should be exact
236
def run(self, revision_id=None, revision=None):
237
if revision_id is not None and revision is not None:
238
raise errors.BzrCommandError('You can only supply one of'
239
' revision_id or --revision')
240
if revision_id is None and revision is None:
241
raise errors.BzrCommandError('You must supply either'
242
' --revision or a revision_id')
243
b = WorkingTree.open_containing(u'.')[0].branch
245
# TODO: jam 20060112 should cat-revision always output utf-8?
246
if revision_id is not None:
247
revision_id = osutils.safe_revision_id(revision_id, warn=False)
249
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
250
except errors.NoSuchRevision:
251
msg = "The repository %s contains no revision %s." % (b.repository.base,
253
raise errors.BzrCommandError(msg)
254
elif revision is not None:
257
raise errors.BzrCommandError('You cannot specify a NULL'
259
rev_id = rev.as_revision_id(b)
260
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
263
class cmd_dump_btree(Command):
264
"""Dump the contents of a btree index file to stdout.
266
PATH is a btree index file, it can be any URL. This includes things like
267
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
269
By default, the tuples stored in the index file will be displayed. With
270
--raw, we will uncompress the pages, but otherwise display the raw bytes
274
# TODO: Do we want to dump the internal nodes as well?
275
# TODO: It would be nice to be able to dump the un-parsed information,
276
# rather than only going through iter_all_entries. However, this is
277
# good enough for a start
279
encoding_type = 'exact'
280
takes_args = ['path']
281
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
282
' rather than the parsed tuples.'),
285
def run(self, path, raw=False):
286
dirname, basename = osutils.split(path)
287
t = transport.get_transport(dirname)
289
self._dump_raw_bytes(t, basename)
291
self._dump_entries(t, basename)
293
def _get_index_and_bytes(self, trans, basename):
294
"""Create a BTreeGraphIndex and raw bytes."""
295
bt = btree_index.BTreeGraphIndex(trans, basename, None)
296
bytes = trans.get_bytes(basename)
297
bt._file = cStringIO.StringIO(bytes)
298
bt._size = len(bytes)
301
def _dump_raw_bytes(self, trans, basename):
304
# We need to parse at least the root node.
305
# This is because the first page of every row starts with an
306
# uncompressed header.
307
bt, bytes = self._get_index_and_bytes(trans, basename)
308
for page_idx, page_start in enumerate(xrange(0, len(bytes),
309
btree_index._PAGE_SIZE)):
310
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
311
page_bytes = bytes[page_start:page_end]
313
self.outf.write('Root node:\n')
314
header_end, data = bt._parse_header_from_bytes(page_bytes)
315
self.outf.write(page_bytes[:header_end])
317
self.outf.write('\nPage %d\n' % (page_idx,))
318
decomp_bytes = zlib.decompress(page_bytes)
319
self.outf.write(decomp_bytes)
320
self.outf.write('\n')
322
def _dump_entries(self, trans, basename):
324
st = trans.stat(basename)
325
except errors.TransportNotPossible:
326
# We can't stat, so we'll fake it because we have to do the 'get()'
328
bt, _ = self._get_index_and_bytes(trans, basename)
330
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
331
for node in bt.iter_all_entries():
332
# Node is made up of:
333
# (index, key, value, [references])
334
self.outf.write('%s\n' % (node[1:],))
337
class cmd_remove_tree(Command):
338
"""Remove the working tree from a given branch/checkout.
340
Since a lightweight checkout is little more than a working tree
341
this will refuse to run against one.
343
To re-create the working tree, use "bzr checkout".
345
_see_also = ['checkout', 'working-trees']
346
takes_args = ['location?']
349
help='Remove the working tree even if it has '
350
'uncommitted changes.'),
353
def run(self, location='.', force=False):
354
d = bzrdir.BzrDir.open(location)
357
working = d.open_workingtree()
358
except errors.NoWorkingTree:
359
raise errors.BzrCommandError("No working tree to remove")
360
except errors.NotLocalUrl:
361
raise errors.BzrCommandError("You cannot remove the working tree of a "
364
changes = working.changes_from(working.basis_tree())
365
if changes.has_changed():
366
raise errors.UncommittedChanges(working)
368
working_path = working.bzrdir.root_transport.base
369
branch_path = working.branch.bzrdir.root_transport.base
370
if working_path != branch_path:
371
raise errors.BzrCommandError("You cannot remove the working tree from "
372
"a lightweight checkout")
374
d.destroy_workingtree()
377
class cmd_revno(Command):
378
"""Show current revision number.
380
This is equal to the number of revisions on this branch.
384
takes_args = ['location?']
387
def run(self, location=u'.'):
388
self.outf.write(str(Branch.open_containing(location)[0].revno()))
389
self.outf.write('\n')
392
class cmd_revision_info(Command):
393
"""Show revision number and revision id for a given revision identifier.
396
takes_args = ['revision_info*']
400
help='Branch to examine, '
401
'rather than the one containing the working directory.',
408
def run(self, revision=None, directory=u'.', revision_info_list=[]):
411
if revision is not None:
412
revs.extend(revision)
413
if revision_info_list is not None:
414
for rev in revision_info_list:
415
revs.append(RevisionSpec.from_string(rev))
417
b = Branch.open_containing(directory)[0]
420
revs.append(RevisionSpec.from_string('-1'))
423
revision_id = rev.as_revision_id(b)
425
revno = '%4d' % (b.revision_id_to_revno(revision_id))
426
except errors.NoSuchRevision:
427
dotted_map = b.get_revision_id_to_revno_map()
428
revno = '.'.join(str(i) for i in dotted_map[revision_id])
429
print '%s %s' % (revno, revision_id)
432
class cmd_add(Command):
433
"""Add specified files or directories.
435
In non-recursive mode, all the named items are added, regardless
436
of whether they were previously ignored. A warning is given if
437
any of the named files are already versioned.
439
In recursive mode (the default), files are treated the same way
440
but the behaviour for directories is different. Directories that
441
are already versioned do not give a warning. All directories,
442
whether already versioned or not, are searched for files or
443
subdirectories that are neither versioned or ignored, and these
444
are added. This search proceeds recursively into versioned
445
directories. If no names are given '.' is assumed.
447
Therefore simply saying 'bzr add' will version all files that
448
are currently unknown.
450
Adding a file whose parent directory is not versioned will
451
implicitly add the parent, and so on up to the root. This means
452
you should never need to explicitly add a directory, they'll just
453
get added when you add a file in the directory.
455
--dry-run will show which files would be added, but not actually
458
--file-ids-from will try to use the file ids from the supplied path.
459
It looks up ids trying to find a matching parent directory with the
460
same filename, and then by pure path. This option is rarely needed
461
but can be useful when adding the same logical file into two
462
branches that will be merged later (without showing the two different
463
adds as a conflict). It is also useful when merging another project
464
into a subdirectory of this one.
466
takes_args = ['file*']
469
help="Don't recursively add the contents of directories."),
471
help="Show what would be done, but don't actually do anything."),
473
Option('file-ids-from',
475
help='Lookup file ids from this tree.'),
477
encoding_type = 'replace'
478
_see_also = ['remove']
480
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
485
if file_ids_from is not None:
487
base_tree, base_path = WorkingTree.open_containing(
489
except errors.NoWorkingTree:
490
base_branch, base_path = Branch.open_containing(
492
base_tree = base_branch.basis_tree()
494
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
495
to_file=self.outf, should_print=(not is_quiet()))
497
action = bzrlib.add.AddAction(to_file=self.outf,
498
should_print=(not is_quiet()))
501
base_tree.lock_read()
503
file_list = self._maybe_expand_globs(file_list)
505
tree = WorkingTree.open_containing(file_list[0])[0]
507
tree = WorkingTree.open_containing(u'.')[0]
508
added, ignored = tree.smart_add(file_list, not
509
no_recurse, action=action, save=not dry_run)
511
if base_tree is not None:
515
for glob in sorted(ignored.keys()):
516
for path in ignored[glob]:
517
self.outf.write("ignored %s matching \"%s\"\n"
521
for glob, paths in ignored.items():
522
match_len += len(paths)
523
self.outf.write("ignored %d file(s).\n" % match_len)
524
self.outf.write("If you wish to add some of these files,"
525
" please add them by name.\n")
528
class cmd_mkdir(Command):
529
"""Create a new versioned directory.
531
This is equivalent to creating the directory and then adding it.
534
takes_args = ['dir+']
535
encoding_type = 'replace'
537
def run(self, dir_list):
540
wt, dd = WorkingTree.open_containing(d)
542
self.outf.write('added %s\n' % d)
545
class cmd_relpath(Command):
546
"""Show path of a file relative to root"""
548
takes_args = ['filename']
552
def run(self, filename):
553
# TODO: jam 20050106 Can relpath return a munged path if
554
# sys.stdout encoding cannot represent it?
555
tree, relpath = WorkingTree.open_containing(filename)
556
self.outf.write(relpath)
557
self.outf.write('\n')
560
class cmd_inventory(Command):
561
"""Show inventory of the current working copy or a revision.
563
It is possible to limit the output to a particular entry
564
type using the --kind option. For example: --kind file.
566
It is also possible to restrict the list of files to a specific
567
set. For example: bzr inventory --show-ids this/file
576
help='List entries of a particular kind: file, directory, symlink.',
579
takes_args = ['file*']
582
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
583
if kind and kind not in ['file', 'directory', 'symlink']:
584
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
586
work_tree, file_list = tree_files(file_list)
587
work_tree.lock_read()
589
if revision is not None:
590
if len(revision) > 1:
591
raise errors.BzrCommandError(
592
'bzr inventory --revision takes exactly one revision'
594
tree = revision[0].as_tree(work_tree.branch)
596
extra_trees = [work_tree]
602
if file_list is not None:
603
file_ids = tree.paths2ids(file_list, trees=extra_trees,
604
require_versioned=True)
605
# find_ids_across_trees may include some paths that don't
607
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
608
for file_id in file_ids if file_id in tree)
610
entries = tree.inventory.entries()
613
if tree is not work_tree:
616
for path, entry in entries:
617
if kind and kind != entry.kind:
620
self.outf.write('%-50s %s\n' % (path, entry.file_id))
622
self.outf.write(path)
623
self.outf.write('\n')
626
class cmd_mv(Command):
627
"""Move or rename a file.
630
bzr mv OLDNAME NEWNAME
632
bzr mv SOURCE... DESTINATION
634
If the last argument is a versioned directory, all the other names
635
are moved into it. Otherwise, there must be exactly two arguments
636
and the file is changed to a new name.
638
If OLDNAME does not exist on the filesystem but is versioned and
639
NEWNAME does exist on the filesystem but is not versioned, mv
640
assumes that the file has been manually moved and only updates
641
its internal inventory to reflect that change.
642
The same is valid when moving many SOURCE files to a DESTINATION.
644
Files cannot be moved between branches.
647
takes_args = ['names*']
648
takes_options = [Option("after", help="Move only the bzr identifier"
649
" of the file, because the file has already been moved."),
651
aliases = ['move', 'rename']
652
encoding_type = 'replace'
654
def run(self, names_list, after=False):
655
if names_list is None:
658
if len(names_list) < 2:
659
raise errors.BzrCommandError("missing file argument")
660
tree, rel_names = tree_files(names_list)
663
self._run(tree, names_list, rel_names, after)
667
def _run(self, tree, names_list, rel_names, after):
668
into_existing = osutils.isdir(names_list[-1])
669
if into_existing and len(names_list) == 2:
671
# a. case-insensitive filesystem and change case of dir
672
# b. move directory after the fact (if the source used to be
673
# a directory, but now doesn't exist in the working tree
674
# and the target is an existing directory, just rename it)
675
if (not tree.case_sensitive
676
and rel_names[0].lower() == rel_names[1].lower()):
677
into_existing = False
680
# 'fix' the case of a potential 'from'
681
from_id = tree.path2id(
682
tree.get_canonical_inventory_path(rel_names[0]))
683
if (not osutils.lexists(names_list[0]) and
684
from_id and inv.get_file_kind(from_id) == "directory"):
685
into_existing = False
688
# move into existing directory
689
# All entries reference existing inventory items, so fix them up
690
# for cicp file-systems.
691
rel_names = tree.get_canonical_inventory_paths(rel_names)
692
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
693
self.outf.write("%s => %s\n" % pair)
695
if len(names_list) != 2:
696
raise errors.BzrCommandError('to mv multiple files the'
697
' destination must be a versioned'
700
# for cicp file-systems: the src references an existing inventory
702
src = tree.get_canonical_inventory_path(rel_names[0])
703
# Find the canonical version of the destination: In all cases, the
704
# parent of the target must be in the inventory, so we fetch the
705
# canonical version from there (we do not always *use* the
706
# canonicalized tail portion - we may be attempting to rename the
708
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
709
dest_parent = osutils.dirname(canon_dest)
710
spec_tail = osutils.basename(rel_names[1])
711
# For a CICP file-system, we need to avoid creating 2 inventory
712
# entries that differ only by case. So regardless of the case
713
# we *want* to use (ie, specified by the user or the file-system),
714
# we must always choose to use the case of any existing inventory
715
# items. The only exception to this is when we are attempting a
716
# case-only rename (ie, canonical versions of src and dest are
718
dest_id = tree.path2id(canon_dest)
719
if dest_id is None or tree.path2id(src) == dest_id:
720
# No existing item we care about, so work out what case we
721
# are actually going to use.
723
# If 'after' is specified, the tail must refer to a file on disk.
725
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
727
# pathjoin with an empty tail adds a slash, which breaks
729
dest_parent_fq = tree.basedir
731
dest_tail = osutils.canonical_relpath(
733
osutils.pathjoin(dest_parent_fq, spec_tail))
735
# not 'after', so case as specified is used
736
dest_tail = spec_tail
738
# Use the existing item so 'mv' fails with AlreadyVersioned.
739
dest_tail = os.path.basename(canon_dest)
740
dest = osutils.pathjoin(dest_parent, dest_tail)
741
mutter("attempting to move %s => %s", src, dest)
742
tree.rename_one(src, dest, after=after)
743
self.outf.write("%s => %s\n" % (src, dest))
746
class cmd_pull(Command):
747
"""Turn this branch into a mirror of another branch.
749
This command only works on branches that have not diverged. Branches are
750
considered diverged if the destination branch's most recent commit is one
751
that has not been merged (directly or indirectly) into the parent.
753
If branches have diverged, you can use 'bzr merge' to integrate the changes
754
from one into the other. Once one branch has merged, the other should
755
be able to pull it again.
757
If you want to forget your local changes and just update your branch to
758
match the remote one, use pull --overwrite.
760
If there is no default location set, the first pull will set it. After
761
that, you can omit the location to use the default. To change the
762
default, use --remember. The value will only be saved if the remote
763
location can be accessed.
765
Note: The location can be specified either in the form of a branch,
766
or in the form of a path to a file containing a merge directive generated
770
_see_also = ['push', 'update', 'status-flags']
771
takes_options = ['remember', 'overwrite', 'revision',
772
custom_help('verbose',
773
help='Show logs of pulled revisions.'),
775
help='Branch to pull into, '
776
'rather than the one containing the working directory.',
781
takes_args = ['location?']
782
encoding_type = 'replace'
784
def run(self, location=None, remember=False, overwrite=False,
785
revision=None, verbose=False,
787
# FIXME: too much stuff is in the command class
790
if directory is None:
793
tree_to = WorkingTree.open_containing(directory)[0]
794
branch_to = tree_to.branch
795
except errors.NoWorkingTree:
797
branch_to = Branch.open_containing(directory)[0]
799
possible_transports = []
800
if location is not None:
802
mergeable = bundle.read_mergeable_from_url(location,
803
possible_transports=possible_transports)
804
except errors.NotABundle:
807
stored_loc = branch_to.get_parent()
809
if stored_loc is None:
810
raise errors.BzrCommandError("No pull location known or"
813
display_url = urlutils.unescape_for_display(stored_loc,
816
self.outf.write("Using saved parent location: %s\n" % display_url)
817
location = stored_loc
819
if mergeable is not None:
820
if revision is not None:
821
raise errors.BzrCommandError(
822
'Cannot use -r with merge directives or bundles')
823
mergeable.install_revisions(branch_to.repository)
824
base_revision_id, revision_id, verified = \
825
mergeable.get_merge_request(branch_to.repository)
826
branch_from = branch_to
828
branch_from = Branch.open(location,
829
possible_transports=possible_transports)
831
if branch_to.get_parent() is None or remember:
832
branch_to.set_parent(branch_from.base)
834
if revision is not None:
835
if len(revision) == 1:
836
revision_id = revision[0].as_revision_id(branch_from)
838
raise errors.BzrCommandError(
839
'bzr pull --revision takes one value.')
841
branch_to.lock_write()
843
if tree_to is not None:
844
change_reporter = delta._ChangeReporter(
845
unversioned_filter=tree_to.is_ignored)
846
result = tree_to.pull(branch_from, overwrite, revision_id,
848
possible_transports=possible_transports)
850
result = branch_to.pull(branch_from, overwrite, revision_id)
852
result.report(self.outf)
853
if verbose and result.old_revid != result.new_revid:
855
branch_to.repository.iter_reverse_revision_history(
858
new_rh = branch_to.revision_history()
859
log_format = branch_to.get_config().log_format()
860
log.show_changed_revisions(branch_to, old_rh, new_rh,
862
log_format=log_format)
867
class cmd_push(Command):
868
"""Update a mirror of this branch.
870
The target branch will not have its working tree populated because this
871
is both expensive, and is not supported on remote file systems.
873
Some smart servers or protocols *may* put the working tree in place in
876
This command only works on branches that have not diverged. Branches are
877
considered diverged if the destination branch's most recent commit is one
878
that has not been merged (directly or indirectly) by the source branch.
880
If branches have diverged, you can use 'bzr push --overwrite' to replace
881
the other branch completely, discarding its unmerged changes.
883
If you want to ensure you have the different changes in the other branch,
884
do a merge (see bzr help merge) from the other branch, and commit that.
885
After that you will be able to do a push without '--overwrite'.
887
If there is no default push location set, the first push will set it.
888
After that, you can omit the location to use the default. To change the
889
default, use --remember. The value will only be saved if the remote
890
location can be accessed.
893
_see_also = ['pull', 'update', 'working-trees']
894
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
895
Option('create-prefix',
896
help='Create the path leading up to the branch '
897
'if it does not already exist.'),
899
help='Branch to push from, '
900
'rather than the one containing the working directory.',
904
Option('use-existing-dir',
905
help='By default push will fail if the target'
906
' directory exists, but does not already'
907
' have a control directory. This flag will'
908
' allow push to proceed.'),
910
help='Create a stacked branch that references the public location '
911
'of the parent branch.'),
913
help='Create a stacked branch that refers to another branch '
914
'for the commit history. Only the work not present in the '
915
'referenced branch is included in the branch created.',
918
takes_args = ['location?']
919
encoding_type = 'replace'
921
def run(self, location=None, remember=False, overwrite=False,
922
create_prefix=False, verbose=False, revision=None,
923
use_existing_dir=False, directory=None, stacked_on=None,
925
from bzrlib.push import _show_push_branch
927
# Get the source branch and revision_id
928
if directory is None:
930
br_from = Branch.open_containing(directory)[0]
931
if revision is not None:
932
if len(revision) == 1:
933
revision_id = revision[0].in_history(br_from).rev_id
935
raise errors.BzrCommandError(
936
'bzr push --revision takes one value.')
938
revision_id = br_from.last_revision()
940
# Get the stacked_on branch, if any
941
if stacked_on is not None:
942
stacked_on = urlutils.normalize_url(stacked_on)
944
parent_url = br_from.get_parent()
946
parent = Branch.open(parent_url)
947
stacked_on = parent.get_public_branch()
949
# I considered excluding non-http url's here, thus forcing
950
# 'public' branches only, but that only works for some
951
# users, so it's best to just depend on the user spotting an
952
# error by the feedback given to them. RBC 20080227.
953
stacked_on = parent_url
955
raise errors.BzrCommandError(
956
"Could not determine branch to refer to.")
958
# Get the destination location
960
stored_loc = br_from.get_push_location()
961
if stored_loc is None:
962
raise errors.BzrCommandError(
963
"No push location known or specified.")
965
display_url = urlutils.unescape_for_display(stored_loc,
967
self.outf.write("Using saved push location: %s\n" % display_url)
968
location = stored_loc
970
_show_push_branch(br_from, revision_id, location, self.outf,
971
verbose=verbose, overwrite=overwrite, remember=remember,
972
stacked_on=stacked_on, create_prefix=create_prefix,
973
use_existing_dir=use_existing_dir)
976
class cmd_branch(Command):
977
"""Create a new copy of a branch.
979
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
980
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
981
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
982
is derived from the FROM_LOCATION by stripping a leading scheme or drive
983
identifier, if any. For example, "branch lp:foo-bar" will attempt to
986
To retrieve the branch as of a particular revision, supply the --revision
987
parameter, as in "branch foo/bar -r 5".
990
_see_also = ['checkout']
991
takes_args = ['from_location', 'to_location?']
992
takes_options = ['revision', Option('hardlink',
993
help='Hard-link working tree files where possible.'),
995
help='Create a stacked branch referring to the source branch. '
996
'The new branch will depend on the availability of the source '
997
'branch for all operations.'),
999
help='Do not use a shared repository, even if available.'),
1001
aliases = ['get', 'clone']
1003
def run(self, from_location, to_location=None, revision=None,
1004
hardlink=False, stacked=False, standalone=False):
1005
from bzrlib.tag import _merge_tags_if_possible
1006
if revision is None:
1008
elif len(revision) > 1:
1009
raise errors.BzrCommandError(
1010
'bzr branch --revision takes exactly 1 revision value')
1012
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1016
if len(revision) == 1 and revision[0] is not None:
1017
revision_id = revision[0].as_revision_id(br_from)
1019
# FIXME - wt.last_revision, fallback to branch, fall back to
1020
# None or perhaps NULL_REVISION to mean copy nothing
1022
revision_id = br_from.last_revision()
1023
if to_location is None:
1024
to_location = urlutils.derive_to_location(from_location)
1025
to_transport = transport.get_transport(to_location)
1027
to_transport.mkdir('.')
1028
except errors.FileExists:
1029
raise errors.BzrCommandError('Target directory "%s" already'
1030
' exists.' % to_location)
1031
except errors.NoSuchFile:
1032
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1035
# preserve whatever source format we have.
1036
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1037
possible_transports=[to_transport],
1038
accelerator_tree=accelerator_tree,
1039
hardlink=hardlink, stacked=stacked,
1040
force_new_repo=standalone,
1041
source_branch=br_from)
1042
branch = dir.open_branch()
1043
except errors.NoSuchRevision:
1044
to_transport.delete_tree('.')
1045
msg = "The branch %s has no revision %s." % (from_location,
1047
raise errors.BzrCommandError(msg)
1048
_merge_tags_if_possible(br_from, branch)
1049
# If the source branch is stacked, the new branch may
1050
# be stacked whether we asked for that explicitly or not.
1051
# We therefore need a try/except here and not just 'if stacked:'
1053
note('Created new stacked branch referring to %s.' %
1054
branch.get_stacked_on_url())
1055
except (errors.NotStacked, errors.UnstackableBranchFormat,
1056
errors.UnstackableRepositoryFormat), e:
1057
note('Branched %d revision(s).' % branch.revno())
1062
class cmd_checkout(Command):
1063
"""Create a new checkout of an existing branch.
1065
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1066
the branch found in '.'. This is useful if you have removed the working tree
1067
or if it was never created - i.e. if you pushed the branch to its current
1068
location using SFTP.
1070
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1071
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1072
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1073
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1074
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1077
To retrieve the branch as of a particular revision, supply the --revision
1078
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1079
out of date [so you cannot commit] but it may be useful (i.e. to examine old
1083
_see_also = ['checkouts', 'branch']
1084
takes_args = ['branch_location?', 'to_location?']
1085
takes_options = ['revision',
1086
Option('lightweight',
1087
help="Perform a lightweight checkout. Lightweight "
1088
"checkouts depend on access to the branch for "
1089
"every operation. Normal checkouts can perform "
1090
"common operations like diff and status without "
1091
"such access, and also support local commits."
1093
Option('files-from', type=str,
1094
help="Get file contents from this tree."),
1096
help='Hard-link working tree files where possible.'
1101
def run(self, branch_location=None, to_location=None, revision=None,
1102
lightweight=False, files_from=None, hardlink=False):
1103
if revision is None:
1105
elif len(revision) > 1:
1106
raise errors.BzrCommandError(
1107
'bzr checkout --revision takes exactly 1 revision value')
1108
if branch_location is None:
1109
branch_location = osutils.getcwd()
1110
to_location = branch_location
1111
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1113
if files_from is not None:
1114
accelerator_tree = WorkingTree.open(files_from)
1115
if len(revision) == 1 and revision[0] is not None:
1116
revision_id = revision[0].as_revision_id(source)
1119
if to_location is None:
1120
to_location = urlutils.derive_to_location(branch_location)
1121
# if the source and to_location are the same,
1122
# and there is no working tree,
1123
# then reconstitute a branch
1124
if (osutils.abspath(to_location) ==
1125
osutils.abspath(branch_location)):
1127
source.bzrdir.open_workingtree()
1128
except errors.NoWorkingTree:
1129
source.bzrdir.create_workingtree(revision_id)
1131
source.create_checkout(to_location, revision_id, lightweight,
1132
accelerator_tree, hardlink)
1135
class cmd_renames(Command):
1136
"""Show list of renamed files.
1138
# TODO: Option to show renames between two historical versions.
1140
# TODO: Only show renames under dir, rather than in the whole branch.
1141
_see_also = ['status']
1142
takes_args = ['dir?']
1145
def run(self, dir=u'.'):
1146
tree = WorkingTree.open_containing(dir)[0]
1149
new_inv = tree.inventory
1150
old_tree = tree.basis_tree()
1151
old_tree.lock_read()
1153
old_inv = old_tree.inventory
1155
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1156
for f, paths, c, v, p, n, k, e in iterator:
1157
if paths[0] == paths[1]:
1161
renames.append(paths)
1163
for old_name, new_name in renames:
1164
self.outf.write("%s => %s\n" % (old_name, new_name))
1171
class cmd_update(Command):
1172
"""Update a tree to have the latest code committed to its branch.
1174
This will perform a merge into the working tree, and may generate
1175
conflicts. If you have any local changes, you will still
1176
need to commit them after the update for the update to be complete.
1178
If you want to discard your local changes, you can just do a
1179
'bzr revert' instead of 'bzr commit' after the update.
1182
_see_also = ['pull', 'working-trees', 'status-flags']
1183
takes_args = ['dir?']
1186
def run(self, dir='.'):
1187
tree = WorkingTree.open_containing(dir)[0]
1188
possible_transports = []
1189
master = tree.branch.get_master_branch(
1190
possible_transports=possible_transports)
1191
if master is not None:
1194
tree.lock_tree_write()
1196
existing_pending_merges = tree.get_parent_ids()[1:]
1197
last_rev = _mod_revision.ensure_null(tree.last_revision())
1198
if last_rev == _mod_revision.ensure_null(
1199
tree.branch.last_revision()):
1200
# may be up to date, check master too.
1201
if master is None or last_rev == _mod_revision.ensure_null(
1202
master.last_revision()):
1203
revno = tree.branch.revision_id_to_revno(last_rev)
1204
note("Tree is up to date at revision %d." % (revno,))
1206
conflicts = tree.update(
1207
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1208
possible_transports=possible_transports)
1209
revno = tree.branch.revision_id_to_revno(
1210
_mod_revision.ensure_null(tree.last_revision()))
1211
note('Updated to revision %d.' % (revno,))
1212
if tree.get_parent_ids()[1:] != existing_pending_merges:
1213
note('Your local commits will now show as pending merges with '
1214
"'bzr status', and can be committed with 'bzr commit'.")
1223
class cmd_info(Command):
1224
"""Show information about a working tree, branch or repository.
1226
This command will show all known locations and formats associated to the
1227
tree, branch or repository. Statistical information is included with
1230
Branches and working trees will also report any missing revisions.
1232
_see_also = ['revno', 'working-trees', 'repositories']
1233
takes_args = ['location?']
1234
takes_options = ['verbose']
1235
encoding_type = 'replace'
1238
def run(self, location=None, verbose=False):
1243
from bzrlib.info import show_bzrdir_info
1244
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1245
verbose=noise_level, outfile=self.outf)
1248
class cmd_remove(Command):
1249
"""Remove files or directories.
1251
This makes bzr stop tracking changes to the specified files. bzr will delete
1252
them if they can easily be recovered using revert. If no options or
1253
parameters are given bzr will scan for files that are being tracked by bzr
1254
but missing in your tree and stop tracking them for you.
1256
takes_args = ['file*']
1257
takes_options = ['verbose',
1258
Option('new', help='Only remove files that have never been committed.'),
1259
RegistryOption.from_kwargs('file-deletion-strategy',
1260
'The file deletion mode to be used.',
1261
title='Deletion Strategy', value_switches=True, enum_switch=False,
1262
safe='Only delete files if they can be'
1263
' safely recovered (default).',
1264
keep="Don't delete any files.",
1265
force='Delete all the specified files, even if they can not be '
1266
'recovered and even if they are non-empty directories.')]
1267
aliases = ['rm', 'del']
1268
encoding_type = 'replace'
1270
def run(self, file_list, verbose=False, new=False,
1271
file_deletion_strategy='safe'):
1272
tree, file_list = tree_files(file_list)
1274
if file_list is not None:
1275
file_list = tree.get_canonical_inventory_paths(file_list)
1279
# Heuristics should probably all move into tree.remove_smart or
1282
added = tree.changes_from(tree.basis_tree(),
1283
specific_files=file_list).added
1284
file_list = sorted([f[0] for f in added], reverse=True)
1285
if len(file_list) == 0:
1286
raise errors.BzrCommandError('No matching files.')
1287
elif file_list is None:
1288
# missing files show up in iter_changes(basis) as
1289
# versioned-with-no-kind.
1291
for change in tree.iter_changes(tree.basis_tree()):
1292
# Find paths in the working tree that have no kind:
1293
if change[1][1] is not None and change[6][1] is None:
1294
missing.append(change[1][1])
1295
file_list = sorted(missing, reverse=True)
1296
file_deletion_strategy = 'keep'
1297
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1298
keep_files=file_deletion_strategy=='keep',
1299
force=file_deletion_strategy=='force')
1304
class cmd_file_id(Command):
1305
"""Print file_id of a particular file or directory.
1307
The file_id is assigned when the file is first added and remains the
1308
same through all revisions where the file exists, even when it is
1313
_see_also = ['inventory', 'ls']
1314
takes_args = ['filename']
1317
def run(self, filename):
1318
tree, relpath = WorkingTree.open_containing(filename)
1319
i = tree.path2id(relpath)
1321
raise errors.NotVersionedError(filename)
1323
self.outf.write(i + '\n')
1326
class cmd_file_path(Command):
1327
"""Print path of file_ids to a file or directory.
1329
This prints one line for each directory down to the target,
1330
starting at the branch root.
1334
takes_args = ['filename']
1337
def run(self, filename):
1338
tree, relpath = WorkingTree.open_containing(filename)
1339
fid = tree.path2id(relpath)
1341
raise errors.NotVersionedError(filename)
1342
segments = osutils.splitpath(relpath)
1343
for pos in range(1, len(segments) + 1):
1344
path = osutils.joinpath(segments[:pos])
1345
self.outf.write("%s\n" % tree.path2id(path))
1348
class cmd_reconcile(Command):
1349
"""Reconcile bzr metadata in a branch.
1351
This can correct data mismatches that may have been caused by
1352
previous ghost operations or bzr upgrades. You should only
1353
need to run this command if 'bzr check' or a bzr developer
1354
advises you to run it.
1356
If a second branch is provided, cross-branch reconciliation is
1357
also attempted, which will check that data like the tree root
1358
id which was not present in very early bzr versions is represented
1359
correctly in both branches.
1361
At the same time it is run it may recompress data resulting in
1362
a potential saving in disk space or performance gain.
1364
The branch *MUST* be on a listable system such as local disk or sftp.
1367
_see_also = ['check']
1368
takes_args = ['branch?']
1370
def run(self, branch="."):
1371
from bzrlib.reconcile import reconcile
1372
dir = bzrdir.BzrDir.open(branch)
1376
class cmd_revision_history(Command):
1377
"""Display the list of revision ids on a branch."""
1380
takes_args = ['location?']
1385
def run(self, location="."):
1386
branch = Branch.open_containing(location)[0]
1387
for revid in branch.revision_history():
1388
self.outf.write(revid)
1389
self.outf.write('\n')
1392
class cmd_ancestry(Command):
1393
"""List all revisions merged into this branch."""
1395
_see_also = ['log', 'revision-history']
1396
takes_args = ['location?']
1401
def run(self, location="."):
1403
wt = WorkingTree.open_containing(location)[0]
1404
except errors.NoWorkingTree:
1405
b = Branch.open(location)
1406
last_revision = b.last_revision()
1409
last_revision = wt.last_revision()
1411
revision_ids = b.repository.get_ancestry(last_revision)
1413
for revision_id in revision_ids:
1414
self.outf.write(revision_id + '\n')
1417
class cmd_init(Command):
1418
"""Make a directory into a versioned branch.
1420
Use this to create an empty branch, or before importing an
1423
If there is a repository in a parent directory of the location, then
1424
the history of the branch will be stored in the repository. Otherwise
1425
init creates a standalone branch which carries its own history
1426
in the .bzr directory.
1428
If there is already a branch at the location but it has no working tree,
1429
the tree can be populated with 'bzr checkout'.
1431
Recipe for importing a tree of files::
1437
bzr commit -m "imported project"
1440
_see_also = ['init-repository', 'branch', 'checkout']
1441
takes_args = ['location?']
1443
Option('create-prefix',
1444
help='Create the path leading up to the branch '
1445
'if it does not already exist.'),
1446
RegistryOption('format',
1447
help='Specify a format for this branch. '
1448
'See "help formats".',
1449
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1450
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1451
value_switches=True,
1452
title="Branch Format",
1454
Option('append-revisions-only',
1455
help='Never change revnos or the existing log.'
1456
' Append revisions to it only.')
1458
def run(self, location=None, format=None, append_revisions_only=False,
1459
create_prefix=False):
1461
format = bzrdir.format_registry.make_bzrdir('default')
1462
if location is None:
1465
to_transport = transport.get_transport(location)
1467
# The path has to exist to initialize a
1468
# branch inside of it.
1469
# Just using os.mkdir, since I don't
1470
# believe that we want to create a bunch of
1471
# locations if the user supplies an extended path
1473
to_transport.ensure_base()
1474
except errors.NoSuchFile:
1475
if not create_prefix:
1476
raise errors.BzrCommandError("Parent directory of %s"
1478
"\nYou may supply --create-prefix to create all"
1479
" leading parent directories."
1481
_create_prefix(to_transport)
1484
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1485
except errors.NotBranchError:
1486
# really a NotBzrDir error...
1487
create_branch = bzrdir.BzrDir.create_branch_convenience
1488
branch = create_branch(to_transport.base, format=format,
1489
possible_transports=[to_transport])
1490
a_bzrdir = branch.bzrdir
1492
from bzrlib.transport.local import LocalTransport
1493
if a_bzrdir.has_branch():
1494
if (isinstance(to_transport, LocalTransport)
1495
and not a_bzrdir.has_workingtree()):
1496
raise errors.BranchExistsWithoutWorkingTree(location)
1497
raise errors.AlreadyBranchError(location)
1498
branch = a_bzrdir.create_branch()
1499
a_bzrdir.create_workingtree()
1500
if append_revisions_only:
1502
branch.set_append_revisions_only(True)
1503
except errors.UpgradeRequired:
1504
raise errors.BzrCommandError('This branch format cannot be set'
1505
' to append-revisions-only. Try --experimental-branch6')
1507
from bzrlib.info import show_bzrdir_info
1508
show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1511
class cmd_init_repository(Command):
1512
"""Create a shared repository to hold branches.
1514
New branches created under the repository directory will store their
1515
revisions in the repository, not in the branch directory.
1517
If the --no-trees option is used then the branches in the repository
1518
will not have working trees by default.
1521
Create a shared repositories holding just branches::
1523
bzr init-repo --no-trees repo
1526
Make a lightweight checkout elsewhere::
1528
bzr checkout --lightweight repo/trunk trunk-checkout
1533
_see_also = ['init', 'branch', 'checkout', 'repositories']
1534
takes_args = ["location"]
1535
takes_options = [RegistryOption('format',
1536
help='Specify a format for this repository. See'
1537
' "bzr help formats" for details.',
1538
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1539
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1540
value_switches=True, title='Repository format'),
1542
help='Branches in the repository will default to'
1543
' not having a working tree.'),
1545
aliases = ["init-repo"]
1547
def run(self, location, format=None, no_trees=False):
1549
format = bzrdir.format_registry.make_bzrdir('default')
1551
if location is None:
1554
to_transport = transport.get_transport(location)
1555
to_transport.ensure_base()
1557
newdir = format.initialize_on_transport(to_transport)
1558
repo = newdir.create_repository(shared=True)
1559
repo.set_make_working_trees(not no_trees)
1561
from bzrlib.info import show_bzrdir_info
1562
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1565
class cmd_diff(Command):
1566
"""Show differences in the working tree, between revisions or branches.
1568
If no arguments are given, all changes for the current tree are listed.
1569
If files are given, only the changes in those files are listed.
1570
Remote and multiple branches can be compared by using the --old and
1571
--new options. If not provided, the default for both is derived from
1572
the first argument, if any, or the current tree if no arguments are
1575
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1576
produces patches suitable for "patch -p1".
1580
2 - unrepresentable changes
1585
Shows the difference in the working tree versus the last commit::
1589
Difference between the working tree and revision 1::
1593
Difference between revision 2 and revision 1::
1597
Difference between revision 2 and revision 1 for branch xxx::
1601
Show just the differences for file NEWS::
1605
Show the differences in working tree xxx for file NEWS::
1609
Show the differences from branch xxx to this working tree:
1613
Show the differences between two branches for file NEWS::
1615
bzr diff --old xxx --new yyy NEWS
1617
Same as 'bzr diff' but prefix paths with old/ and new/::
1619
bzr diff --prefix old/:new/
1621
_see_also = ['status']
1622
takes_args = ['file*']
1624
Option('diff-options', type=str,
1625
help='Pass these options to the external diff program.'),
1626
Option('prefix', type=str,
1628
help='Set prefixes added to old and new filenames, as '
1629
'two values separated by a colon. (eg "old/:new/").'),
1631
help='Branch/tree to compare from.',
1635
help='Branch/tree to compare to.',
1641
help='Use this command to compare files.',
1645
aliases = ['di', 'dif']
1646
encoding_type = 'exact'
1649
def run(self, revision=None, file_list=None, diff_options=None,
1650
prefix=None, old=None, new=None, using=None):
1651
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1653
if (prefix is None) or (prefix == '0'):
1661
old_label, new_label = prefix.split(":")
1663
raise errors.BzrCommandError(
1664
'--prefix expects two values separated by a colon'
1665
' (eg "old/:new/")')
1667
if revision and len(revision) > 2:
1668
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1669
' one or two revision specifiers')
1671
old_tree, new_tree, specific_files, extra_trees = \
1672
_get_trees_to_diff(file_list, revision, old, new)
1673
return show_diff_trees(old_tree, new_tree, sys.stdout,
1674
specific_files=specific_files,
1675
external_diff_options=diff_options,
1676
old_label=old_label, new_label=new_label,
1677
extra_trees=extra_trees, using=using)
1680
class cmd_deleted(Command):
1681
"""List files deleted in the working tree.
1683
# TODO: Show files deleted since a previous revision, or
1684
# between two revisions.
1685
# TODO: Much more efficient way to do this: read in new
1686
# directories with readdir, rather than stating each one. Same
1687
# level of effort but possibly much less IO. (Or possibly not,
1688
# if the directories are very large...)
1689
_see_also = ['status', 'ls']
1690
takes_options = ['show-ids']
1693
def run(self, show_ids=False):
1694
tree = WorkingTree.open_containing(u'.')[0]
1697
old = tree.basis_tree()
1700
for path, ie in old.inventory.iter_entries():
1701
if not tree.has_id(ie.file_id):
1702
self.outf.write(path)
1704
self.outf.write(' ')
1705
self.outf.write(ie.file_id)
1706
self.outf.write('\n')
1713
class cmd_modified(Command):
1714
"""List files modified in working tree.
1718
_see_also = ['status', 'ls']
1721
help='Write an ascii NUL (\\0) separator '
1722
'between files rather than a newline.')
1726
def run(self, null=False):
1727
tree = WorkingTree.open_containing(u'.')[0]
1728
td = tree.changes_from(tree.basis_tree())
1729
for path, id, kind, text_modified, meta_modified in td.modified:
1731
self.outf.write(path + '\0')
1733
self.outf.write(osutils.quotefn(path) + '\n')
1736
class cmd_added(Command):
1737
"""List files added in working tree.
1741
_see_also = ['status', 'ls']
1744
help='Write an ascii NUL (\\0) separator '
1745
'between files rather than a newline.')
1749
def run(self, null=False):
1750
wt = WorkingTree.open_containing(u'.')[0]
1753
basis = wt.basis_tree()
1756
basis_inv = basis.inventory
1759
if file_id in basis_inv:
1761
if inv.is_root(file_id) and len(basis_inv) == 0:
1763
path = inv.id2path(file_id)
1764
if not os.access(osutils.abspath(path), os.F_OK):
1767
self.outf.write(path + '\0')
1769
self.outf.write(osutils.quotefn(path) + '\n')
1776
class cmd_root(Command):
1777
"""Show the tree root directory.
1779
The root is the nearest enclosing directory with a .bzr control
1782
takes_args = ['filename?']
1784
def run(self, filename=None):
1785
"""Print the branch root."""
1786
tree = WorkingTree.open_containing(filename)[0]
1787
self.outf.write(tree.basedir + '\n')
1790
def _parse_limit(limitstring):
1792
return int(limitstring)
1794
msg = "The limit argument must be an integer."
1795
raise errors.BzrCommandError(msg)
1798
class cmd_log(Command):
1799
"""Show log of a branch, file, or directory.
1801
By default show the log of the branch containing the working directory.
1803
To request a range of logs, you can use the command -r begin..end
1804
-r revision requests a specific revision, -r ..end or -r begin.. are
1808
Log the current branch::
1816
Log the last 10 revisions of a branch::
1818
bzr log -r -10.. http://server/branch
1821
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1823
takes_args = ['location?']
1826
help='Show from oldest to newest.'),
1828
custom_help('verbose',
1829
help='Show files changed in each revision.'),
1833
type=bzrlib.option._parse_revision_str,
1835
help='Show just the specified revision.'
1836
' See also "help revisionspec".'),
1840
help='Show revisions whose message matches this '
1841
'regular expression.',
1845
help='Limit the output to the first N revisions.',
1849
encoding_type = 'replace'
1852
def run(self, location=None, timezone='original',
1861
from bzrlib.log import show_log
1862
direction = (forward and 'forward') or 'reverse'
1864
if change is not None:
1866
raise errors.RangeInChangeOption()
1867
if revision is not None:
1868
raise errors.BzrCommandError(
1869
'--revision and --change are mutually exclusive')
1876
# find the file id to log:
1878
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1882
tree = b.basis_tree()
1883
file_id = tree.path2id(fp)
1885
raise errors.BzrCommandError(
1886
"Path does not have any revision history: %s" %
1890
# FIXME ? log the current subdir only RBC 20060203
1891
if revision is not None \
1892
and len(revision) > 0 and revision[0].get_branch():
1893
location = revision[0].get_branch()
1896
dir, relpath = bzrdir.BzrDir.open_containing(location)
1897
b = dir.open_branch()
1901
rev1, rev2 = _get_revision_range(revision, b, self.name())
1902
if log_format is None:
1903
log_format = log.log_formatter_registry.get_default(b)
1905
lf = log_format(show_ids=show_ids, to_file=self.outf,
1906
show_timezone=timezone,
1907
delta_format=get_verbosity_level())
1913
direction=direction,
1914
start_revision=rev1,
1921
def _get_revision_range(revisionspec_list, branch, command_name):
1922
"""Take the input of a revision option and turn it into a revision range.
1924
It returns RevisionInfo objects which can be used to obtain the rev_id's
1925
of the desired revisons. It does some user input validations.
1927
if revisionspec_list is None:
1930
elif len(revisionspec_list) == 1:
1931
rev1 = rev2 = revisionspec_list[0].in_history(branch)
1932
elif len(revisionspec_list) == 2:
1933
if revisionspec_list[1].get_branch() != revisionspec_list[0
1935
# b is taken from revision[0].get_branch(), and
1936
# show_log will use its revision_history. Having
1937
# different branches will lead to weird behaviors.
1938
raise errors.BzrCommandError(
1939
"bzr %s doesn't accept two revisions in different"
1940
" branches." % command_name)
1941
rev1 = revisionspec_list[0].in_history(branch)
1942
rev2 = revisionspec_list[1].in_history(branch)
1944
raise errors.BzrCommandError(
1945
'bzr %s --revision takes one or two values.' % command_name)
1948
def get_log_format(long=False, short=False, line=False, default='long'):
1949
log_format = default
1953
log_format = 'short'
1959
class cmd_touching_revisions(Command):
1960
"""Return revision-ids which affected a particular file.
1962
A more user-friendly interface is "bzr log FILE".
1966
takes_args = ["filename"]
1969
def run(self, filename):
1970
tree, relpath = WorkingTree.open_containing(filename)
1972
file_id = tree.path2id(relpath)
1973
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1974
self.outf.write("%6d %s\n" % (revno, what))
1977
class cmd_ls(Command):
1978
"""List files in a tree.
1981
_see_also = ['status', 'cat']
1982
takes_args = ['path?']
1983
# TODO: Take a revision or remote path and list that tree instead.
1987
Option('non-recursive',
1988
help='Don\'t recurse into subdirectories.'),
1990
help='Print paths relative to the root of the branch.'),
1991
Option('unknown', help='Print unknown files.'),
1992
Option('versioned', help='Print versioned files.',
1994
Option('ignored', help='Print ignored files.'),
1996
help='Write an ascii NUL (\\0) separator '
1997
'between files rather than a newline.'),
1999
help='List entries of a particular kind: file, directory, symlink.',
2004
def run(self, revision=None, verbose=False,
2005
non_recursive=False, from_root=False,
2006
unknown=False, versioned=False, ignored=False,
2007
null=False, kind=None, show_ids=False, path=None):
2009
if kind and kind not in ('file', 'directory', 'symlink'):
2010
raise errors.BzrCommandError('invalid kind specified')
2012
if verbose and null:
2013
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2014
all = not (unknown or versioned or ignored)
2016
selection = {'I':ignored, '?':unknown, 'V':versioned}
2023
raise errors.BzrCommandError('cannot specify both --from-root'
2027
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2033
if revision is not None or tree is None:
2034
tree = _get_one_revision_tree('ls', revision, branch=branch)
2038
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2039
if fp.startswith(relpath):
2040
fp = osutils.pathjoin(prefix, fp[len(relpath):])
2041
if non_recursive and '/' in fp:
2043
if not all and not selection[fc]:
2045
if kind is not None and fkind != kind:
2047
kindch = entry.kind_character()
2048
outstring = fp + kindch
2050
outstring = '%-8s %s' % (fc, outstring)
2051
if show_ids and fid is not None:
2052
outstring = "%-50s %s" % (outstring, fid)
2053
self.outf.write(outstring + '\n')
2055
self.outf.write(fp + '\0')
2058
self.outf.write(fid)
2059
self.outf.write('\0')
2067
self.outf.write('%-50s %s\n' % (outstring, my_id))
2069
self.outf.write(outstring + '\n')
2074
class cmd_unknowns(Command):
2075
"""List unknown files.
2083
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2084
self.outf.write(osutils.quotefn(f) + '\n')
2087
class cmd_ignore(Command):
2088
"""Ignore specified files or patterns.
2090
See ``bzr help patterns`` for details on the syntax of patterns.
2092
To remove patterns from the ignore list, edit the .bzrignore file.
2093
After adding, editing or deleting that file either indirectly by
2094
using this command or directly by using an editor, be sure to commit
2097
Note: ignore patterns containing shell wildcards must be quoted from
2101
Ignore the top level Makefile::
2103
bzr ignore ./Makefile
2105
Ignore class files in all directories::
2107
bzr ignore "*.class"
2109
Ignore .o files under the lib directory::
2111
bzr ignore "lib/**/*.o"
2113
Ignore .o files under the lib directory::
2115
bzr ignore "RE:lib/.*\.o"
2117
Ignore everything but the "debian" toplevel directory::
2119
bzr ignore "RE:(?!debian/).*"
2122
_see_also = ['status', 'ignored', 'patterns']
2123
takes_args = ['name_pattern*']
2125
Option('old-default-rules',
2126
help='Write out the ignore rules bzr < 0.9 always used.')
2129
def run(self, name_pattern_list=None, old_default_rules=None):
2130
from bzrlib import ignores
2131
if old_default_rules is not None:
2132
# dump the rules and exit
2133
for pattern in ignores.OLD_DEFAULTS:
2136
if not name_pattern_list:
2137
raise errors.BzrCommandError("ignore requires at least one "
2138
"NAME_PATTERN or --old-default-rules")
2139
name_pattern_list = [globbing.normalize_pattern(p)
2140
for p in name_pattern_list]
2141
for name_pattern in name_pattern_list:
2142
if (name_pattern[0] == '/' or
2143
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2144
raise errors.BzrCommandError(
2145
"NAME_PATTERN should not be an absolute path")
2146
tree, relpath = WorkingTree.open_containing(u'.')
2147
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2148
ignored = globbing.Globster(name_pattern_list)
2151
for entry in tree.list_files():
2155
if ignored.match(filename):
2156
matches.append(filename.encode('utf-8'))
2158
if len(matches) > 0:
2159
print "Warning: the following files are version controlled and" \
2160
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2163
class cmd_ignored(Command):
2164
"""List ignored files and the patterns that matched them.
2166
List all the ignored files and the ignore pattern that caused the file to
2169
Alternatively, to list just the files::
2174
encoding_type = 'replace'
2175
_see_also = ['ignore', 'ls']
2179
tree = WorkingTree.open_containing(u'.')[0]
2182
for path, file_class, kind, file_id, entry in tree.list_files():
2183
if file_class != 'I':
2185
## XXX: Slightly inefficient since this was already calculated
2186
pat = tree.is_ignored(path)
2187
self.outf.write('%-50s %s\n' % (path, pat))
2192
class cmd_lookup_revision(Command):
2193
"""Lookup the revision-id from a revision-number
2196
bzr lookup-revision 33
2199
takes_args = ['revno']
2202
def run(self, revno):
2206
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2208
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2211
class cmd_export(Command):
2212
"""Export current or past revision to a destination directory or archive.
2214
If no revision is specified this exports the last committed revision.
2216
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2217
given, try to find the format with the extension. If no extension
2218
is found exports to a directory (equivalent to --format=dir).
2220
If root is supplied, it will be used as the root directory inside
2221
container formats (tar, zip, etc). If it is not supplied it will default
2222
to the exported filename. The root option has no effect for 'dir' format.
2224
If branch is omitted then the branch containing the current working
2225
directory will be used.
2227
Note: Export of tree with non-ASCII filenames to zip is not supported.
2229
================= =========================
2230
Supported formats Autodetected by extension
2231
================= =========================
2234
tbz2 .tar.bz2, .tbz2
2237
================= =========================
2239
takes_args = ['dest', 'branch_or_subdir?']
2242
help="Type of file to export to.",
2247
help="Name of the root directory inside the exported file."),
2249
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2251
from bzrlib.export import export
2253
if branch_or_subdir is None:
2254
tree = WorkingTree.open_containing(u'.')[0]
2258
b, subdir = Branch.open_containing(branch_or_subdir)
2261
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2263
export(rev_tree, dest, format, root, subdir)
2264
except errors.NoSuchExportFormat, e:
2265
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2268
class cmd_cat(Command):
2269
"""Write the contents of a file as of a given revision to standard output.
2271
If no revision is nominated, the last revision is used.
2273
Note: Take care to redirect standard output when using this command on a
2279
Option('name-from-revision', help='The path name in the old tree.'),
2282
takes_args = ['filename']
2283
encoding_type = 'exact'
2286
def run(self, filename, revision=None, name_from_revision=False):
2287
if revision is not None and len(revision) != 1:
2288
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2289
" one revision specifier")
2290
tree, branch, relpath = \
2291
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2294
return self._run(tree, branch, relpath, filename, revision,
2299
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2301
tree = b.basis_tree()
2302
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2304
cur_file_id = tree.path2id(relpath)
2305
old_file_id = rev_tree.path2id(relpath)
2307
if name_from_revision:
2308
if old_file_id is None:
2309
raise errors.BzrCommandError(
2310
"%r is not present in revision %s" % (
2311
filename, rev_tree.get_revision_id()))
2313
content = rev_tree.get_file_text(old_file_id)
2314
elif cur_file_id is not None:
2315
content = rev_tree.get_file_text(cur_file_id)
2316
elif old_file_id is not None:
2317
content = rev_tree.get_file_text(old_file_id)
2319
raise errors.BzrCommandError(
2320
"%r is not present in revision %s" % (
2321
filename, rev_tree.get_revision_id()))
2322
self.outf.write(content)
2325
class cmd_local_time_offset(Command):
2326
"""Show the offset in seconds from GMT to local time."""
2330
print osutils.local_time_offset()
2334
class cmd_commit(Command):
2335
"""Commit changes into a new revision.
2337
If no arguments are given, the entire tree is committed.
2339
If selected files are specified, only changes to those files are
2340
committed. If a directory is specified then the directory and everything
2341
within it is committed.
2343
When excludes are given, they take precedence over selected files.
2344
For example, too commit only changes within foo, but not changes within
2347
bzr commit foo -x foo/bar
2349
If author of the change is not the same person as the committer, you can
2350
specify the author's name using the --author option. The name should be
2351
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2353
A selected-file commit may fail in some cases where the committed
2354
tree would be invalid. Consider::
2359
bzr commit foo -m "committing foo"
2360
bzr mv foo/bar foo/baz
2363
bzr commit foo/bar -m "committing bar but not baz"
2365
In the example above, the last commit will fail by design. This gives
2366
the user the opportunity to decide whether they want to commit the
2367
rename at the same time, separately first, or not at all. (As a general
2368
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2370
Note: A selected-file commit after a merge is not yet supported.
2372
# TODO: Run hooks on tree to-be-committed, and after commit.
2374
# TODO: Strict commit that fails if there are deleted files.
2375
# (what does "deleted files" mean ??)
2377
# TODO: Give better message for -s, --summary, used by tla people
2379
# XXX: verbose currently does nothing
2381
_see_also = ['bugs', 'uncommit']
2382
takes_args = ['selected*']
2384
ListOption('exclude', type=str, short_name='x',
2385
help="Do not consider changes made to a given path."),
2386
Option('message', type=unicode,
2388
help="Description of the new revision."),
2391
help='Commit even if nothing has changed.'),
2392
Option('file', type=str,
2395
help='Take commit message from this file.'),
2397
help="Refuse to commit if there are unknown "
2398
"files in the working tree."),
2399
ListOption('fixes', type=str,
2400
help="Mark a bug as being fixed by this revision."),
2401
Option('author', type=unicode,
2402
help="Set the author's name, if it's different "
2403
"from the committer."),
2405
help="Perform a local commit in a bound "
2406
"branch. Local commits are not pushed to "
2407
"the master branch until a normal commit "
2411
help='When no message is supplied, show the diff along'
2412
' with the status summary in the message editor.'),
2414
aliases = ['ci', 'checkin']
2416
def _get_bug_fix_properties(self, fixes, branch):
2418
# Configure the properties for bug fixing attributes.
2419
for fixed_bug in fixes:
2420
tokens = fixed_bug.split(':')
2421
if len(tokens) != 2:
2422
raise errors.BzrCommandError(
2423
"Invalid bug %s. Must be in the form of 'tag:id'. "
2424
"Commit refused." % fixed_bug)
2425
tag, bug_id = tokens
2427
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2428
except errors.UnknownBugTrackerAbbreviation:
2429
raise errors.BzrCommandError(
2430
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2431
except errors.MalformedBugIdentifier:
2432
raise errors.BzrCommandError(
2433
"Invalid bug identifier for %s. Commit refused."
2435
properties.append('%s fixed' % bug_url)
2436
return '\n'.join(properties)
2438
def run(self, message=None, file=None, verbose=False, selected_list=None,
2439
unchanged=False, strict=False, local=False, fixes=None,
2440
author=None, show_diff=False, exclude=None):
2441
from bzrlib.errors import (
2446
from bzrlib.msgeditor import (
2447
edit_commit_message_encoded,
2448
generate_commit_message_template,
2449
make_commit_message_template_encoded
2452
# TODO: Need a blackbox test for invoking the external editor; may be
2453
# slightly problematic to run this cross-platform.
2455
# TODO: do more checks that the commit will succeed before
2456
# spending the user's valuable time typing a commit message.
2460
tree, selected_list = tree_files(selected_list)
2461
if selected_list == ['']:
2462
# workaround - commit of root of tree should be exactly the same
2463
# as just default commit in that tree, and succeed even though
2464
# selected-file merge commit is not done yet
2467
selected_list = tree.get_canonical_inventory_paths(selected_list)
2471
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2473
properties['bugs'] = bug_property
2475
if local and not tree.branch.get_bound_location():
2476
raise errors.LocalRequiresBoundBranch()
2478
def get_message(commit_obj):
2479
"""Callback to get commit message"""
2480
my_message = message
2481
if my_message is None and not file:
2482
t = make_commit_message_template_encoded(tree,
2483
selected_list, diff=show_diff,
2484
output_encoding=osutils.get_user_encoding())
2485
start_message = generate_commit_message_template(commit_obj)
2486
my_message = edit_commit_message_encoded(t,
2487
start_message=start_message)
2488
if my_message is None:
2489
raise errors.BzrCommandError("please specify a commit"
2490
" message with either --message or --file")
2491
elif my_message and file:
2492
raise errors.BzrCommandError(
2493
"please specify either --message or --file")
2495
my_message = codecs.open(file, 'rt',
2496
osutils.get_user_encoding()).read()
2497
if my_message == "":
2498
raise errors.BzrCommandError("empty commit message specified")
2502
tree.commit(message_callback=get_message,
2503
specific_files=selected_list,
2504
allow_pointless=unchanged, strict=strict, local=local,
2505
reporter=None, verbose=verbose, revprops=properties,
2507
exclude=safe_relpath_files(tree, exclude))
2508
except PointlessCommit:
2509
# FIXME: This should really happen before the file is read in;
2510
# perhaps prepare the commit; get the message; then actually commit
2511
raise errors.BzrCommandError("no changes to commit."
2512
" use --unchanged to commit anyhow")
2513
except ConflictsInTree:
2514
raise errors.BzrCommandError('Conflicts detected in working '
2515
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2517
except StrictCommitFailed:
2518
raise errors.BzrCommandError("Commit refused because there are"
2519
" unknown files in the working tree.")
2520
except errors.BoundBranchOutOfDate, e:
2521
raise errors.BzrCommandError(str(e) + "\n"
2522
'To commit to master branch, run update and then commit.\n'
2523
'You can also pass --local to commit to continue working '
2527
class cmd_check(Command):
2528
"""Validate working tree structure, branch consistency and repository history.
2530
This command checks various invariants about branch and repository storage
2531
to detect data corruption or bzr bugs.
2533
The working tree and branch checks will only give output if a problem is
2534
detected. The output fields of the repository check are:
2536
revisions: This is just the number of revisions checked. It doesn't
2538
versionedfiles: This is just the number of versionedfiles checked. It
2539
doesn't indicate a problem.
2540
unreferenced ancestors: Texts that are ancestors of other texts, but
2541
are not properly referenced by the revision ancestry. This is a
2542
subtle problem that Bazaar can work around.
2543
unique file texts: This is the total number of unique file contents
2544
seen in the checked revisions. It does not indicate a problem.
2545
repeated file texts: This is the total number of repeated texts seen
2546
in the checked revisions. Texts can be repeated when their file
2547
entries are modified, but the file contents are not. It does not
2550
If no restrictions are specified, all Bazaar data that is found at the given
2551
location will be checked.
2555
Check the tree and branch at 'foo'::
2557
bzr check --tree --branch foo
2559
Check only the repository at 'bar'::
2561
bzr check --repo bar
2563
Check everything at 'baz'::
2568
_see_also = ['reconcile']
2569
takes_args = ['path?']
2570
takes_options = ['verbose',
2571
Option('branch', help="Check the branch related to the"
2572
" current directory."),
2573
Option('repo', help="Check the repository related to the"
2574
" current directory."),
2575
Option('tree', help="Check the working tree related to"
2576
" the current directory.")]
2578
def run(self, path=None, verbose=False, branch=False, repo=False,
2580
from bzrlib.check import check_dwim
2583
if not branch and not repo and not tree:
2584
branch = repo = tree = True
2585
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2588
class cmd_upgrade(Command):
2589
"""Upgrade branch storage to current format.
2591
The check command or bzr developers may sometimes advise you to run
2592
this command. When the default format has changed you may also be warned
2593
during other operations to upgrade.
2596
_see_also = ['check']
2597
takes_args = ['url?']
2599
RegistryOption('format',
2600
help='Upgrade to a specific format. See "bzr help'
2601
' formats" for details.',
2602
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2603
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2604
value_switches=True, title='Branch format'),
2607
def run(self, url='.', format=None):
2608
from bzrlib.upgrade import upgrade
2610
format = bzrdir.format_registry.make_bzrdir('default')
2611
upgrade(url, format)
2614
class cmd_whoami(Command):
2615
"""Show or set bzr user id.
2618
Show the email of the current user::
2622
Set the current user::
2624
bzr whoami "Frank Chu <fchu@example.com>"
2626
takes_options = [ Option('email',
2627
help='Display email address only.'),
2629
help='Set identity for the current branch instead of '
2632
takes_args = ['name?']
2633
encoding_type = 'replace'
2636
def run(self, email=False, branch=False, name=None):
2638
# use branch if we're inside one; otherwise global config
2640
c = Branch.open_containing('.')[0].get_config()
2641
except errors.NotBranchError:
2642
c = config.GlobalConfig()
2644
self.outf.write(c.user_email() + '\n')
2646
self.outf.write(c.username() + '\n')
2649
# display a warning if an email address isn't included in the given name.
2651
config.extract_email_address(name)
2652
except errors.NoEmailInUsername, e:
2653
warning('"%s" does not seem to contain an email address. '
2654
'This is allowed, but not recommended.', name)
2656
# use global config unless --branch given
2658
c = Branch.open_containing('.')[0].get_config()
2660
c = config.GlobalConfig()
2661
c.set_user_option('email', name)
2664
class cmd_nick(Command):
2665
"""Print or set the branch nickname.
2667
If unset, the tree root directory name is used as the nickname.
2668
To print the current nickname, execute with no argument.
2670
Bound branches use the nickname of its master branch unless it is set
2674
_see_also = ['info']
2675
takes_args = ['nickname?']
2676
def run(self, nickname=None):
2677
branch = Branch.open_containing(u'.')[0]
2678
if nickname is None:
2679
self.printme(branch)
2681
branch.nick = nickname
2684
def printme(self, branch):
2688
class cmd_alias(Command):
2689
"""Set/unset and display aliases.
2692
Show the current aliases::
2696
Show the alias specified for 'll'::
2700
Set an alias for 'll'::
2702
bzr alias ll="log --line -r-10..-1"
2704
To remove an alias for 'll'::
2706
bzr alias --remove ll
2709
takes_args = ['name?']
2711
Option('remove', help='Remove the alias.'),
2714
def run(self, name=None, remove=False):
2716
self.remove_alias(name)
2718
self.print_aliases()
2720
equal_pos = name.find('=')
2722
self.print_alias(name)
2724
self.set_alias(name[:equal_pos], name[equal_pos+1:])
2726
def remove_alias(self, alias_name):
2727
if alias_name is None:
2728
raise errors.BzrCommandError(
2729
'bzr alias --remove expects an alias to remove.')
2730
# If alias is not found, print something like:
2731
# unalias: foo: not found
2732
c = config.GlobalConfig()
2733
c.unset_alias(alias_name)
2736
def print_aliases(self):
2737
"""Print out the defined aliases in a similar format to bash."""
2738
aliases = config.GlobalConfig().get_aliases()
2739
for key, value in sorted(aliases.iteritems()):
2740
self.outf.write('bzr alias %s="%s"\n' % (key, value))
2743
def print_alias(self, alias_name):
2744
from bzrlib.commands import get_alias
2745
alias = get_alias(alias_name)
2747
self.outf.write("bzr alias: %s: not found\n" % alias_name)
2750
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2752
def set_alias(self, alias_name, alias_command):
2753
"""Save the alias in the global config."""
2754
c = config.GlobalConfig()
2755
c.set_alias(alias_name, alias_command)
2758
class cmd_selftest(Command):
2759
"""Run internal test suite.
2761
If arguments are given, they are regular expressions that say which tests
2762
should run. Tests matching any expression are run, and other tests are
2765
Alternatively if --first is given, matching tests are run first and then
2766
all other tests are run. This is useful if you have been working in a
2767
particular area, but want to make sure nothing else was broken.
2769
If --exclude is given, tests that match that regular expression are
2770
excluded, regardless of whether they match --first or not.
2772
To help catch accidential dependencies between tests, the --randomize
2773
option is useful. In most cases, the argument used is the word 'now'.
2774
Note that the seed used for the random number generator is displayed
2775
when this option is used. The seed can be explicitly passed as the
2776
argument to this option if required. This enables reproduction of the
2777
actual ordering used if and when an order sensitive problem is encountered.
2779
If --list-only is given, the tests that would be run are listed. This is
2780
useful when combined with --first, --exclude and/or --randomize to
2781
understand their impact. The test harness reports "Listed nn tests in ..."
2782
instead of "Ran nn tests in ..." when list mode is enabled.
2784
If the global option '--no-plugins' is given, plugins are not loaded
2785
before running the selftests. This has two effects: features provided or
2786
modified by plugins will not be tested, and tests provided by plugins will
2789
Tests that need working space on disk use a common temporary directory,
2790
typically inside $TMPDIR or /tmp.
2793
Run only tests relating to 'ignore'::
2797
Disable plugins and list tests as they're run::
2799
bzr --no-plugins selftest -v
2801
# NB: this is used from the class without creating an instance, which is
2802
# why it does not have a self parameter.
2803
def get_transport_type(typestring):
2804
"""Parse and return a transport specifier."""
2805
if typestring == "sftp":
2806
from bzrlib.transport.sftp import SFTPAbsoluteServer
2807
return SFTPAbsoluteServer
2808
if typestring == "memory":
2809
from bzrlib.transport.memory import MemoryServer
2811
if typestring == "fakenfs":
2812
from bzrlib.transport.fakenfs import FakeNFSServer
2813
return FakeNFSServer
2814
msg = "No known transport type %s. Supported types are: sftp\n" %\
2816
raise errors.BzrCommandError(msg)
2819
takes_args = ['testspecs*']
2820
takes_options = ['verbose',
2822
help='Stop when one test fails.',
2826
help='Use a different transport by default '
2827
'throughout the test suite.',
2828
type=get_transport_type),
2830
help='Run the benchmarks rather than selftests.'),
2831
Option('lsprof-timed',
2832
help='Generate lsprof output for benchmarked'
2833
' sections of code.'),
2834
Option('cache-dir', type=str,
2835
help='Cache intermediate benchmark output in this '
2838
help='Run all tests, but run specified tests first.',
2842
help='List the tests instead of running them.'),
2843
Option('randomize', type=str, argname="SEED",
2844
help='Randomize the order of tests using the given'
2845
' seed or "now" for the current time.'),
2846
Option('exclude', type=str, argname="PATTERN",
2848
help='Exclude tests that match this regular'
2850
Option('strict', help='Fail on missing dependencies or '
2852
Option('load-list', type=str, argname='TESTLISTFILE',
2853
help='Load a test id list from a text file.'),
2854
ListOption('debugflag', type=str, short_name='E',
2855
help='Turn on a selftest debug flag.'),
2856
ListOption('starting-with', type=str, argname='TESTID',
2857
param_name='starting_with', short_name='s',
2859
'Load only the tests starting with TESTID.'),
2861
encoding_type = 'replace'
2863
def run(self, testspecs_list=None, verbose=False, one=False,
2864
transport=None, benchmark=None,
2865
lsprof_timed=None, cache_dir=None,
2866
first=False, list_only=False,
2867
randomize=None, exclude=None, strict=False,
2868
load_list=None, debugflag=None, starting_with=None):
2869
from bzrlib.tests import selftest
2870
import bzrlib.benchmarks as benchmarks
2871
from bzrlib.benchmarks import tree_creator
2873
# Make deprecation warnings visible, unless -Werror is set
2874
symbol_versioning.activate_deprecation_warnings(override=False)
2876
if cache_dir is not None:
2877
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2879
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2880
print ' %s (%s python%s)' % (
2882
bzrlib.version_string,
2883
bzrlib._format_version_tuple(sys.version_info),
2886
if testspecs_list is not None:
2887
pattern = '|'.join(testspecs_list)
2891
test_suite_factory = benchmarks.test_suite
2892
# Unless user explicitly asks for quiet, be verbose in benchmarks
2893
verbose = not is_quiet()
2894
# TODO: should possibly lock the history file...
2895
benchfile = open(".perf_history", "at", buffering=1)
2897
test_suite_factory = None
2900
result = selftest(verbose=verbose,
2902
stop_on_failure=one,
2903
transport=transport,
2904
test_suite_factory=test_suite_factory,
2905
lsprof_timed=lsprof_timed,
2906
bench_history=benchfile,
2907
matching_tests_first=first,
2908
list_only=list_only,
2909
random_seed=randomize,
2910
exclude_pattern=exclude,
2912
load_list=load_list,
2913
debug_flags=debugflag,
2914
starting_with=starting_with,
2917
if benchfile is not None:
2920
note('tests passed')
2922
note('tests failed')
2923
return int(not result)
2926
class cmd_version(Command):
2927
"""Show version of bzr."""
2929
encoding_type = 'replace'
2931
Option("short", help="Print just the version number."),
2935
def run(self, short=False):
2936
from bzrlib.version import show_version
2938
self.outf.write(bzrlib.version_string + '\n')
2940
show_version(to_file=self.outf)
2943
class cmd_rocks(Command):
2944
"""Statement of optimism."""
2950
print "It sure does!"
2953
class cmd_find_merge_base(Command):
2954
"""Find and print a base revision for merging two branches."""
2955
# TODO: Options to specify revisions on either side, as if
2956
# merging only part of the history.
2957
takes_args = ['branch', 'other']
2961
def run(self, branch, other):
2962
from bzrlib.revision import ensure_null
2964
branch1 = Branch.open_containing(branch)[0]
2965
branch2 = Branch.open_containing(other)[0]
2970
last1 = ensure_null(branch1.last_revision())
2971
last2 = ensure_null(branch2.last_revision())
2973
graph = branch1.repository.get_graph(branch2.repository)
2974
base_rev_id = graph.find_unique_lca(last1, last2)
2976
print 'merge base is revision %s' % base_rev_id
2983
class cmd_merge(Command):
2984
"""Perform a three-way merge.
2986
The source of the merge can be specified either in the form of a branch,
2987
or in the form of a path to a file containing a merge directive generated
2988
with bzr send. If neither is specified, the default is the upstream branch
2989
or the branch most recently merged using --remember.
2991
When merging a branch, by default the tip will be merged. To pick a different
2992
revision, pass --revision. If you specify two values, the first will be used as
2993
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2994
available revisions, like this is commonly referred to as "cherrypicking".
2996
Revision numbers are always relative to the branch being merged.
2998
By default, bzr will try to merge in all new work from the other
2999
branch, automatically determining an appropriate base. If this
3000
fails, you may need to give an explicit base.
3002
Merge will do its best to combine the changes in two branches, but there
3003
are some kinds of problems only a human can fix. When it encounters those,
3004
it will mark a conflict. A conflict means that you need to fix something,
3005
before you should commit.
3007
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
3009
If there is no default branch set, the first merge will set it. After
3010
that, you can omit the branch to use the default. To change the
3011
default, use --remember. The value will only be saved if the remote
3012
location can be accessed.
3014
The results of the merge are placed into the destination working
3015
directory, where they can be reviewed (with bzr diff), tested, and then
3016
committed to record the result of the merge.
3018
merge refuses to run if there are any uncommitted changes, unless
3022
To merge the latest revision from bzr.dev::
3024
bzr merge ../bzr.dev
3026
To merge changes up to and including revision 82 from bzr.dev::
3028
bzr merge -r 82 ../bzr.dev
3030
To merge the changes introduced by 82, without previous changes::
3032
bzr merge -r 81..82 ../bzr.dev
3034
To apply a merge directive contained in in /tmp/merge:
3036
bzr merge /tmp/merge
3039
encoding_type = 'exact'
3040
_see_also = ['update', 'remerge', 'status-flags']
3041
takes_args = ['location?']
3046
help='Merge even if the destination tree has uncommitted changes.'),
3050
Option('show-base', help="Show base revision text in "
3052
Option('uncommitted', help='Apply uncommitted changes'
3053
' from a working copy, instead of branch changes.'),
3054
Option('pull', help='If the destination is already'
3055
' completely merged into the source, pull from the'
3056
' source rather than merging. When this happens,'
3057
' you do not need to commit the result.'),
3059
help='Branch to merge into, '
3060
'rather than the one containing the working directory.',
3064
Option('preview', help='Instead of merging, show a diff of the merge.')
3067
def run(self, location=None, revision=None, force=False,
3068
merge_type=None, show_base=False, reprocess=None, remember=False,
3069
uncommitted=False, pull=False,
3073
if merge_type is None:
3074
merge_type = _mod_merge.Merge3Merger
3076
if directory is None: directory = u'.'
3077
possible_transports = []
3079
allow_pending = True
3080
verified = 'inapplicable'
3081
tree = WorkingTree.open_containing(directory)[0]
3082
change_reporter = delta._ChangeReporter(
3083
unversioned_filter=tree.is_ignored)
3086
pb = ui.ui_factory.nested_progress_bar()
3087
cleanups.append(pb.finished)
3089
cleanups.append(tree.unlock)
3090
if location is not None:
3092
mergeable = bundle.read_mergeable_from_url(location,
3093
possible_transports=possible_transports)
3094
except errors.NotABundle:
3098
raise errors.BzrCommandError('Cannot use --uncommitted'
3099
' with bundles or merge directives.')
3101
if revision is not None:
3102
raise errors.BzrCommandError(
3103
'Cannot use -r with merge directives or bundles')
3104
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3107
if merger is None and uncommitted:
3108
if revision is not None and len(revision) > 0:
3109
raise errors.BzrCommandError('Cannot use --uncommitted and'
3110
' --revision at the same time.')
3111
location = self._select_branch_location(tree, location)[0]
3112
other_tree, other_path = WorkingTree.open_containing(location)
3113
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3115
allow_pending = False
3116
if other_path != '':
3117
merger.interesting_files = [other_path]
3120
merger, allow_pending = self._get_merger_from_branch(tree,
3121
location, revision, remember, possible_transports, pb)
3123
merger.merge_type = merge_type
3124
merger.reprocess = reprocess
3125
merger.show_base = show_base
3126
self.sanity_check_merger(merger)
3127
if (merger.base_rev_id == merger.other_rev_id and
3128
merger.other_rev_id is not None):
3129
note('Nothing to do.')
3132
if merger.interesting_files is not None:
3133
raise errors.BzrCommandError('Cannot pull individual files')
3134
if (merger.base_rev_id == tree.last_revision()):
3135
result = tree.pull(merger.other_branch, False,
3136
merger.other_rev_id)
3137
result.report(self.outf)
3139
merger.check_basis(not force)
3141
return self._do_preview(merger)
3143
return self._do_merge(merger, change_reporter, allow_pending,
3146
for cleanup in reversed(cleanups):
3149
def _do_preview(self, merger):
3150
from bzrlib.diff import show_diff_trees
3151
tree_merger = merger.make_merger()
3152
tt = tree_merger.make_preview_transform()
3154
result_tree = tt.get_preview_tree()
3155
show_diff_trees(merger.this_tree, result_tree, self.outf,
3156
old_label='', new_label='')
3160
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3161
merger.change_reporter = change_reporter
3162
conflict_count = merger.do_merge()
3164
merger.set_pending()
3165
if verified == 'failed':
3166
warning('Preview patch does not match changes')
3167
if conflict_count != 0:
3172
def sanity_check_merger(self, merger):
3173
if (merger.show_base and
3174
not merger.merge_type is _mod_merge.Merge3Merger):
3175
raise errors.BzrCommandError("Show-base is not supported for this"
3176
" merge type. %s" % merger.merge_type)
3177
if merger.reprocess is None:
3178
if merger.show_base:
3179
merger.reprocess = False
3181
# Use reprocess if the merger supports it
3182
merger.reprocess = merger.merge_type.supports_reprocess
3183
if merger.reprocess and not merger.merge_type.supports_reprocess:
3184
raise errors.BzrCommandError("Conflict reduction is not supported"
3185
" for merge type %s." %
3187
if merger.reprocess and merger.show_base:
3188
raise errors.BzrCommandError("Cannot do conflict reduction and"
3191
def _get_merger_from_branch(self, tree, location, revision, remember,
3192
possible_transports, pb):
3193
"""Produce a merger from a location, assuming it refers to a branch."""
3194
from bzrlib.tag import _merge_tags_if_possible
3195
# find the branch locations
3196
other_loc, user_location = self._select_branch_location(tree, location,
3198
if revision is not None and len(revision) == 2:
3199
base_loc, _unused = self._select_branch_location(tree,
3200
location, revision, 0)
3202
base_loc = other_loc
3204
other_branch, other_path = Branch.open_containing(other_loc,
3205
possible_transports)
3206
if base_loc == other_loc:
3207
base_branch = other_branch
3209
base_branch, base_path = Branch.open_containing(base_loc,
3210
possible_transports)
3211
# Find the revision ids
3212
if revision is None or len(revision) < 1 or revision[-1] is None:
3213
other_revision_id = _mod_revision.ensure_null(
3214
other_branch.last_revision())
3216
other_revision_id = revision[-1].as_revision_id(other_branch)
3217
if (revision is not None and len(revision) == 2
3218
and revision[0] is not None):
3219
base_revision_id = revision[0].as_revision_id(base_branch)
3221
base_revision_id = None
3222
# Remember where we merge from
3223
if ((remember or tree.branch.get_submit_branch() is None) and
3224
user_location is not None):
3225
tree.branch.set_submit_branch(other_branch.base)
3226
_merge_tags_if_possible(other_branch, tree.branch)
3227
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3228
other_revision_id, base_revision_id, other_branch, base_branch)
3229
if other_path != '':
3230
allow_pending = False
3231
merger.interesting_files = [other_path]
3233
allow_pending = True
3234
return merger, allow_pending
3236
def _select_branch_location(self, tree, user_location, revision=None,
3238
"""Select a branch location, according to possible inputs.
3240
If provided, branches from ``revision`` are preferred. (Both
3241
``revision`` and ``index`` must be supplied.)
3243
Otherwise, the ``location`` parameter is used. If it is None, then the
3244
``submit`` or ``parent`` location is used, and a note is printed.
3246
:param tree: The working tree to select a branch for merging into
3247
:param location: The location entered by the user
3248
:param revision: The revision parameter to the command
3249
:param index: The index to use for the revision parameter. Negative
3250
indices are permitted.
3251
:return: (selected_location, user_location). The default location
3252
will be the user-entered location.
3254
if (revision is not None and index is not None
3255
and revision[index] is not None):
3256
branch = revision[index].get_branch()
3257
if branch is not None:
3258
return branch, branch
3259
if user_location is None:
3260
location = self._get_remembered(tree, 'Merging from')
3262
location = user_location
3263
return location, user_location
3265
def _get_remembered(self, tree, verb_string):
3266
"""Use tree.branch's parent if none was supplied.
3268
Report if the remembered location was used.
3270
stored_location = tree.branch.get_submit_branch()
3271
stored_location_type = "submit"
3272
if stored_location is None:
3273
stored_location = tree.branch.get_parent()
3274
stored_location_type = "parent"
3275
mutter("%s", stored_location)
3276
if stored_location is None:
3277
raise errors.BzrCommandError("No location specified or remembered")
3278
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3279
note(u"%s remembered %s location %s", verb_string,
3280
stored_location_type, display_url)
3281
return stored_location
3284
class cmd_remerge(Command):
3287
Use this if you want to try a different merge technique while resolving
3288
conflicts. Some merge techniques are better than others, and remerge
3289
lets you try different ones on different files.
3291
The options for remerge have the same meaning and defaults as the ones for
3292
merge. The difference is that remerge can (only) be run when there is a
3293
pending merge, and it lets you specify particular files.
3296
Re-do the merge of all conflicted files, and show the base text in
3297
conflict regions, in addition to the usual THIS and OTHER texts::
3299
bzr remerge --show-base
3301
Re-do the merge of "foobar", using the weave merge algorithm, with
3302
additional processing to reduce the size of conflict regions::
3304
bzr remerge --merge-type weave --reprocess foobar
3306
takes_args = ['file*']
3311
help="Show base revision text in conflicts."),
3314
def run(self, file_list=None, merge_type=None, show_base=False,
3316
if merge_type is None:
3317
merge_type = _mod_merge.Merge3Merger
3318
tree, file_list = tree_files(file_list)
3321
parents = tree.get_parent_ids()
3322
if len(parents) != 2:
3323
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3324
" merges. Not cherrypicking or"
3326
repository = tree.branch.repository
3327
interesting_ids = None
3329
conflicts = tree.conflicts()
3330
if file_list is not None:
3331
interesting_ids = set()
3332
for filename in file_list:
3333
file_id = tree.path2id(filename)
3335
raise errors.NotVersionedError(filename)
3336
interesting_ids.add(file_id)
3337
if tree.kind(file_id) != "directory":
3340
for name, ie in tree.inventory.iter_entries(file_id):
3341
interesting_ids.add(ie.file_id)
3342
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3344
# Remerge only supports resolving contents conflicts
3345
allowed_conflicts = ('text conflict', 'contents conflict')
3346
restore_files = [c.path for c in conflicts
3347
if c.typestring in allowed_conflicts]
3348
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3349
tree.set_conflicts(ConflictList(new_conflicts))
3350
if file_list is not None:
3351
restore_files = file_list
3352
for filename in restore_files:
3354
restore(tree.abspath(filename))
3355
except errors.NotConflicted:
3357
# Disable pending merges, because the file texts we are remerging
3358
# have not had those merges performed. If we use the wrong parents
3359
# list, we imply that the working tree text has seen and rejected
3360
# all the changes from the other tree, when in fact those changes
3361
# have not yet been seen.
3362
pb = ui.ui_factory.nested_progress_bar()
3363
tree.set_parent_ids(parents[:1])
3365
merger = _mod_merge.Merger.from_revision_ids(pb,
3367
merger.interesting_ids = interesting_ids
3368
merger.merge_type = merge_type
3369
merger.show_base = show_base
3370
merger.reprocess = reprocess
3371
conflicts = merger.do_merge()
3373
tree.set_parent_ids(parents)
3383
class cmd_revert(Command):
3384
"""Revert files to a previous revision.
3386
Giving a list of files will revert only those files. Otherwise, all files
3387
will be reverted. If the revision is not specified with '--revision', the
3388
last committed revision is used.
3390
To remove only some changes, without reverting to a prior version, use
3391
merge instead. For example, "merge . --revision -2..-3" will remove the
3392
changes introduced by -2, without affecting the changes introduced by -1.
3393
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3395
By default, any files that have been manually changed will be backed up
3396
first. (Files changed only by merge are not backed up.) Backup files have
3397
'.~#~' appended to their name, where # is a number.
3399
When you provide files, you can use their current pathname or the pathname
3400
from the target revision. So you can use revert to "undelete" a file by
3401
name. If you name a directory, all the contents of that directory will be
3404
Any files that have been newly added since that revision will be deleted,
3405
with a backup kept if appropriate. Directories containing unknown files
3406
will not be deleted.
3408
The working tree contains a list of pending merged revisions, which will
3409
be included as parents in the next commit. Normally, revert clears that
3410
list as well as reverting the files. If any files are specified, revert
3411
leaves the pending merge list alone and reverts only the files. Use "bzr
3412
revert ." in the tree root to revert all files but keep the merge record,
3413
and "bzr revert --forget-merges" to clear the pending merge list without
3414
reverting any files.
3417
_see_also = ['cat', 'export']
3420
Option('no-backup', "Do not save backups of reverted files."),
3421
Option('forget-merges',
3422
'Remove pending merge marker, without changing any files.'),
3424
takes_args = ['file*']
3426
def run(self, revision=None, no_backup=False, file_list=None,
3427
forget_merges=None):
3428
tree, file_list = tree_files(file_list)
3432
tree.set_parent_ids(tree.get_parent_ids()[:1])
3434
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3439
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3440
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3441
pb = ui.ui_factory.nested_progress_bar()
3443
tree.revert(file_list, rev_tree, not no_backup, pb,
3444
report_changes=True)
3449
class cmd_assert_fail(Command):
3450
"""Test reporting of assertion failures"""
3451
# intended just for use in testing
3456
raise AssertionError("always fails")
3459
class cmd_help(Command):
3460
"""Show help on a command or other topic.
3463
_see_also = ['topics']
3465
Option('long', 'Show help on all commands.'),
3467
takes_args = ['topic?']
3468
aliases = ['?', '--help', '-?', '-h']
3471
def run(self, topic=None, long=False):
3473
if topic is None and long:
3475
bzrlib.help.help(topic)
3478
class cmd_shell_complete(Command):
3479
"""Show appropriate completions for context.
3481
For a list of all available commands, say 'bzr shell-complete'.
3483
takes_args = ['context?']
3488
def run(self, context=None):
3489
import shellcomplete
3490
shellcomplete.shellcomplete(context)
3493
class cmd_missing(Command):
3494
"""Show unmerged/unpulled revisions between two branches.
3496
OTHER_BRANCH may be local or remote.
3499
_see_also = ['merge', 'pull']
3500
takes_args = ['other_branch?']
3502
Option('reverse', 'Reverse the order of revisions.'),
3504
'Display changes in the local branch only.'),
3505
Option('this' , 'Same as --mine-only.'),
3506
Option('theirs-only',
3507
'Display changes in the remote branch only.'),
3508
Option('other', 'Same as --theirs-only.'),
3512
Option('include-merges', 'Show merged revisions.'),
3514
encoding_type = 'replace'
3517
def run(self, other_branch=None, reverse=False, mine_only=False,
3519
log_format=None, long=False, short=False, line=False,
3520
show_ids=False, verbose=False, this=False, other=False,
3521
include_merges=False):
3522
from bzrlib.missing import find_unmerged, iter_log_revisions
3531
# TODO: We should probably check that we don't have mine-only and
3532
# theirs-only set, but it gets complicated because we also have
3533
# this and other which could be used.
3540
local_branch = Branch.open_containing(u".")[0]
3541
parent = local_branch.get_parent()
3542
if other_branch is None:
3543
other_branch = parent
3544
if other_branch is None:
3545
raise errors.BzrCommandError("No peer location known"
3547
display_url = urlutils.unescape_for_display(parent,
3549
message("Using saved parent location: "
3550
+ display_url + "\n")
3552
remote_branch = Branch.open(other_branch)
3553
if remote_branch.base == local_branch.base:
3554
remote_branch = local_branch
3555
local_branch.lock_read()
3557
remote_branch.lock_read()
3559
local_extra, remote_extra = find_unmerged(
3560
local_branch, remote_branch, restrict,
3561
backward=not reverse,
3562
include_merges=include_merges)
3564
if log_format is None:
3565
registry = log.log_formatter_registry
3566
log_format = registry.get_default(local_branch)
3567
lf = log_format(to_file=self.outf,
3569
show_timezone='original')
3572
if local_extra and not theirs_only:
3573
message("You have %d extra revision(s):\n" %
3575
for revision in iter_log_revisions(local_extra,
3576
local_branch.repository,
3578
lf.log_revision(revision)
3579
printed_local = True
3582
printed_local = False
3584
if remote_extra and not mine_only:
3585
if printed_local is True:
3587
message("You are missing %d revision(s):\n" %
3589
for revision in iter_log_revisions(remote_extra,
3590
remote_branch.repository,
3592
lf.log_revision(revision)
3595
if mine_only and not local_extra:
3596
# We checked local, and found nothing extra
3597
message('This branch is up to date.\n')
3598
elif theirs_only and not remote_extra:
3599
# We checked remote, and found nothing extra
3600
message('Other branch is up to date.\n')
3601
elif not (mine_only or theirs_only or local_extra or
3603
# We checked both branches, and neither one had extra
3605
message("Branches are up to date.\n")
3607
remote_branch.unlock()
3609
local_branch.unlock()
3610
if not status_code and parent is None and other_branch is not None:
3611
local_branch.lock_write()
3613
# handle race conditions - a parent might be set while we run.
3614
if local_branch.get_parent() is None:
3615
local_branch.set_parent(remote_branch.base)
3617
local_branch.unlock()
3621
class cmd_pack(Command):
3622
"""Compress the data within a repository."""
3624
_see_also = ['repositories']
3625
takes_args = ['branch_or_repo?']
3627
def run(self, branch_or_repo='.'):
3628
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3630
branch = dir.open_branch()
3631
repository = branch.repository
3632
except errors.NotBranchError:
3633
repository = dir.open_repository()
3637
class cmd_plugins(Command):
3638
"""List the installed plugins.
3640
This command displays the list of installed plugins including
3641
version of plugin and a short description of each.
3643
--verbose shows the path where each plugin is located.
3645
A plugin is an external component for Bazaar that extends the
3646
revision control system, by adding or replacing code in Bazaar.
3647
Plugins can do a variety of things, including overriding commands,
3648
adding new commands, providing additional network transports and
3649
customizing log output.
3651
See the Bazaar web site, http://bazaar-vcs.org, for further
3652
information on plugins including where to find them and how to
3653
install them. Instructions are also provided there on how to
3654
write new plugins using the Python programming language.
3656
takes_options = ['verbose']
3659
def run(self, verbose=False):
3660
import bzrlib.plugin
3661
from inspect import getdoc
3663
for name, plugin in bzrlib.plugin.plugins().items():
3664
version = plugin.__version__
3665
if version == 'unknown':
3667
name_ver = '%s %s' % (name, version)
3668
d = getdoc(plugin.module)
3670
doc = d.split('\n')[0]
3672
doc = '(no description)'
3673
result.append((name_ver, doc, plugin.path()))
3674
for name_ver, doc, path in sorted(result):
3682
class cmd_testament(Command):
3683
"""Show testament (signing-form) of a revision."""
3686
Option('long', help='Produce long-format testament.'),
3688
help='Produce a strict-format testament.')]
3689
takes_args = ['branch?']
3691
def run(self, branch=u'.', revision=None, long=False, strict=False):
3692
from bzrlib.testament import Testament, StrictTestament
3694
testament_class = StrictTestament
3696
testament_class = Testament
3698
b = Branch.open_containing(branch)[0]
3700
b = Branch.open(branch)
3703
if revision is None:
3704
rev_id = b.last_revision()
3706
rev_id = revision[0].as_revision_id(b)
3707
t = testament_class.from_revision(b.repository, rev_id)
3709
sys.stdout.writelines(t.as_text_lines())
3711
sys.stdout.write(t.as_short_text())
3716
class cmd_annotate(Command):
3717
"""Show the origin of each line in a file.
3719
This prints out the given file with an annotation on the left side
3720
indicating which revision, author and date introduced the change.
3722
If the origin is the same for a run of consecutive lines, it is
3723
shown only at the top, unless the --all option is given.
3725
# TODO: annotate directories; showing when each file was last changed
3726
# TODO: if the working copy is modified, show annotations on that
3727
# with new uncommitted lines marked
3728
aliases = ['ann', 'blame', 'praise']
3729
takes_args = ['filename']
3730
takes_options = [Option('all', help='Show annotations on all lines.'),
3731
Option('long', help='Show commit date in annotations.'),
3735
encoding_type = 'exact'
3738
def run(self, filename, all=False, long=False, revision=None,
3740
from bzrlib.annotate import annotate_file, annotate_file_tree
3741
wt, branch, relpath = \
3742
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3748
tree = _get_one_revision_tree('annotate', revision, branch=branch)
3750
file_id = wt.path2id(relpath)
3752
file_id = tree.path2id(relpath)
3754
raise errors.NotVersionedError(filename)
3755
file_version = tree.inventory[file_id].revision
3756
if wt is not None and revision is None:
3757
# If there is a tree and we're not annotating historical
3758
# versions, annotate the working tree's content.
3759
annotate_file_tree(wt, file_id, self.outf, long, all,
3762
annotate_file(branch, file_version, file_id, long, all, self.outf,
3771
class cmd_re_sign(Command):
3772
"""Create a digital signature for an existing revision."""
3773
# TODO be able to replace existing ones.
3775
hidden = True # is this right ?
3776
takes_args = ['revision_id*']
3777
takes_options = ['revision']
3779
def run(self, revision_id_list=None, revision=None):
3780
if revision_id_list is not None and revision is not None:
3781
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3782
if revision_id_list is None and revision is None:
3783
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3784
b = WorkingTree.open_containing(u'.')[0].branch
3787
return self._run(b, revision_id_list, revision)
3791
def _run(self, b, revision_id_list, revision):
3792
import bzrlib.gpg as gpg
3793
gpg_strategy = gpg.GPGStrategy(b.get_config())
3794
if revision_id_list is not None:
3795
b.repository.start_write_group()
3797
for revision_id in revision_id_list:
3798
b.repository.sign_revision(revision_id, gpg_strategy)
3800
b.repository.abort_write_group()
3803
b.repository.commit_write_group()
3804
elif revision is not None:
3805
if len(revision) == 1:
3806
revno, rev_id = revision[0].in_history(b)
3807
b.repository.start_write_group()
3809
b.repository.sign_revision(rev_id, gpg_strategy)
3811
b.repository.abort_write_group()
3814
b.repository.commit_write_group()
3815
elif len(revision) == 2:
3816
# are they both on rh- if so we can walk between them
3817
# might be nice to have a range helper for arbitrary
3818
# revision paths. hmm.
3819
from_revno, from_revid = revision[0].in_history(b)
3820
to_revno, to_revid = revision[1].in_history(b)
3821
if to_revid is None:
3822
to_revno = b.revno()
3823
if from_revno is None or to_revno is None:
3824
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3825
b.repository.start_write_group()
3827
for revno in range(from_revno, to_revno + 1):
3828
b.repository.sign_revision(b.get_rev_id(revno),
3831
b.repository.abort_write_group()
3834
b.repository.commit_write_group()
3836
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3839
class cmd_bind(Command):
3840
"""Convert the current branch into a checkout of the supplied branch.
3842
Once converted into a checkout, commits must succeed on the master branch
3843
before they will be applied to the local branch.
3845
Bound branches use the nickname of its master branch unless it is set
3846
locally, in which case binding will update the the local nickname to be
3850
_see_also = ['checkouts', 'unbind']
3851
takes_args = ['location?']
3854
def run(self, location=None):
3855
b, relpath = Branch.open_containing(u'.')
3856
if location is None:
3858
location = b.get_old_bound_location()
3859
except errors.UpgradeRequired:
3860
raise errors.BzrCommandError('No location supplied. '
3861
'This format does not remember old locations.')
3863
if location is None:
3864
raise errors.BzrCommandError('No location supplied and no '
3865
'previous location known')
3866
b_other = Branch.open(location)
3869
except errors.DivergedBranches:
3870
raise errors.BzrCommandError('These branches have diverged.'
3871
' Try merging, and then bind again.')
3872
if b.get_config().has_explicit_nickname():
3873
b.nick = b_other.nick
3876
class cmd_unbind(Command):
3877
"""Convert the current checkout into a regular branch.
3879
After unbinding, the local branch is considered independent and subsequent
3880
commits will be local only.
3883
_see_also = ['checkouts', 'bind']
3888
b, relpath = Branch.open_containing(u'.')
3890
raise errors.BzrCommandError('Local branch is not bound')
3893
class cmd_uncommit(Command):
3894
"""Remove the last committed revision.
3896
--verbose will print out what is being removed.
3897
--dry-run will go through all the motions, but not actually
3900
If --revision is specified, uncommit revisions to leave the branch at the
3901
specified revision. For example, "bzr uncommit -r 15" will leave the
3902
branch at revision 15.
3904
Uncommit leaves the working tree ready for a new commit. The only change
3905
it may make is to restore any pending merges that were present before
3909
# TODO: jam 20060108 Add an option to allow uncommit to remove
3910
# unreferenced information in 'branch-as-repository' branches.
3911
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3912
# information in shared branches as well.
3913
_see_also = ['commit']
3914
takes_options = ['verbose', 'revision',
3915
Option('dry-run', help='Don\'t actually make changes.'),
3916
Option('force', help='Say yes to all questions.'),
3918
help="Only remove the commits from the local branch"
3919
" when in a checkout."
3922
takes_args = ['location?']
3924
encoding_type = 'replace'
3926
def run(self, location=None,
3927
dry_run=False, verbose=False,
3928
revision=None, force=False, local=False):
3929
if location is None:
3931
control, relpath = bzrdir.BzrDir.open_containing(location)
3933
tree = control.open_workingtree()
3935
except (errors.NoWorkingTree, errors.NotLocalUrl):
3937
b = control.open_branch()
3939
if tree is not None:
3944
return self._run(b, tree, dry_run, verbose, revision, force,
3947
if tree is not None:
3952
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3953
from bzrlib.log import log_formatter, show_log
3954
from bzrlib.uncommit import uncommit
3956
last_revno, last_rev_id = b.last_revision_info()
3959
if revision is None:
3961
rev_id = last_rev_id
3963
# 'bzr uncommit -r 10' actually means uncommit
3964
# so that the final tree is at revno 10.
3965
# but bzrlib.uncommit.uncommit() actually uncommits
3966
# the revisions that are supplied.
3967
# So we need to offset it by one
3968
revno = revision[0].in_history(b).revno + 1
3969
if revno <= last_revno:
3970
rev_id = b.get_rev_id(revno)
3972
if rev_id is None or _mod_revision.is_null(rev_id):
3973
self.outf.write('No revisions to uncommit.\n')
3976
lf = log_formatter('short',
3978
show_timezone='original')
3983
direction='forward',
3984
start_revision=revno,
3985
end_revision=last_revno)
3988
print 'Dry-run, pretending to remove the above revisions.'
3990
val = raw_input('Press <enter> to continue')
3992
print 'The above revision(s) will be removed.'
3994
val = raw_input('Are you sure [y/N]? ')
3995
if val.lower() not in ('y', 'yes'):
3999
mutter('Uncommitting from {%s} to {%s}',
4000
last_rev_id, rev_id)
4001
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4002
revno=revno, local=local)
4003
note('You can restore the old tip by running:\n'
4004
' bzr pull . -r revid:%s', last_rev_id)
4007
class cmd_break_lock(Command):
4008
"""Break a dead lock on a repository, branch or working directory.
4010
CAUTION: Locks should only be broken when you are sure that the process
4011
holding the lock has been stopped.
4013
You can get information on what locks are open via the 'bzr info' command.
4018
takes_args = ['location?']
4020
def run(self, location=None, show=False):
4021
if location is None:
4023
control, relpath = bzrdir.BzrDir.open_containing(location)
4025
control.break_lock()
4026
except NotImplementedError:
4030
class cmd_wait_until_signalled(Command):
4031
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4033
This just prints a line to signal when it is ready, then blocks on stdin.
4039
sys.stdout.write("running\n")
4041
sys.stdin.readline()
4044
class cmd_serve(Command):
4045
"""Run the bzr server."""
4047
aliases = ['server']
4051
help='Serve on stdin/out for use from inetd or sshd.'),
4053
help='Listen for connections on nominated port of the form '
4054
'[hostname:]portnumber. Passing 0 as the port number will '
4055
'result in a dynamically allocated port. The default port is '
4059
help='Serve contents of this directory.',
4061
Option('allow-writes',
4062
help='By default the server is a readonly server. Supplying '
4063
'--allow-writes enables write access to the contents of '
4064
'the served directory and below.'
4068
def run(self, port=None, inet=False, directory=None, allow_writes=False):
4069
from bzrlib import lockdir
4070
from bzrlib.smart import medium, server
4071
from bzrlib.transport import get_transport
4072
from bzrlib.transport.chroot import ChrootServer
4073
if directory is None:
4074
directory = os.getcwd()
4075
url = urlutils.local_path_to_url(directory)
4076
if not allow_writes:
4077
url = 'readonly+' + url
4078
chroot_server = ChrootServer(get_transport(url))
4079
chroot_server.setUp()
4080
t = get_transport(chroot_server.get_url())
4082
smart_server = medium.SmartServerPipeStreamMedium(
4083
sys.stdin, sys.stdout, t)
4085
host = medium.BZR_DEFAULT_INTERFACE
4087
port = medium.BZR_DEFAULT_PORT
4090
host, port = port.split(':')
4092
smart_server = server.SmartTCPServer(t, host=host, port=port)
4093
print 'listening on port: ', smart_server.port
4095
# for the duration of this server, no UI output is permitted.
4096
# note that this may cause problems with blackbox tests. This should
4097
# be changed with care though, as we dont want to use bandwidth sending
4098
# progress over stderr to smart server clients!
4099
old_factory = ui.ui_factory
4100
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4102
ui.ui_factory = ui.SilentUIFactory()
4103
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4104
smart_server.serve()
4106
ui.ui_factory = old_factory
4107
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4110
class cmd_join(Command):
4111
"""Combine a subtree into its containing tree.
4113
This command is for experimental use only. It requires the target tree
4114
to be in dirstate-with-subtree format, which cannot be converted into
4117
The TREE argument should be an independent tree, inside another tree, but
4118
not part of it. (Such trees can be produced by "bzr split", but also by
4119
running "bzr branch" with the target inside a tree.)
4121
The result is a combined tree, with the subtree no longer an independant
4122
part. This is marked as a merge of the subtree into the containing tree,
4123
and all history is preserved.
4125
If --reference is specified, the subtree retains its independence. It can
4126
be branched by itself, and can be part of multiple projects at the same
4127
time. But operations performed in the containing tree, such as commit
4128
and merge, will recurse into the subtree.
4131
_see_also = ['split']
4132
takes_args = ['tree']
4134
Option('reference', help='Join by reference.'),
4138
def run(self, tree, reference=False):
4139
sub_tree = WorkingTree.open(tree)
4140
parent_dir = osutils.dirname(sub_tree.basedir)
4141
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4142
repo = containing_tree.branch.repository
4143
if not repo.supports_rich_root():
4144
raise errors.BzrCommandError(
4145
"Can't join trees because %s doesn't support rich root data.\n"
4146
"You can use bzr upgrade on the repository."
4150
containing_tree.add_reference(sub_tree)
4151
except errors.BadReferenceTarget, e:
4152
# XXX: Would be better to just raise a nicely printable
4153
# exception from the real origin. Also below. mbp 20070306
4154
raise errors.BzrCommandError("Cannot join %s. %s" %
4158
containing_tree.subsume(sub_tree)
4159
except errors.BadSubsumeSource, e:
4160
raise errors.BzrCommandError("Cannot join %s. %s" %
4164
class cmd_split(Command):
4165
"""Split a subdirectory of a tree into a separate tree.
4167
This command will produce a target tree in a format that supports
4168
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4169
converted into earlier formats like 'dirstate-tags'.
4171
The TREE argument should be a subdirectory of a working tree. That
4172
subdirectory will be converted into an independent tree, with its own
4173
branch. Commits in the top-level tree will not apply to the new subtree.
4176
# join is not un-hidden yet
4177
#_see_also = ['join']
4178
takes_args = ['tree']
4180
def run(self, tree):
4181
containing_tree, subdir = WorkingTree.open_containing(tree)
4182
sub_id = containing_tree.path2id(subdir)
4184
raise errors.NotVersionedError(subdir)
4186
containing_tree.extract(sub_id)
4187
except errors.RootNotRich:
4188
raise errors.UpgradeRequired(containing_tree.branch.base)
4191
class cmd_merge_directive(Command):
4192
"""Generate a merge directive for auto-merge tools.
4194
A directive requests a merge to be performed, and also provides all the
4195
information necessary to do so. This means it must either include a
4196
revision bundle, or the location of a branch containing the desired
4199
A submit branch (the location to merge into) must be supplied the first
4200
time the command is issued. After it has been supplied once, it will
4201
be remembered as the default.
4203
A public branch is optional if a revision bundle is supplied, but required
4204
if --diff or --plain is specified. It will be remembered as the default
4205
after the first use.
4208
takes_args = ['submit_branch?', 'public_branch?']
4212
_see_also = ['send']
4215
RegistryOption.from_kwargs('patch-type',
4216
'The type of patch to include in the directive.',
4218
value_switches=True,
4220
bundle='Bazaar revision bundle (default).',
4221
diff='Normal unified diff.',
4222
plain='No patch, just directive.'),
4223
Option('sign', help='GPG-sign the directive.'), 'revision',
4224
Option('mail-to', type=str,
4225
help='Instead of printing the directive, email to this address.'),
4226
Option('message', type=str, short_name='m',
4227
help='Message to use when committing this merge.')
4230
encoding_type = 'exact'
4232
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4233
sign=False, revision=None, mail_to=None, message=None):
4234
from bzrlib.revision import ensure_null, NULL_REVISION
4235
include_patch, include_bundle = {
4236
'plain': (False, False),
4237
'diff': (True, False),
4238
'bundle': (True, True),
4240
branch = Branch.open('.')
4241
stored_submit_branch = branch.get_submit_branch()
4242
if submit_branch is None:
4243
submit_branch = stored_submit_branch
4245
if stored_submit_branch is None:
4246
branch.set_submit_branch(submit_branch)
4247
if submit_branch is None:
4248
submit_branch = branch.get_parent()
4249
if submit_branch is None:
4250
raise errors.BzrCommandError('No submit branch specified or known')
4252
stored_public_branch = branch.get_public_branch()
4253
if public_branch is None:
4254
public_branch = stored_public_branch
4255
elif stored_public_branch is None:
4256
branch.set_public_branch(public_branch)
4257
if not include_bundle and public_branch is None:
4258
raise errors.BzrCommandError('No public branch specified or'
4260
base_revision_id = None
4261
if revision is not None:
4262
if len(revision) > 2:
4263
raise errors.BzrCommandError('bzr merge-directive takes '
4264
'at most two one revision identifiers')
4265
revision_id = revision[-1].as_revision_id(branch)
4266
if len(revision) == 2:
4267
base_revision_id = revision[0].as_revision_id(branch)
4269
revision_id = branch.last_revision()
4270
revision_id = ensure_null(revision_id)
4271
if revision_id == NULL_REVISION:
4272
raise errors.BzrCommandError('No revisions to bundle.')
4273
directive = merge_directive.MergeDirective2.from_objects(
4274
branch.repository, revision_id, time.time(),
4275
osutils.local_time_offset(), submit_branch,
4276
public_branch=public_branch, include_patch=include_patch,
4277
include_bundle=include_bundle, message=message,
4278
base_revision_id=base_revision_id)
4281
self.outf.write(directive.to_signed(branch))
4283
self.outf.writelines(directive.to_lines())
4285
message = directive.to_email(mail_to, branch, sign)
4286
s = SMTPConnection(branch.get_config())
4287
s.send_email(message)
4290
class cmd_send(Command):
4291
"""Mail or create a merge-directive for submiting changes.
4293
A merge directive provides many things needed for requesting merges:
4295
* A machine-readable description of the merge to perform
4297
* An optional patch that is a preview of the changes requested
4299
* An optional bundle of revision data, so that the changes can be applied
4300
directly from the merge directive, without retrieving data from a
4303
If --no-bundle is specified, then public_branch is needed (and must be
4304
up-to-date), so that the receiver can perform the merge using the
4305
public_branch. The public_branch is always included if known, so that
4306
people can check it later.
4308
The submit branch defaults to the parent, but can be overridden. Both
4309
submit branch and public branch will be remembered if supplied.
4311
If a public_branch is known for the submit_branch, that public submit
4312
branch is used in the merge instructions. This means that a local mirror
4313
can be used as your actual submit branch, once you have set public_branch
4316
Mail is sent using your preferred mail program. This should be transparent
4317
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4318
If the preferred client can't be found (or used), your editor will be used.
4320
To use a specific mail program, set the mail_client configuration option.
4321
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4322
specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4323
generic options are "default", "editor", "emacsclient", "mapi", and
4324
"xdg-email". Plugins may also add supported clients.
4326
If mail is being sent, a to address is required. This can be supplied
4327
either on the commandline, by setting the submit_to configuration
4328
option in the branch itself or the child_submit_to configuration option
4329
in the submit branch.
4331
Two formats are currently supported: "4" uses revision bundle format 4 and
4332
merge directive format 2. It is significantly faster and smaller than
4333
older formats. It is compatible with Bazaar 0.19 and later. It is the
4334
default. "0.9" uses revision bundle format 0.9 and merge directive
4335
format 1. It is compatible with Bazaar 0.12 - 0.18.
4337
Merge directives are applied using the merge command or the pull command.
4340
encoding_type = 'exact'
4342
_see_also = ['merge', 'pull']
4344
takes_args = ['submit_branch?', 'public_branch?']
4348
help='Do not include a bundle in the merge directive.'),
4349
Option('no-patch', help='Do not include a preview patch in the merge'
4352
help='Remember submit and public branch.'),
4354
help='Branch to generate the submission from, '
4355
'rather than the one containing the working directory.',
4358
Option('output', short_name='o',
4359
help='Write merge directive to this file; '
4360
'use - for stdout.',
4362
Option('mail-to', help='Mail the request to this address.',
4366
RegistryOption.from_kwargs('format',
4367
'Use the specified output format.',
4368
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4369
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4372
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4373
no_patch=False, revision=None, remember=False, output=None,
4374
format='4', mail_to=None, message=None, **kwargs):
4375
return self._run(submit_branch, revision, public_branch, remember,
4376
format, no_bundle, no_patch, output,
4377
kwargs.get('from', '.'), mail_to, message)
4379
def _run(self, submit_branch, revision, public_branch, remember, format,
4380
no_bundle, no_patch, output, from_, mail_to, message):
4381
from bzrlib.revision import NULL_REVISION
4382
branch = Branch.open_containing(from_)[0]
4384
outfile = cStringIO.StringIO()
4388
outfile = open(output, 'wb')
4389
# we may need to write data into branch's repository to calculate
4394
config = branch.get_config()
4396
mail_to = config.get_user_option('submit_to')
4397
mail_client = config.get_mail_client()
4398
if remember and submit_branch is None:
4399
raise errors.BzrCommandError(
4400
'--remember requires a branch to be specified.')
4401
stored_submit_branch = branch.get_submit_branch()
4402
remembered_submit_branch = None
4403
if submit_branch is None:
4404
submit_branch = stored_submit_branch
4405
remembered_submit_branch = "submit"
4407
if stored_submit_branch is None or remember:
4408
branch.set_submit_branch(submit_branch)
4409
if submit_branch is None:
4410
submit_branch = branch.get_parent()
4411
remembered_submit_branch = "parent"
4412
if submit_branch is None:
4413
raise errors.BzrCommandError('No submit branch known or'
4415
if remembered_submit_branch is not None:
4416
note('Using saved %s location "%s" to determine what '
4417
'changes to submit.', remembered_submit_branch,
4421
submit_config = Branch.open(submit_branch).get_config()
4422
mail_to = submit_config.get_user_option("child_submit_to")
4424
stored_public_branch = branch.get_public_branch()
4425
if public_branch is None:
4426
public_branch = stored_public_branch
4427
elif stored_public_branch is None or remember:
4428
branch.set_public_branch(public_branch)
4429
if no_bundle and public_branch is None:
4430
raise errors.BzrCommandError('No public branch specified or'
4432
base_revision_id = None
4434
if revision is not None:
4435
if len(revision) > 2:
4436
raise errors.BzrCommandError('bzr send takes '
4437
'at most two one revision identifiers')
4438
revision_id = revision[-1].as_revision_id(branch)
4439
if len(revision) == 2:
4440
base_revision_id = revision[0].as_revision_id(branch)
4441
if revision_id is None:
4442
revision_id = branch.last_revision()
4443
if revision_id == NULL_REVISION:
4444
raise errors.BzrCommandError('No revisions to submit.')
4446
directive = merge_directive.MergeDirective2.from_objects(
4447
branch.repository, revision_id, time.time(),
4448
osutils.local_time_offset(), submit_branch,
4449
public_branch=public_branch, include_patch=not no_patch,
4450
include_bundle=not no_bundle, message=message,
4451
base_revision_id=base_revision_id)
4452
elif format == '0.9':
4455
patch_type = 'bundle'
4457
raise errors.BzrCommandError('Format 0.9 does not'
4458
' permit bundle with no patch')
4464
directive = merge_directive.MergeDirective.from_objects(
4465
branch.repository, revision_id, time.time(),
4466
osutils.local_time_offset(), submit_branch,
4467
public_branch=public_branch, patch_type=patch_type,
4470
outfile.writelines(directive.to_lines())
4472
subject = '[MERGE] '
4473
if message is not None:
4476
revision = branch.repository.get_revision(revision_id)
4477
subject += revision.get_summary()
4478
basename = directive.get_disk_name(branch)
4479
mail_client.compose_merge_request(mail_to, subject,
4480
outfile.getvalue(), basename)
4487
class cmd_bundle_revisions(cmd_send):
4489
"""Create a merge-directive for submiting changes.
4491
A merge directive provides many things needed for requesting merges:
4493
* A machine-readable description of the merge to perform
4495
* An optional patch that is a preview of the changes requested
4497
* An optional bundle of revision data, so that the changes can be applied
4498
directly from the merge directive, without retrieving data from a
4501
If --no-bundle is specified, then public_branch is needed (and must be
4502
up-to-date), so that the receiver can perform the merge using the
4503
public_branch. The public_branch is always included if known, so that
4504
people can check it later.
4506
The submit branch defaults to the parent, but can be overridden. Both
4507
submit branch and public branch will be remembered if supplied.
4509
If a public_branch is known for the submit_branch, that public submit
4510
branch is used in the merge instructions. This means that a local mirror
4511
can be used as your actual submit branch, once you have set public_branch
4514
Two formats are currently supported: "4" uses revision bundle format 4 and
4515
merge directive format 2. It is significantly faster and smaller than
4516
older formats. It is compatible with Bazaar 0.19 and later. It is the
4517
default. "0.9" uses revision bundle format 0.9 and merge directive
4518
format 1. It is compatible with Bazaar 0.12 - 0.18.
4523
help='Do not include a bundle in the merge directive.'),
4524
Option('no-patch', help='Do not include a preview patch in the merge'
4527
help='Remember submit and public branch.'),
4529
help='Branch to generate the submission from, '
4530
'rather than the one containing the working directory.',
4533
Option('output', short_name='o', help='Write directive to this file.',
4536
RegistryOption.from_kwargs('format',
4537
'Use the specified output format.',
4538
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4539
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4541
aliases = ['bundle']
4543
_see_also = ['send', 'merge']
4547
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4548
no_patch=False, revision=None, remember=False, output=None,
4549
format='4', **kwargs):
4552
return self._run(submit_branch, revision, public_branch, remember,
4553
format, no_bundle, no_patch, output,
4554
kwargs.get('from', '.'), None, None)
4557
class cmd_tag(Command):
4558
"""Create, remove or modify a tag naming a revision.
4560
Tags give human-meaningful names to revisions. Commands that take a -r
4561
(--revision) option can be given -rtag:X, where X is any previously
4564
Tags are stored in the branch. Tags are copied from one branch to another
4565
along when you branch, push, pull or merge.
4567
It is an error to give a tag name that already exists unless you pass
4568
--force, in which case the tag is moved to point to the new revision.
4570
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4571
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4574
_see_also = ['commit', 'tags']
4575
takes_args = ['tag_name']
4578
help='Delete this tag rather than placing it.',
4581
help='Branch in which to place the tag.',
4586
help='Replace existing tags.',
4591
def run(self, tag_name,
4597
branch, relpath = Branch.open_containing(directory)
4601
branch.tags.delete_tag(tag_name)
4602
self.outf.write('Deleted tag %s.\n' % tag_name)
4605
if len(revision) != 1:
4606
raise errors.BzrCommandError(
4607
"Tags can only be placed on a single revision, "
4609
revision_id = revision[0].as_revision_id(branch)
4611
revision_id = branch.last_revision()
4612
if (not force) and branch.tags.has_tag(tag_name):
4613
raise errors.TagAlreadyExists(tag_name)
4614
branch.tags.set_tag(tag_name, revision_id)
4615
self.outf.write('Created tag %s.\n' % tag_name)
4620
class cmd_tags(Command):
4623
This command shows a table of tag names and the revisions they reference.
4629
help='Branch whose tags should be displayed.',
4633
RegistryOption.from_kwargs('sort',
4634
'Sort tags by different criteria.', title='Sorting',
4635
alpha='Sort tags lexicographically (default).',
4636
time='Sort tags chronologically.',
4649
branch, relpath = Branch.open_containing(directory)
4651
tags = branch.tags.get_tag_dict().items()
4658
graph = branch.repository.get_graph()
4659
rev1, rev2 = _get_revision_range(revision, branch, self.name())
4660
revid1, revid2 = rev1.rev_id, rev2.rev_id
4661
# only show revisions between revid1 and revid2 (inclusive)
4662
tags = [(tag, revid) for tag, revid in tags if
4664
graph.is_ancestor(revid, revid2)) and
4666
graph.is_ancestor(revid1, revid))]
4671
elif sort == 'time':
4673
for tag, revid in tags:
4675
revobj = branch.repository.get_revision(revid)
4676
except errors.NoSuchRevision:
4677
timestamp = sys.maxint # place them at the end
4679
timestamp = revobj.timestamp
4680
timestamps[revid] = timestamp
4681
tags.sort(key=lambda x: timestamps[x[1]])
4683
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4684
revno_map = branch.get_revision_id_to_revno_map()
4685
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4686
for tag, revid in tags ]
4687
for tag, revspec in tags:
4688
self.outf.write('%-20s %s\n' % (tag, revspec))
4691
class cmd_reconfigure(Command):
4692
"""Reconfigure the type of a bzr directory.
4694
A target configuration must be specified.
4696
For checkouts, the bind-to location will be auto-detected if not specified.
4697
The order of preference is
4698
1. For a lightweight checkout, the current bound location.
4699
2. For branches that used to be checkouts, the previously-bound location.
4700
3. The push location.
4701
4. The parent location.
4702
If none of these is available, --bind-to must be specified.
4705
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4706
takes_args = ['location?']
4707
takes_options = [RegistryOption.from_kwargs('target_type',
4708
title='Target type',
4709
help='The type to reconfigure the directory to.',
4710
value_switches=True, enum_switch=False,
4711
branch='Reconfigure to be an unbound branch '
4712
'with no working tree.',
4713
tree='Reconfigure to be an unbound branch '
4714
'with a working tree.',
4715
checkout='Reconfigure to be a bound branch '
4716
'with a working tree.',
4717
lightweight_checkout='Reconfigure to be a lightweight'
4718
' checkout (with no local history).',
4719
standalone='Reconfigure to be a standalone branch '
4720
'(i.e. stop using shared repository).',
4721
use_shared='Reconfigure to use a shared repository.'),
4722
Option('bind-to', help='Branch to bind checkout to.',
4725
help='Perform reconfiguration even if local changes'
4729
def run(self, location=None, target_type=None, bind_to=None, force=False):
4730
directory = bzrdir.BzrDir.open(location)
4731
if target_type is None:
4732
raise errors.BzrCommandError('No target configuration specified')
4733
elif target_type == 'branch':
4734
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4735
elif target_type == 'tree':
4736
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4737
elif target_type == 'checkout':
4738
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4740
elif target_type == 'lightweight-checkout':
4741
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4743
elif target_type == 'use-shared':
4744
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4745
elif target_type == 'standalone':
4746
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4747
reconfiguration.apply(force)
4750
class cmd_switch(Command):
4751
"""Set the branch of a checkout and update.
4753
For lightweight checkouts, this changes the branch being referenced.
4754
For heavyweight checkouts, this checks that there are no local commits
4755
versus the current bound branch, then it makes the local branch a mirror
4756
of the new location and binds to it.
4758
In both cases, the working tree is updated and uncommitted changes
4759
are merged. The user can commit or revert these as they desire.
4761
Pending merges need to be committed or reverted before using switch.
4763
The path to the branch to switch to can be specified relative to the parent
4764
directory of the current branch. For example, if you are currently in a
4765
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4768
Bound branches use the nickname of its master branch unless it is set
4769
locally, in which case switching will update the the local nickname to be
4773
takes_args = ['to_location']
4774
takes_options = [Option('force',
4775
help='Switch even if local commits will be lost.')
4778
def run(self, to_location, force=False):
4779
from bzrlib import switch
4781
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4782
branch = control_dir.open_branch()
4784
to_branch = Branch.open(to_location)
4785
except errors.NotBranchError:
4786
this_branch = control_dir.open_branch()
4787
# This may be a heavy checkout, where we want the master branch
4788
this_url = this_branch.get_bound_location()
4789
# If not, use a local sibling
4790
if this_url is None:
4791
this_url = this_branch.base
4792
to_branch = Branch.open(
4793
urlutils.join(this_url, '..', to_location))
4794
switch.switch(control_dir, to_branch, force)
4795
if branch.get_config().has_explicit_nickname():
4796
branch = control_dir.open_branch() #get the new branch!
4797
branch.nick = to_branch.nick
4798
note('Switched to branch: %s',
4799
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4802
class cmd_hooks(Command):
4803
"""Show a branch's currently registered hooks.
4807
takes_args = ['path?']
4809
def run(self, path=None):
4812
branch_hooks = Branch.open(path).hooks
4813
for hook_type in branch_hooks:
4814
hooks = branch_hooks[hook_type]
4815
self.outf.write("%s:\n" % (hook_type,))
4818
self.outf.write(" %s\n" %
4819
(branch_hooks.get_hook_name(hook),))
4821
self.outf.write(" <no hooks installed>\n")
4824
class cmd_shelve(Command):
4825
"""Temporarily set aside some changes from the current tree.
4827
Shelve allows you to temporarily put changes you've made "on the shelf",
4828
ie. out of the way, until a later time when you can bring them back from
4829
the shelf with the 'unshelve' command.
4831
If shelve --list is specified, previously-shelved changes are listed.
4833
Shelve is intended to help separate several sets of changes that have
4834
been inappropriately mingled. If you just want to get rid of all changes
4835
and you don't need to restore them later, use revert. If you want to
4836
shelve all text changes at once, use shelve --all.
4838
If filenames are specified, only the changes to those files will be
4839
shelved. Other files will be left untouched.
4841
If a revision is specified, changes since that revision will be shelved.
4843
You can put multiple items on the shelf, and by default, 'unshelve' will
4844
restore the most recently shelved changes.
4847
takes_args = ['file*']
4851
Option('all', help='Shelve all changes.'),
4853
RegistryOption('writer', 'Method to use for writing diffs.',
4854
bzrlib.option.diff_writer_registry,
4855
value_switches=True, enum_switch=False),
4857
Option('list', help='List shelved changes.'),
4859
_see_also = ['unshelve']
4861
def run(self, revision=None, all=False, file_list=None, message=None,
4862
writer=None, list=False):
4864
return self.run_for_list()
4865
from bzrlib.shelf_ui import Shelver
4867
writer = bzrlib.option.diff_writer_registry.get()
4869
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
4871
except errors.UserAbort:
4874
def run_for_list(self):
4875
tree = WorkingTree.open_containing('.')[0]
4878
manager = tree.get_shelf_manager()
4879
shelves = manager.active_shelves()
4880
if len(shelves) == 0:
4881
note('No shelved changes.')
4883
for shelf_id in reversed(shelves):
4884
message = manager.get_metadata(shelf_id).get('message')
4886
message = '<no message>'
4887
self.outf.write('%3d: %s\n' % (shelf_id, message))
4893
class cmd_unshelve(Command):
4894
"""Restore shelved changes.
4896
By default, the most recently shelved changes are restored. However if you
4897
specify a patch by name those changes will be restored instead. This
4898
works best when the changes don't depend on each other.
4901
takes_args = ['shelf_id?']
4903
RegistryOption.from_kwargs(
4904
'action', help="The action to perform.",
4905
enum_switch=False, value_switches=True,
4906
apply="Apply changes and remove from the shelf.",
4907
dry_run="Show changes, but do not apply or remove them.",
4908
delete_only="Delete changes without applying them."
4911
_see_also = ['shelve']
4913
def run(self, shelf_id=None, action='apply'):
4914
from bzrlib.shelf_ui import Unshelver
4915
Unshelver.from_args(shelf_id, action).run()
4918
def _create_prefix(cur_transport):
4919
needed = [cur_transport]
4920
# Recurse upwards until we can create a directory successfully
4922
new_transport = cur_transport.clone('..')
4923
if new_transport.base == cur_transport.base:
4924
raise errors.BzrCommandError(
4925
"Failed to create path prefix for %s."
4926
% cur_transport.base)
4928
new_transport.mkdir('.')
4929
except errors.NoSuchFile:
4930
needed.append(new_transport)
4931
cur_transport = new_transport
4934
# Now we only need to create child directories
4936
cur_transport = needed.pop()
4937
cur_transport.ensure_base()
4940
# these get imported and then picked up by the scan for cmd_*
4941
# TODO: Some more consistent way to split command definitions across files;
4942
# we do need to load at least some information about them to know of
4943
# aliases. ideally we would avoid loading the implementation until the
4944
# details were needed.
4945
from bzrlib.cmd_version_info import cmd_version_info
4946
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4947
from bzrlib.bundle.commands import (
4950
from bzrlib.sign_my_commits import cmd_sign_my_commits
4951
from bzrlib.weave_commands import cmd_versionedfile_list, \
4952
cmd_weave_plan_merge, cmd_weave_merge_text