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'.', canonicalize=True):
64
return internal_tree_files(file_list, default_branch, canonicalize)
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'.', canonicalize=True):
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, canonicalize)
110
def safe_relpath_files(tree, file_list, canonicalize=True):
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
# tree.relpath exists as a "thunk" to osutils, but canonical_relpath
123
# doesn't - fix that up here before we enter the loop.
125
fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
128
for filename in file_list:
130
new_list.append(fixer(osutils.dereference_path(filename)))
131
except errors.PathNotChild:
132
raise errors.FileInWrongBranch(tree.branch, filename)
136
# TODO: Make sure no commands unconditionally use the working directory as a
137
# branch. If a filename argument is used, the first of them should be used to
138
# specify the branch. (Perhaps this can be factored out into some kind of
139
# Argument class, representing a file in a branch, where the first occurrence
142
class cmd_status(Command):
143
"""Display status summary.
145
This reports on versioned and unknown files, reporting them
146
grouped by state. Possible states are:
149
Versioned in the working copy but not in the previous revision.
152
Versioned in the previous revision but removed or deleted
156
Path of this file changed from the previous revision;
157
the text may also have changed. This includes files whose
158
parent directory was renamed.
161
Text has changed since the previous revision.
164
File kind has been changed (e.g. from file to directory).
167
Not versioned and not matching an ignore pattern.
169
To see ignored files use 'bzr ignored'. For details on the
170
changes to file texts, use 'bzr diff'.
172
Note that --short or -S gives status flags for each item, similar
173
to Subversion's status command. To get output similar to svn -q,
176
If no arguments are specified, the status of the entire working
177
directory is shown. Otherwise, only the status of the specified
178
files or directories is reported. If a directory is given, status
179
is reported for everything inside that directory.
181
If a revision argument is given, the status is calculated against
182
that revision, or between two revisions if two are provided.
185
# TODO: --no-recurse, --recurse options
187
takes_args = ['file*']
188
takes_options = ['show-ids', 'revision', 'change',
189
Option('short', help='Use short status indicators.',
191
Option('versioned', help='Only show versioned files.',
193
Option('no-pending', help='Don\'t show pending merges.',
196
aliases = ['st', 'stat']
198
encoding_type = 'replace'
199
_see_also = ['diff', 'revert', 'status-flags']
202
def run(self, show_ids=False, file_list=None, revision=None, short=False,
203
versioned=False, no_pending=False):
204
from bzrlib.status import show_tree_status
206
if revision and len(revision) > 2:
207
raise errors.BzrCommandError('bzr status --revision takes exactly'
208
' one or two revision specifiers')
210
tree, relfile_list = tree_files(file_list)
211
# Avoid asking for specific files when that is not needed.
212
if relfile_list == ['']:
214
# Don't disable pending merges for full trees other than '.'.
215
if file_list == ['.']:
217
# A specific path within a tree was given.
218
elif relfile_list is not None:
220
show_tree_status(tree, show_ids=show_ids,
221
specific_files=relfile_list, revision=revision,
222
to_file=self.outf, short=short, versioned=versioned,
223
show_pending=(not no_pending))
226
class cmd_cat_revision(Command):
227
"""Write out metadata for a revision.
229
The revision to print can either be specified by a specific
230
revision identifier, or you can use --revision.
234
takes_args = ['revision_id?']
235
takes_options = ['revision']
236
# cat-revision is more for frontends so should be exact
240
def run(self, revision_id=None, revision=None):
241
if revision_id is not None and revision is not None:
242
raise errors.BzrCommandError('You can only supply one of'
243
' revision_id or --revision')
244
if revision_id is None and revision is None:
245
raise errors.BzrCommandError('You must supply either'
246
' --revision or a revision_id')
247
b = WorkingTree.open_containing(u'.')[0].branch
249
# TODO: jam 20060112 should cat-revision always output utf-8?
250
if revision_id is not None:
251
revision_id = osutils.safe_revision_id(revision_id, warn=False)
253
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
254
except errors.NoSuchRevision:
255
msg = "The repository %s contains no revision %s." % (b.repository.base,
257
raise errors.BzrCommandError(msg)
258
elif revision is not None:
261
raise errors.BzrCommandError('You cannot specify a NULL'
263
rev_id = rev.as_revision_id(b)
264
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
267
class cmd_dump_btree(Command):
268
"""Dump the contents of a btree index file to stdout.
270
PATH is a btree index file, it can be any URL. This includes things like
271
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
273
By default, the tuples stored in the index file will be displayed. With
274
--raw, we will uncompress the pages, but otherwise display the raw bytes
278
# TODO: Do we want to dump the internal nodes as well?
279
# TODO: It would be nice to be able to dump the un-parsed information,
280
# rather than only going through iter_all_entries. However, this is
281
# good enough for a start
283
encoding_type = 'exact'
284
takes_args = ['path']
285
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
286
' rather than the parsed tuples.'),
289
def run(self, path, raw=False):
290
dirname, basename = osutils.split(path)
291
t = transport.get_transport(dirname)
293
self._dump_raw_bytes(t, basename)
295
self._dump_entries(t, basename)
297
def _get_index_and_bytes(self, trans, basename):
298
"""Create a BTreeGraphIndex and raw bytes."""
299
bt = btree_index.BTreeGraphIndex(trans, basename, None)
300
bytes = trans.get_bytes(basename)
301
bt._file = cStringIO.StringIO(bytes)
302
bt._size = len(bytes)
305
def _dump_raw_bytes(self, trans, basename):
308
# We need to parse at least the root node.
309
# This is because the first page of every row starts with an
310
# uncompressed header.
311
bt, bytes = self._get_index_and_bytes(trans, basename)
312
for page_idx, page_start in enumerate(xrange(0, len(bytes),
313
btree_index._PAGE_SIZE)):
314
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
315
page_bytes = bytes[page_start:page_end]
317
self.outf.write('Root node:\n')
318
header_end, data = bt._parse_header_from_bytes(page_bytes)
319
self.outf.write(page_bytes[:header_end])
321
self.outf.write('\nPage %d\n' % (page_idx,))
322
decomp_bytes = zlib.decompress(page_bytes)
323
self.outf.write(decomp_bytes)
324
self.outf.write('\n')
326
def _dump_entries(self, trans, basename):
328
st = trans.stat(basename)
329
except errors.TransportNotPossible:
330
# We can't stat, so we'll fake it because we have to do the 'get()'
332
bt, _ = self._get_index_and_bytes(trans, basename)
334
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
335
for node in bt.iter_all_entries():
336
# Node is made up of:
337
# (index, key, value, [references])
338
self.outf.write('%s\n' % (node[1:],))
341
class cmd_remove_tree(Command):
342
"""Remove the working tree from a given branch/checkout.
344
Since a lightweight checkout is little more than a working tree
345
this will refuse to run against one.
347
To re-create the working tree, use "bzr checkout".
349
_see_also = ['checkout', 'working-trees']
350
takes_args = ['location?']
353
help='Remove the working tree even if it has '
354
'uncommitted changes.'),
357
def run(self, location='.', force=False):
358
d = bzrdir.BzrDir.open(location)
361
working = d.open_workingtree()
362
except errors.NoWorkingTree:
363
raise errors.BzrCommandError("No working tree to remove")
364
except errors.NotLocalUrl:
365
raise errors.BzrCommandError("You cannot remove the working tree of a "
368
changes = working.changes_from(working.basis_tree())
369
if changes.has_changed():
370
raise errors.UncommittedChanges(working)
372
working_path = working.bzrdir.root_transport.base
373
branch_path = working.branch.bzrdir.root_transport.base
374
if working_path != branch_path:
375
raise errors.BzrCommandError("You cannot remove the working tree from "
376
"a lightweight checkout")
378
d.destroy_workingtree()
381
class cmd_revno(Command):
382
"""Show current revision number.
384
This is equal to the number of revisions on this branch.
388
takes_args = ['location?']
391
def run(self, location=u'.'):
392
self.outf.write(str(Branch.open_containing(location)[0].revno()))
393
self.outf.write('\n')
396
class cmd_revision_info(Command):
397
"""Show revision number and revision id for a given revision identifier.
400
takes_args = ['revision_info*']
404
help='Branch to examine, '
405
'rather than the one containing the working directory.',
412
def run(self, revision=None, directory=u'.', revision_info_list=[]):
415
if revision is not None:
416
revs.extend(revision)
417
if revision_info_list is not None:
418
for rev in revision_info_list:
419
revs.append(RevisionSpec.from_string(rev))
421
b = Branch.open_containing(directory)[0]
424
revs.append(RevisionSpec.from_string('-1'))
427
revision_id = rev.as_revision_id(b)
429
revno = '%4d' % (b.revision_id_to_revno(revision_id))
430
except errors.NoSuchRevision:
431
dotted_map = b.get_revision_id_to_revno_map()
432
revno = '.'.join(str(i) for i in dotted_map[revision_id])
433
print '%s %s' % (revno, revision_id)
436
class cmd_add(Command):
437
"""Add specified files or directories.
439
In non-recursive mode, all the named items are added, regardless
440
of whether they were previously ignored. A warning is given if
441
any of the named files are already versioned.
443
In recursive mode (the default), files are treated the same way
444
but the behaviour for directories is different. Directories that
445
are already versioned do not give a warning. All directories,
446
whether already versioned or not, are searched for files or
447
subdirectories that are neither versioned or ignored, and these
448
are added. This search proceeds recursively into versioned
449
directories. If no names are given '.' is assumed.
451
Therefore simply saying 'bzr add' will version all files that
452
are currently unknown.
454
Adding a file whose parent directory is not versioned will
455
implicitly add the parent, and so on up to the root. This means
456
you should never need to explicitly add a directory, they'll just
457
get added when you add a file in the directory.
459
--dry-run will show which files would be added, but not actually
462
--file-ids-from will try to use the file ids from the supplied path.
463
It looks up ids trying to find a matching parent directory with the
464
same filename, and then by pure path. This option is rarely needed
465
but can be useful when adding the same logical file into two
466
branches that will be merged later (without showing the two different
467
adds as a conflict). It is also useful when merging another project
468
into a subdirectory of this one.
470
takes_args = ['file*']
473
help="Don't recursively add the contents of directories."),
475
help="Show what would be done, but don't actually do anything."),
477
Option('file-ids-from',
479
help='Lookup file ids from this tree.'),
481
encoding_type = 'replace'
482
_see_also = ['remove']
484
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
489
if file_ids_from is not None:
491
base_tree, base_path = WorkingTree.open_containing(
493
except errors.NoWorkingTree:
494
base_branch, base_path = Branch.open_containing(
496
base_tree = base_branch.basis_tree()
498
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
499
to_file=self.outf, should_print=(not is_quiet()))
501
action = bzrlib.add.AddAction(to_file=self.outf,
502
should_print=(not is_quiet()))
505
base_tree.lock_read()
507
file_list = self._maybe_expand_globs(file_list)
509
tree = WorkingTree.open_containing(file_list[0])[0]
511
tree = WorkingTree.open_containing(u'.')[0]
512
added, ignored = tree.smart_add(file_list, not
513
no_recurse, action=action, save=not dry_run)
515
if base_tree is not None:
519
for glob in sorted(ignored.keys()):
520
for path in ignored[glob]:
521
self.outf.write("ignored %s matching \"%s\"\n"
525
for glob, paths in ignored.items():
526
match_len += len(paths)
527
self.outf.write("ignored %d file(s).\n" % match_len)
528
self.outf.write("If you wish to add some of these files,"
529
" please add them by name.\n")
532
class cmd_mkdir(Command):
533
"""Create a new versioned directory.
535
This is equivalent to creating the directory and then adding it.
538
takes_args = ['dir+']
539
encoding_type = 'replace'
541
def run(self, dir_list):
544
wt, dd = WorkingTree.open_containing(d)
546
self.outf.write('added %s\n' % d)
549
class cmd_relpath(Command):
550
"""Show path of a file relative to root"""
552
takes_args = ['filename']
556
def run(self, filename):
557
# TODO: jam 20050106 Can relpath return a munged path if
558
# sys.stdout encoding cannot represent it?
559
tree, relpath = WorkingTree.open_containing(filename)
560
self.outf.write(relpath)
561
self.outf.write('\n')
564
class cmd_inventory(Command):
565
"""Show inventory of the current working copy or a revision.
567
It is possible to limit the output to a particular entry
568
type using the --kind option. For example: --kind file.
570
It is also possible to restrict the list of files to a specific
571
set. For example: bzr inventory --show-ids this/file
580
help='List entries of a particular kind: file, directory, symlink.',
583
takes_args = ['file*']
586
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
587
if kind and kind not in ['file', 'directory', 'symlink']:
588
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
590
work_tree, file_list = tree_files(file_list)
591
work_tree.lock_read()
593
if revision is not None:
594
if len(revision) > 1:
595
raise errors.BzrCommandError(
596
'bzr inventory --revision takes exactly one revision'
598
tree = revision[0].as_tree(work_tree.branch)
600
extra_trees = [work_tree]
606
if file_list is not None:
607
file_ids = tree.paths2ids(file_list, trees=extra_trees,
608
require_versioned=True)
609
# find_ids_across_trees may include some paths that don't
611
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
612
for file_id in file_ids if file_id in tree)
614
entries = tree.inventory.entries()
617
if tree is not work_tree:
620
for path, entry in entries:
621
if kind and kind != entry.kind:
624
self.outf.write('%-50s %s\n' % (path, entry.file_id))
626
self.outf.write(path)
627
self.outf.write('\n')
630
class cmd_mv(Command):
631
"""Move or rename a file.
634
bzr mv OLDNAME NEWNAME
636
bzr mv SOURCE... DESTINATION
638
If the last argument is a versioned directory, all the other names
639
are moved into it. Otherwise, there must be exactly two arguments
640
and the file is changed to a new name.
642
If OLDNAME does not exist on the filesystem but is versioned and
643
NEWNAME does exist on the filesystem but is not versioned, mv
644
assumes that the file has been manually moved and only updates
645
its internal inventory to reflect that change.
646
The same is valid when moving many SOURCE files to a DESTINATION.
648
Files cannot be moved between branches.
651
takes_args = ['names*']
652
takes_options = [Option("after", help="Move only the bzr identifier"
653
" of the file, because the file has already been moved."),
655
aliases = ['move', 'rename']
656
encoding_type = 'replace'
658
def run(self, names_list, after=False):
659
if names_list is None:
662
if len(names_list) < 2:
663
raise errors.BzrCommandError("missing file argument")
664
tree, rel_names = tree_files(names_list, canonicalize=False)
667
self._run(tree, names_list, rel_names, after)
671
def _run(self, tree, names_list, rel_names, after):
672
into_existing = osutils.isdir(names_list[-1])
673
if into_existing and len(names_list) == 2:
675
# a. case-insensitive filesystem and change case of dir
676
# b. move directory after the fact (if the source used to be
677
# a directory, but now doesn't exist in the working tree
678
# and the target is an existing directory, just rename it)
679
if (not tree.case_sensitive
680
and rel_names[0].lower() == rel_names[1].lower()):
681
into_existing = False
684
# 'fix' the case of a potential 'from'
685
from_id = tree.path2id(
686
tree.get_canonical_inventory_path(rel_names[0]))
687
if (not osutils.lexists(names_list[0]) and
688
from_id and inv.get_file_kind(from_id) == "directory"):
689
into_existing = False
692
# move into existing directory
693
# All entries reference existing inventory items, so fix them up
694
# for cicp file-systems.
695
rel_names = tree.get_canonical_inventory_paths(rel_names)
696
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
697
self.outf.write("%s => %s\n" % pair)
699
if len(names_list) != 2:
700
raise errors.BzrCommandError('to mv multiple files the'
701
' destination must be a versioned'
704
# for cicp file-systems: the src references an existing inventory
706
src = tree.get_canonical_inventory_path(rel_names[0])
707
# Find the canonical version of the destination: In all cases, the
708
# parent of the target must be in the inventory, so we fetch the
709
# canonical version from there (we do not always *use* the
710
# canonicalized tail portion - we may be attempting to rename the
712
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
713
dest_parent = osutils.dirname(canon_dest)
714
spec_tail = osutils.basename(rel_names[1])
715
# For a CICP file-system, we need to avoid creating 2 inventory
716
# entries that differ only by case. So regardless of the case
717
# we *want* to use (ie, specified by the user or the file-system),
718
# we must always choose to use the case of any existing inventory
719
# items. The only exception to this is when we are attempting a
720
# case-only rename (ie, canonical versions of src and dest are
722
dest_id = tree.path2id(canon_dest)
723
if dest_id is None or tree.path2id(src) == dest_id:
724
# No existing item we care about, so work out what case we
725
# are actually going to use.
727
# If 'after' is specified, the tail must refer to a file on disk.
729
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
731
# pathjoin with an empty tail adds a slash, which breaks
733
dest_parent_fq = tree.basedir
735
dest_tail = osutils.canonical_relpath(
737
osutils.pathjoin(dest_parent_fq, spec_tail))
739
# not 'after', so case as specified is used
740
dest_tail = spec_tail
742
# Use the existing item so 'mv' fails with AlreadyVersioned.
743
dest_tail = os.path.basename(canon_dest)
744
dest = osutils.pathjoin(dest_parent, dest_tail)
745
mutter("attempting to move %s => %s", src, dest)
746
tree.rename_one(src, dest, after=after)
747
self.outf.write("%s => %s\n" % (src, dest))
750
class cmd_pull(Command):
751
"""Turn this branch into a mirror of another branch.
753
This command only works on branches that have not diverged. Branches are
754
considered diverged if the destination branch's most recent commit is one
755
that has not been merged (directly or indirectly) into the parent.
757
If branches have diverged, you can use 'bzr merge' to integrate the changes
758
from one into the other. Once one branch has merged, the other should
759
be able to pull it again.
761
If you want to forget your local changes and just update your branch to
762
match the remote one, use pull --overwrite.
764
If there is no default location set, the first pull will set it. After
765
that, you can omit the location to use the default. To change the
766
default, use --remember. The value will only be saved if the remote
767
location can be accessed.
769
Note: The location can be specified either in the form of a branch,
770
or in the form of a path to a file containing a merge directive generated
774
_see_also = ['push', 'update', 'status-flags']
775
takes_options = ['remember', 'overwrite', 'revision',
776
custom_help('verbose',
777
help='Show logs of pulled revisions.'),
779
help='Branch to pull into, '
780
'rather than the one containing the working directory.',
785
takes_args = ['location?']
786
encoding_type = 'replace'
788
def run(self, location=None, remember=False, overwrite=False,
789
revision=None, verbose=False,
791
# FIXME: too much stuff is in the command class
794
if directory is None:
797
tree_to = WorkingTree.open_containing(directory)[0]
798
branch_to = tree_to.branch
799
except errors.NoWorkingTree:
801
branch_to = Branch.open_containing(directory)[0]
803
possible_transports = []
804
if location is not None:
806
mergeable = bundle.read_mergeable_from_url(location,
807
possible_transports=possible_transports)
808
except errors.NotABundle:
811
stored_loc = branch_to.get_parent()
813
if stored_loc is None:
814
raise errors.BzrCommandError("No pull location known or"
817
display_url = urlutils.unescape_for_display(stored_loc,
820
self.outf.write("Using saved parent location: %s\n" % display_url)
821
location = stored_loc
823
if mergeable is not None:
824
if revision is not None:
825
raise errors.BzrCommandError(
826
'Cannot use -r with merge directives or bundles')
827
mergeable.install_revisions(branch_to.repository)
828
base_revision_id, revision_id, verified = \
829
mergeable.get_merge_request(branch_to.repository)
830
branch_from = branch_to
832
branch_from = Branch.open(location,
833
possible_transports=possible_transports)
835
if branch_to.get_parent() is None or remember:
836
branch_to.set_parent(branch_from.base)
838
if revision is not None:
839
if len(revision) == 1:
840
revision_id = revision[0].as_revision_id(branch_from)
842
raise errors.BzrCommandError(
843
'bzr pull --revision takes one value.')
845
branch_to.lock_write()
847
if tree_to is not None:
848
change_reporter = delta._ChangeReporter(
849
unversioned_filter=tree_to.is_ignored)
850
result = tree_to.pull(branch_from, overwrite, revision_id,
852
possible_transports=possible_transports)
854
result = branch_to.pull(branch_from, overwrite, revision_id)
856
result.report(self.outf)
857
if verbose and result.old_revid != result.new_revid:
858
log.show_branch_change(branch_to, self.outf, result.old_revno,
864
class cmd_push(Command):
865
"""Update a mirror of this branch.
867
The target branch will not have its working tree populated because this
868
is both expensive, and is not supported on remote file systems.
870
Some smart servers or protocols *may* put the working tree in place in
873
This command only works on branches that have not diverged. Branches are
874
considered diverged if the destination branch's most recent commit is one
875
that has not been merged (directly or indirectly) by the source branch.
877
If branches have diverged, you can use 'bzr push --overwrite' to replace
878
the other branch completely, discarding its unmerged changes.
880
If you want to ensure you have the different changes in the other branch,
881
do a merge (see bzr help merge) from the other branch, and commit that.
882
After that you will be able to do a push without '--overwrite'.
884
If there is no default push location set, the first push will set it.
885
After that, you can omit the location to use the default. To change the
886
default, use --remember. The value will only be saved if the remote
887
location can be accessed.
890
_see_also = ['pull', 'update', 'working-trees']
891
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
892
Option('create-prefix',
893
help='Create the path leading up to the branch '
894
'if it does not already exist.'),
896
help='Branch to push from, '
897
'rather than the one containing the working directory.',
901
Option('use-existing-dir',
902
help='By default push will fail if the target'
903
' directory exists, but does not already'
904
' have a control directory. This flag will'
905
' allow push to proceed.'),
907
help='Create a stacked branch that references the public location '
908
'of the parent branch.'),
910
help='Create a stacked branch that refers to another branch '
911
'for the commit history. Only the work not present in the '
912
'referenced branch is included in the branch created.',
915
takes_args = ['location?']
916
encoding_type = 'replace'
918
def run(self, location=None, remember=False, overwrite=False,
919
create_prefix=False, verbose=False, revision=None,
920
use_existing_dir=False, directory=None, stacked_on=None,
922
from bzrlib.push import _show_push_branch
924
# Get the source branch and revision_id
925
if directory is None:
927
br_from = Branch.open_containing(directory)[0]
928
if revision is not None:
929
if len(revision) == 1:
930
revision_id = revision[0].in_history(br_from).rev_id
932
raise errors.BzrCommandError(
933
'bzr push --revision takes one value.')
935
revision_id = br_from.last_revision()
937
# Get the stacked_on branch, if any
938
if stacked_on is not None:
939
stacked_on = urlutils.normalize_url(stacked_on)
941
parent_url = br_from.get_parent()
943
parent = Branch.open(parent_url)
944
stacked_on = parent.get_public_branch()
946
# I considered excluding non-http url's here, thus forcing
947
# 'public' branches only, but that only works for some
948
# users, so it's best to just depend on the user spotting an
949
# error by the feedback given to them. RBC 20080227.
950
stacked_on = parent_url
952
raise errors.BzrCommandError(
953
"Could not determine branch to refer to.")
955
# Get the destination location
957
stored_loc = br_from.get_push_location()
958
if stored_loc is None:
959
raise errors.BzrCommandError(
960
"No push location known or specified.")
962
display_url = urlutils.unescape_for_display(stored_loc,
964
self.outf.write("Using saved push location: %s\n" % display_url)
965
location = stored_loc
967
_show_push_branch(br_from, revision_id, location, self.outf,
968
verbose=verbose, overwrite=overwrite, remember=remember,
969
stacked_on=stacked_on, create_prefix=create_prefix,
970
use_existing_dir=use_existing_dir)
973
class cmd_branch(Command):
974
"""Create a new copy of a branch.
976
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
977
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
978
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
979
is derived from the FROM_LOCATION by stripping a leading scheme or drive
980
identifier, if any. For example, "branch lp:foo-bar" will attempt to
983
To retrieve the branch as of a particular revision, supply the --revision
984
parameter, as in "branch foo/bar -r 5".
987
_see_also = ['checkout']
988
takes_args = ['from_location', 'to_location?']
989
takes_options = ['revision', Option('hardlink',
990
help='Hard-link working tree files where possible.'),
992
help='Create a stacked branch referring to the source branch. '
993
'The new branch will depend on the availability of the source '
994
'branch for all operations.'),
996
help='Do not use a shared repository, even if available.'),
998
aliases = ['get', 'clone']
1000
def run(self, from_location, to_location=None, revision=None,
1001
hardlink=False, stacked=False, standalone=False):
1002
from bzrlib.tag import _merge_tags_if_possible
1003
if revision is None:
1005
elif len(revision) > 1:
1006
raise errors.BzrCommandError(
1007
'bzr branch --revision takes exactly 1 revision value')
1009
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1013
if len(revision) == 1 and revision[0] is not None:
1014
revision_id = revision[0].as_revision_id(br_from)
1016
# FIXME - wt.last_revision, fallback to branch, fall back to
1017
# None or perhaps NULL_REVISION to mean copy nothing
1019
revision_id = br_from.last_revision()
1020
if to_location is None:
1021
to_location = urlutils.derive_to_location(from_location)
1022
to_transport = transport.get_transport(to_location)
1024
to_transport.mkdir('.')
1025
except errors.FileExists:
1026
raise errors.BzrCommandError('Target directory "%s" already'
1027
' exists.' % to_location)
1028
except errors.NoSuchFile:
1029
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1032
# preserve whatever source format we have.
1033
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1034
possible_transports=[to_transport],
1035
accelerator_tree=accelerator_tree,
1036
hardlink=hardlink, stacked=stacked,
1037
force_new_repo=standalone,
1038
source_branch=br_from)
1039
branch = dir.open_branch()
1040
except errors.NoSuchRevision:
1041
to_transport.delete_tree('.')
1042
msg = "The branch %s has no revision %s." % (from_location,
1044
raise errors.BzrCommandError(msg)
1045
_merge_tags_if_possible(br_from, branch)
1046
# If the source branch is stacked, the new branch may
1047
# be stacked whether we asked for that explicitly or not.
1048
# We therefore need a try/except here and not just 'if stacked:'
1050
note('Created new stacked branch referring to %s.' %
1051
branch.get_stacked_on_url())
1052
except (errors.NotStacked, errors.UnstackableBranchFormat,
1053
errors.UnstackableRepositoryFormat), e:
1054
note('Branched %d revision(s).' % branch.revno())
1059
class cmd_checkout(Command):
1060
"""Create a new checkout of an existing branch.
1062
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1063
the branch found in '.'. This is useful if you have removed the working tree
1064
or if it was never created - i.e. if you pushed the branch to its current
1065
location using SFTP.
1067
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1068
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1069
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1070
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1071
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1074
To retrieve the branch as of a particular revision, supply the --revision
1075
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1076
out of date [so you cannot commit] but it may be useful (i.e. to examine old
1080
_see_also = ['checkouts', 'branch']
1081
takes_args = ['branch_location?', 'to_location?']
1082
takes_options = ['revision',
1083
Option('lightweight',
1084
help="Perform a lightweight checkout. Lightweight "
1085
"checkouts depend on access to the branch for "
1086
"every operation. Normal checkouts can perform "
1087
"common operations like diff and status without "
1088
"such access, and also support local commits."
1090
Option('files-from', type=str,
1091
help="Get file contents from this tree."),
1093
help='Hard-link working tree files where possible.'
1098
def run(self, branch_location=None, to_location=None, revision=None,
1099
lightweight=False, files_from=None, hardlink=False):
1100
if revision is None:
1102
elif len(revision) > 1:
1103
raise errors.BzrCommandError(
1104
'bzr checkout --revision takes exactly 1 revision value')
1105
if branch_location is None:
1106
branch_location = osutils.getcwd()
1107
to_location = branch_location
1108
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1110
if files_from is not None:
1111
accelerator_tree = WorkingTree.open(files_from)
1112
if len(revision) == 1 and revision[0] is not None:
1113
revision_id = revision[0].as_revision_id(source)
1116
if to_location is None:
1117
to_location = urlutils.derive_to_location(branch_location)
1118
# if the source and to_location are the same,
1119
# and there is no working tree,
1120
# then reconstitute a branch
1121
if (osutils.abspath(to_location) ==
1122
osutils.abspath(branch_location)):
1124
source.bzrdir.open_workingtree()
1125
except errors.NoWorkingTree:
1126
source.bzrdir.create_workingtree(revision_id)
1128
source.create_checkout(to_location, revision_id, lightweight,
1129
accelerator_tree, hardlink)
1132
class cmd_renames(Command):
1133
"""Show list of renamed files.
1135
# TODO: Option to show renames between two historical versions.
1137
# TODO: Only show renames under dir, rather than in the whole branch.
1138
_see_also = ['status']
1139
takes_args = ['dir?']
1142
def run(self, dir=u'.'):
1143
tree = WorkingTree.open_containing(dir)[0]
1146
new_inv = tree.inventory
1147
old_tree = tree.basis_tree()
1148
old_tree.lock_read()
1150
old_inv = old_tree.inventory
1152
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1153
for f, paths, c, v, p, n, k, e in iterator:
1154
if paths[0] == paths[1]:
1158
renames.append(paths)
1160
for old_name, new_name in renames:
1161
self.outf.write("%s => %s\n" % (old_name, new_name))
1168
class cmd_update(Command):
1169
"""Update a tree to have the latest code committed to its branch.
1171
This will perform a merge into the working tree, and may generate
1172
conflicts. If you have any local changes, you will still
1173
need to commit them after the update for the update to be complete.
1175
If you want to discard your local changes, you can just do a
1176
'bzr revert' instead of 'bzr commit' after the update.
1179
_see_also = ['pull', 'working-trees', 'status-flags']
1180
takes_args = ['dir?']
1183
def run(self, dir='.'):
1184
tree = WorkingTree.open_containing(dir)[0]
1185
possible_transports = []
1186
master = tree.branch.get_master_branch(
1187
possible_transports=possible_transports)
1188
if master is not None:
1191
tree.lock_tree_write()
1193
existing_pending_merges = tree.get_parent_ids()[1:]
1194
last_rev = _mod_revision.ensure_null(tree.last_revision())
1195
if last_rev == _mod_revision.ensure_null(
1196
tree.branch.last_revision()):
1197
# may be up to date, check master too.
1198
if master is None or last_rev == _mod_revision.ensure_null(
1199
master.last_revision()):
1200
revno = tree.branch.revision_id_to_revno(last_rev)
1201
note("Tree is up to date at revision %d." % (revno,))
1203
conflicts = tree.update(
1204
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1205
possible_transports=possible_transports)
1206
revno = tree.branch.revision_id_to_revno(
1207
_mod_revision.ensure_null(tree.last_revision()))
1208
note('Updated to revision %d.' % (revno,))
1209
if tree.get_parent_ids()[1:] != existing_pending_merges:
1210
note('Your local commits will now show as pending merges with '
1211
"'bzr status', and can be committed with 'bzr commit'.")
1220
class cmd_info(Command):
1221
"""Show information about a working tree, branch or repository.
1223
This command will show all known locations and formats associated to the
1224
tree, branch or repository. Statistical information is included with
1227
Branches and working trees will also report any missing revisions.
1229
_see_also = ['revno', 'working-trees', 'repositories']
1230
takes_args = ['location?']
1231
takes_options = ['verbose']
1232
encoding_type = 'replace'
1235
def run(self, location=None, verbose=False):
1240
from bzrlib.info import show_bzrdir_info
1241
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1242
verbose=noise_level, outfile=self.outf)
1245
class cmd_remove(Command):
1246
"""Remove files or directories.
1248
This makes bzr stop tracking changes to the specified files. bzr will delete
1249
them if they can easily be recovered using revert. If no options or
1250
parameters are given bzr will scan for files that are being tracked by bzr
1251
but missing in your tree and stop tracking them for you.
1253
takes_args = ['file*']
1254
takes_options = ['verbose',
1255
Option('new', help='Only remove files that have never been committed.'),
1256
RegistryOption.from_kwargs('file-deletion-strategy',
1257
'The file deletion mode to be used.',
1258
title='Deletion Strategy', value_switches=True, enum_switch=False,
1259
safe='Only delete files if they can be'
1260
' safely recovered (default).',
1261
keep="Don't delete any files.",
1262
force='Delete all the specified files, even if they can not be '
1263
'recovered and even if they are non-empty directories.')]
1264
aliases = ['rm', 'del']
1265
encoding_type = 'replace'
1267
def run(self, file_list, verbose=False, new=False,
1268
file_deletion_strategy='safe'):
1269
tree, file_list = tree_files(file_list)
1271
if file_list is not None:
1272
file_list = [f for f in file_list]
1276
# Heuristics should probably all move into tree.remove_smart or
1279
added = tree.changes_from(tree.basis_tree(),
1280
specific_files=file_list).added
1281
file_list = sorted([f[0] for f in added], reverse=True)
1282
if len(file_list) == 0:
1283
raise errors.BzrCommandError('No matching files.')
1284
elif file_list is None:
1285
# missing files show up in iter_changes(basis) as
1286
# versioned-with-no-kind.
1288
for change in tree.iter_changes(tree.basis_tree()):
1289
# Find paths in the working tree that have no kind:
1290
if change[1][1] is not None and change[6][1] is None:
1291
missing.append(change[1][1])
1292
file_list = sorted(missing, reverse=True)
1293
file_deletion_strategy = 'keep'
1294
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1295
keep_files=file_deletion_strategy=='keep',
1296
force=file_deletion_strategy=='force')
1301
class cmd_file_id(Command):
1302
"""Print file_id of a particular file or directory.
1304
The file_id is assigned when the file is first added and remains the
1305
same through all revisions where the file exists, even when it is
1310
_see_also = ['inventory', 'ls']
1311
takes_args = ['filename']
1314
def run(self, filename):
1315
tree, relpath = WorkingTree.open_containing(filename)
1316
i = tree.path2id(relpath)
1318
raise errors.NotVersionedError(filename)
1320
self.outf.write(i + '\n')
1323
class cmd_file_path(Command):
1324
"""Print path of file_ids to a file or directory.
1326
This prints one line for each directory down to the target,
1327
starting at the branch root.
1331
takes_args = ['filename']
1334
def run(self, filename):
1335
tree, relpath = WorkingTree.open_containing(filename)
1336
fid = tree.path2id(relpath)
1338
raise errors.NotVersionedError(filename)
1339
segments = osutils.splitpath(relpath)
1340
for pos in range(1, len(segments) + 1):
1341
path = osutils.joinpath(segments[:pos])
1342
self.outf.write("%s\n" % tree.path2id(path))
1345
class cmd_reconcile(Command):
1346
"""Reconcile bzr metadata in a branch.
1348
This can correct data mismatches that may have been caused by
1349
previous ghost operations or bzr upgrades. You should only
1350
need to run this command if 'bzr check' or a bzr developer
1351
advises you to run it.
1353
If a second branch is provided, cross-branch reconciliation is
1354
also attempted, which will check that data like the tree root
1355
id which was not present in very early bzr versions is represented
1356
correctly in both branches.
1358
At the same time it is run it may recompress data resulting in
1359
a potential saving in disk space or performance gain.
1361
The branch *MUST* be on a listable system such as local disk or sftp.
1364
_see_also = ['check']
1365
takes_args = ['branch?']
1367
def run(self, branch="."):
1368
from bzrlib.reconcile import reconcile
1369
dir = bzrdir.BzrDir.open(branch)
1373
class cmd_revision_history(Command):
1374
"""Display the list of revision ids on a branch."""
1377
takes_args = ['location?']
1382
def run(self, location="."):
1383
branch = Branch.open_containing(location)[0]
1384
for revid in branch.revision_history():
1385
self.outf.write(revid)
1386
self.outf.write('\n')
1389
class cmd_ancestry(Command):
1390
"""List all revisions merged into this branch."""
1392
_see_also = ['log', 'revision-history']
1393
takes_args = ['location?']
1398
def run(self, location="."):
1400
wt = WorkingTree.open_containing(location)[0]
1401
except errors.NoWorkingTree:
1402
b = Branch.open(location)
1403
last_revision = b.last_revision()
1406
last_revision = wt.last_revision()
1408
revision_ids = b.repository.get_ancestry(last_revision)
1410
for revision_id in revision_ids:
1411
self.outf.write(revision_id + '\n')
1414
class cmd_init(Command):
1415
"""Make a directory into a versioned branch.
1417
Use this to create an empty branch, or before importing an
1420
If there is a repository in a parent directory of the location, then
1421
the history of the branch will be stored in the repository. Otherwise
1422
init creates a standalone branch which carries its own history
1423
in the .bzr directory.
1425
If there is already a branch at the location but it has no working tree,
1426
the tree can be populated with 'bzr checkout'.
1428
Recipe for importing a tree of files::
1434
bzr commit -m "imported project"
1437
_see_also = ['init-repository', 'branch', 'checkout']
1438
takes_args = ['location?']
1440
Option('create-prefix',
1441
help='Create the path leading up to the branch '
1442
'if it does not already exist.'),
1443
RegistryOption('format',
1444
help='Specify a format for this branch. '
1445
'See "help formats".',
1446
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1447
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1448
value_switches=True,
1449
title="Branch Format",
1451
Option('append-revisions-only',
1452
help='Never change revnos or the existing log.'
1453
' Append revisions to it only.')
1455
def run(self, location=None, format=None, append_revisions_only=False,
1456
create_prefix=False):
1458
format = bzrdir.format_registry.make_bzrdir('default')
1459
if location is None:
1462
to_transport = transport.get_transport(location)
1464
# The path has to exist to initialize a
1465
# branch inside of it.
1466
# Just using os.mkdir, since I don't
1467
# believe that we want to create a bunch of
1468
# locations if the user supplies an extended path
1470
to_transport.ensure_base()
1471
except errors.NoSuchFile:
1472
if not create_prefix:
1473
raise errors.BzrCommandError("Parent directory of %s"
1475
"\nYou may supply --create-prefix to create all"
1476
" leading parent directories."
1478
_create_prefix(to_transport)
1481
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1482
except errors.NotBranchError:
1483
# really a NotBzrDir error...
1484
create_branch = bzrdir.BzrDir.create_branch_convenience
1485
branch = create_branch(to_transport.base, format=format,
1486
possible_transports=[to_transport])
1487
a_bzrdir = branch.bzrdir
1489
from bzrlib.transport.local import LocalTransport
1490
if a_bzrdir.has_branch():
1491
if (isinstance(to_transport, LocalTransport)
1492
and not a_bzrdir.has_workingtree()):
1493
raise errors.BranchExistsWithoutWorkingTree(location)
1494
raise errors.AlreadyBranchError(location)
1495
branch = a_bzrdir.create_branch()
1496
a_bzrdir.create_workingtree()
1497
if append_revisions_only:
1499
branch.set_append_revisions_only(True)
1500
except errors.UpgradeRequired:
1501
raise errors.BzrCommandError('This branch format cannot be set'
1502
' to append-revisions-only. Try --experimental-branch6')
1504
from bzrlib.info import show_bzrdir_info
1505
show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1508
class cmd_init_repository(Command):
1509
"""Create a shared repository to hold branches.
1511
New branches created under the repository directory will store their
1512
revisions in the repository, not in the branch directory.
1514
If the --no-trees option is used then the branches in the repository
1515
will not have working trees by default.
1518
Create a shared repositories holding just branches::
1520
bzr init-repo --no-trees repo
1523
Make a lightweight checkout elsewhere::
1525
bzr checkout --lightweight repo/trunk trunk-checkout
1530
_see_also = ['init', 'branch', 'checkout', 'repositories']
1531
takes_args = ["location"]
1532
takes_options = [RegistryOption('format',
1533
help='Specify a format for this repository. See'
1534
' "bzr help formats" for details.',
1535
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1536
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1537
value_switches=True, title='Repository format'),
1539
help='Branches in the repository will default to'
1540
' not having a working tree.'),
1542
aliases = ["init-repo"]
1544
def run(self, location, format=None, no_trees=False):
1546
format = bzrdir.format_registry.make_bzrdir('default')
1548
if location is None:
1551
to_transport = transport.get_transport(location)
1552
to_transport.ensure_base()
1554
newdir = format.initialize_on_transport(to_transport)
1555
repo = newdir.create_repository(shared=True)
1556
repo.set_make_working_trees(not no_trees)
1558
from bzrlib.info import show_bzrdir_info
1559
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1562
class cmd_diff(Command):
1563
"""Show differences in the working tree, between revisions or branches.
1565
If no arguments are given, all changes for the current tree are listed.
1566
If files are given, only the changes in those files are listed.
1567
Remote and multiple branches can be compared by using the --old and
1568
--new options. If not provided, the default for both is derived from
1569
the first argument, if any, or the current tree if no arguments are
1572
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1573
produces patches suitable for "patch -p1".
1577
2 - unrepresentable changes
1582
Shows the difference in the working tree versus the last commit::
1586
Difference between the working tree and revision 1::
1590
Difference between revision 2 and revision 1::
1594
Difference between revision 2 and revision 1 for branch xxx::
1598
Show just the differences for file NEWS::
1602
Show the differences in working tree xxx for file NEWS::
1606
Show the differences from branch xxx to this working tree:
1610
Show the differences between two branches for file NEWS::
1612
bzr diff --old xxx --new yyy NEWS
1614
Same as 'bzr diff' but prefix paths with old/ and new/::
1616
bzr diff --prefix old/:new/
1618
_see_also = ['status']
1619
takes_args = ['file*']
1621
Option('diff-options', type=str,
1622
help='Pass these options to the external diff program.'),
1623
Option('prefix', type=str,
1625
help='Set prefixes added to old and new filenames, as '
1626
'two values separated by a colon. (eg "old/:new/").'),
1628
help='Branch/tree to compare from.',
1632
help='Branch/tree to compare to.',
1638
help='Use this command to compare files.',
1642
aliases = ['di', 'dif']
1643
encoding_type = 'exact'
1646
def run(self, revision=None, file_list=None, diff_options=None,
1647
prefix=None, old=None, new=None, using=None):
1648
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1650
if (prefix is None) or (prefix == '0'):
1658
old_label, new_label = prefix.split(":")
1660
raise errors.BzrCommandError(
1661
'--prefix expects two values separated by a colon'
1662
' (eg "old/:new/")')
1664
if revision and len(revision) > 2:
1665
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1666
' one or two revision specifiers')
1668
old_tree, new_tree, specific_files, extra_trees = \
1669
_get_trees_to_diff(file_list, revision, old, new)
1670
return show_diff_trees(old_tree, new_tree, sys.stdout,
1671
specific_files=specific_files,
1672
external_diff_options=diff_options,
1673
old_label=old_label, new_label=new_label,
1674
extra_trees=extra_trees, using=using)
1677
class cmd_deleted(Command):
1678
"""List files deleted in the working tree.
1680
# TODO: Show files deleted since a previous revision, or
1681
# between two revisions.
1682
# TODO: Much more efficient way to do this: read in new
1683
# directories with readdir, rather than stating each one. Same
1684
# level of effort but possibly much less IO. (Or possibly not,
1685
# if the directories are very large...)
1686
_see_also = ['status', 'ls']
1687
takes_options = ['show-ids']
1690
def run(self, show_ids=False):
1691
tree = WorkingTree.open_containing(u'.')[0]
1694
old = tree.basis_tree()
1697
for path, ie in old.inventory.iter_entries():
1698
if not tree.has_id(ie.file_id):
1699
self.outf.write(path)
1701
self.outf.write(' ')
1702
self.outf.write(ie.file_id)
1703
self.outf.write('\n')
1710
class cmd_modified(Command):
1711
"""List files modified in working tree.
1715
_see_also = ['status', 'ls']
1718
help='Write an ascii NUL (\\0) separator '
1719
'between files rather than a newline.')
1723
def run(self, null=False):
1724
tree = WorkingTree.open_containing(u'.')[0]
1725
td = tree.changes_from(tree.basis_tree())
1726
for path, id, kind, text_modified, meta_modified in td.modified:
1728
self.outf.write(path + '\0')
1730
self.outf.write(osutils.quotefn(path) + '\n')
1733
class cmd_added(Command):
1734
"""List files added in working tree.
1738
_see_also = ['status', 'ls']
1741
help='Write an ascii NUL (\\0) separator '
1742
'between files rather than a newline.')
1746
def run(self, null=False):
1747
wt = WorkingTree.open_containing(u'.')[0]
1750
basis = wt.basis_tree()
1753
basis_inv = basis.inventory
1756
if file_id in basis_inv:
1758
if inv.is_root(file_id) and len(basis_inv) == 0:
1760
path = inv.id2path(file_id)
1761
if not os.access(osutils.abspath(path), os.F_OK):
1764
self.outf.write(path + '\0')
1766
self.outf.write(osutils.quotefn(path) + '\n')
1773
class cmd_root(Command):
1774
"""Show the tree root directory.
1776
The root is the nearest enclosing directory with a .bzr control
1779
takes_args = ['filename?']
1781
def run(self, filename=None):
1782
"""Print the branch root."""
1783
tree = WorkingTree.open_containing(filename)[0]
1784
self.outf.write(tree.basedir + '\n')
1787
def _parse_limit(limitstring):
1789
return int(limitstring)
1791
msg = "The limit argument must be an integer."
1792
raise errors.BzrCommandError(msg)
1795
class cmd_log(Command):
1796
"""Show log of a branch, file, or directory.
1798
By default show the log of the branch containing the working directory.
1800
To request a range of logs, you can use the command -r begin..end
1801
-r revision requests a specific revision, -r ..end or -r begin.. are
1805
Log the current branch::
1813
Log the last 10 revisions of a branch::
1815
bzr log -r -10.. http://server/branch
1818
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1820
takes_args = ['location?']
1823
help='Show from oldest to newest.'),
1825
custom_help('verbose',
1826
help='Show files changed in each revision.'),
1830
type=bzrlib.option._parse_revision_str,
1832
help='Show just the specified revision.'
1833
' See also "help revisionspec".'),
1837
help='Show revisions whose message matches this '
1838
'regular expression.',
1842
help='Limit the output to the first N revisions.',
1846
encoding_type = 'replace'
1849
def run(self, location=None, timezone='original',
1858
from bzrlib.log import show_log
1859
direction = (forward and 'forward') or 'reverse'
1861
if change is not None:
1863
raise errors.RangeInChangeOption()
1864
if revision is not None:
1865
raise errors.BzrCommandError(
1866
'--revision and --change are mutually exclusive')
1873
# find the file id to log:
1875
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1879
tree = b.basis_tree()
1880
file_id = tree.path2id(fp)
1882
raise errors.BzrCommandError(
1883
"Path does not have any revision history: %s" %
1887
# FIXME ? log the current subdir only RBC 20060203
1888
if revision is not None \
1889
and len(revision) > 0 and revision[0].get_branch():
1890
location = revision[0].get_branch()
1893
dir, relpath = bzrdir.BzrDir.open_containing(location)
1894
b = dir.open_branch()
1898
rev1, rev2 = _get_revision_range(revision, b, self.name())
1899
if log_format is None:
1900
log_format = log.log_formatter_registry.get_default(b)
1902
lf = log_format(show_ids=show_ids, to_file=self.outf,
1903
show_timezone=timezone,
1904
delta_format=get_verbosity_level())
1910
direction=direction,
1911
start_revision=rev1,
1918
def _get_revision_range(revisionspec_list, branch, command_name):
1919
"""Take the input of a revision option and turn it into a revision range.
1921
It returns RevisionInfo objects which can be used to obtain the rev_id's
1922
of the desired revisons. It does some user input validations.
1924
if revisionspec_list is None:
1927
elif len(revisionspec_list) == 1:
1928
rev1 = rev2 = revisionspec_list[0].in_history(branch)
1929
elif len(revisionspec_list) == 2:
1930
if revisionspec_list[1].get_branch() != revisionspec_list[0
1932
# b is taken from revision[0].get_branch(), and
1933
# show_log will use its revision_history. Having
1934
# different branches will lead to weird behaviors.
1935
raise errors.BzrCommandError(
1936
"bzr %s doesn't accept two revisions in different"
1937
" branches." % command_name)
1938
rev1 = revisionspec_list[0].in_history(branch)
1939
rev2 = revisionspec_list[1].in_history(branch)
1941
raise errors.BzrCommandError(
1942
'bzr %s --revision takes one or two values.' % command_name)
1945
def get_log_format(long=False, short=False, line=False, default='long'):
1946
log_format = default
1950
log_format = 'short'
1956
class cmd_touching_revisions(Command):
1957
"""Return revision-ids which affected a particular file.
1959
A more user-friendly interface is "bzr log FILE".
1963
takes_args = ["filename"]
1966
def run(self, filename):
1967
tree, relpath = WorkingTree.open_containing(filename)
1969
file_id = tree.path2id(relpath)
1970
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1971
self.outf.write("%6d %s\n" % (revno, what))
1974
class cmd_ls(Command):
1975
"""List files in a tree.
1978
_see_also = ['status', 'cat']
1979
takes_args = ['path?']
1980
# TODO: Take a revision or remote path and list that tree instead.
1984
Option('non-recursive',
1985
help='Don\'t recurse into subdirectories.'),
1987
help='Print paths relative to the root of the branch.'),
1988
Option('unknown', help='Print unknown files.'),
1989
Option('versioned', help='Print versioned files.',
1991
Option('ignored', help='Print ignored files.'),
1993
help='Write an ascii NUL (\\0) separator '
1994
'between files rather than a newline.'),
1996
help='List entries of a particular kind: file, directory, symlink.',
2001
def run(self, revision=None, verbose=False,
2002
non_recursive=False, from_root=False,
2003
unknown=False, versioned=False, ignored=False,
2004
null=False, kind=None, show_ids=False, path=None):
2006
if kind and kind not in ('file', 'directory', 'symlink'):
2007
raise errors.BzrCommandError('invalid kind specified')
2009
if verbose and null:
2010
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2011
all = not (unknown or versioned or ignored)
2013
selection = {'I':ignored, '?':unknown, 'V':versioned}
2020
raise errors.BzrCommandError('cannot specify both --from-root'
2024
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2030
if revision is not None or tree is None:
2031
tree = _get_one_revision_tree('ls', revision, branch=branch)
2035
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2036
if fp.startswith(relpath):
2037
fp = osutils.pathjoin(prefix, fp[len(relpath):])
2038
if non_recursive and '/' in fp:
2040
if not all and not selection[fc]:
2042
if kind is not None and fkind != kind:
2044
kindch = entry.kind_character()
2045
outstring = fp + kindch
2047
outstring = '%-8s %s' % (fc, outstring)
2048
if show_ids and fid is not None:
2049
outstring = "%-50s %s" % (outstring, fid)
2050
self.outf.write(outstring + '\n')
2052
self.outf.write(fp + '\0')
2055
self.outf.write(fid)
2056
self.outf.write('\0')
2064
self.outf.write('%-50s %s\n' % (outstring, my_id))
2066
self.outf.write(outstring + '\n')
2071
class cmd_unknowns(Command):
2072
"""List unknown files.
2080
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2081
self.outf.write(osutils.quotefn(f) + '\n')
2084
class cmd_ignore(Command):
2085
"""Ignore specified files or patterns.
2087
See ``bzr help patterns`` for details on the syntax of patterns.
2089
To remove patterns from the ignore list, edit the .bzrignore file.
2090
After adding, editing or deleting that file either indirectly by
2091
using this command or directly by using an editor, be sure to commit
2094
Note: ignore patterns containing shell wildcards must be quoted from
2098
Ignore the top level Makefile::
2100
bzr ignore ./Makefile
2102
Ignore class files in all directories::
2104
bzr ignore "*.class"
2106
Ignore .o files under the lib directory::
2108
bzr ignore "lib/**/*.o"
2110
Ignore .o files under the lib directory::
2112
bzr ignore "RE:lib/.*\.o"
2114
Ignore everything but the "debian" toplevel directory::
2116
bzr ignore "RE:(?!debian/).*"
2119
_see_also = ['status', 'ignored', 'patterns']
2120
takes_args = ['name_pattern*']
2122
Option('old-default-rules',
2123
help='Write out the ignore rules bzr < 0.9 always used.')
2126
def run(self, name_pattern_list=None, old_default_rules=None):
2127
from bzrlib import ignores
2128
if old_default_rules is not None:
2129
# dump the rules and exit
2130
for pattern in ignores.OLD_DEFAULTS:
2133
if not name_pattern_list:
2134
raise errors.BzrCommandError("ignore requires at least one "
2135
"NAME_PATTERN or --old-default-rules")
2136
name_pattern_list = [globbing.normalize_pattern(p)
2137
for p in name_pattern_list]
2138
for name_pattern in name_pattern_list:
2139
if (name_pattern[0] == '/' or
2140
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2141
raise errors.BzrCommandError(
2142
"NAME_PATTERN should not be an absolute path")
2143
tree, relpath = WorkingTree.open_containing(u'.')
2144
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2145
ignored = globbing.Globster(name_pattern_list)
2148
for entry in tree.list_files():
2152
if ignored.match(filename):
2153
matches.append(filename.encode('utf-8'))
2155
if len(matches) > 0:
2156
print "Warning: the following files are version controlled and" \
2157
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2160
class cmd_ignored(Command):
2161
"""List ignored files and the patterns that matched them.
2163
List all the ignored files and the ignore pattern that caused the file to
2166
Alternatively, to list just the files::
2171
encoding_type = 'replace'
2172
_see_also = ['ignore', 'ls']
2176
tree = WorkingTree.open_containing(u'.')[0]
2179
for path, file_class, kind, file_id, entry in tree.list_files():
2180
if file_class != 'I':
2182
## XXX: Slightly inefficient since this was already calculated
2183
pat = tree.is_ignored(path)
2184
self.outf.write('%-50s %s\n' % (path, pat))
2189
class cmd_lookup_revision(Command):
2190
"""Lookup the revision-id from a revision-number
2193
bzr lookup-revision 33
2196
takes_args = ['revno']
2199
def run(self, revno):
2203
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2205
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2208
class cmd_export(Command):
2209
"""Export current or past revision to a destination directory or archive.
2211
If no revision is specified this exports the last committed revision.
2213
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2214
given, try to find the format with the extension. If no extension
2215
is found exports to a directory (equivalent to --format=dir).
2217
If root is supplied, it will be used as the root directory inside
2218
container formats (tar, zip, etc). If it is not supplied it will default
2219
to the exported filename. The root option has no effect for 'dir' format.
2221
If branch is omitted then the branch containing the current working
2222
directory will be used.
2224
Note: Export of tree with non-ASCII filenames to zip is not supported.
2226
================= =========================
2227
Supported formats Autodetected by extension
2228
================= =========================
2231
tbz2 .tar.bz2, .tbz2
2234
================= =========================
2236
takes_args = ['dest', 'branch_or_subdir?']
2239
help="Type of file to export to.",
2244
help="Name of the root directory inside the exported file."),
2246
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2248
from bzrlib.export import export
2250
if branch_or_subdir is None:
2251
tree = WorkingTree.open_containing(u'.')[0]
2255
b, subdir = Branch.open_containing(branch_or_subdir)
2258
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2260
export(rev_tree, dest, format, root, subdir)
2261
except errors.NoSuchExportFormat, e:
2262
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2265
class cmd_cat(Command):
2266
"""Write the contents of a file as of a given revision to standard output.
2268
If no revision is nominated, the last revision is used.
2270
Note: Take care to redirect standard output when using this command on a
2276
Option('name-from-revision', help='The path name in the old tree.'),
2279
takes_args = ['filename']
2280
encoding_type = 'exact'
2283
def run(self, filename, revision=None, name_from_revision=False):
2284
if revision is not None and len(revision) != 1:
2285
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2286
" one revision specifier")
2287
tree, branch, relpath = \
2288
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2291
return self._run(tree, branch, relpath, filename, revision,
2296
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2298
tree = b.basis_tree()
2299
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2301
cur_file_id = tree.path2id(relpath)
2302
old_file_id = rev_tree.path2id(relpath)
2304
if name_from_revision:
2305
if old_file_id is None:
2306
raise errors.BzrCommandError(
2307
"%r is not present in revision %s" % (
2308
filename, rev_tree.get_revision_id()))
2310
content = rev_tree.get_file_text(old_file_id)
2311
elif cur_file_id is not None:
2312
content = rev_tree.get_file_text(cur_file_id)
2313
elif old_file_id is not None:
2314
content = rev_tree.get_file_text(old_file_id)
2316
raise errors.BzrCommandError(
2317
"%r is not present in revision %s" % (
2318
filename, rev_tree.get_revision_id()))
2319
self.outf.write(content)
2322
class cmd_local_time_offset(Command):
2323
"""Show the offset in seconds from GMT to local time."""
2327
print osutils.local_time_offset()
2331
class cmd_commit(Command):
2332
"""Commit changes into a new revision.
2334
If no arguments are given, the entire tree is committed.
2336
If selected files are specified, only changes to those files are
2337
committed. If a directory is specified then the directory and everything
2338
within it is committed.
2340
When excludes are given, they take precedence over selected files.
2341
For example, too commit only changes within foo, but not changes within
2344
bzr commit foo -x foo/bar
2346
If author of the change is not the same person as the committer, you can
2347
specify the author's name using the --author option. The name should be
2348
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2350
A selected-file commit may fail in some cases where the committed
2351
tree would be invalid. Consider::
2356
bzr commit foo -m "committing foo"
2357
bzr mv foo/bar foo/baz
2360
bzr commit foo/bar -m "committing bar but not baz"
2362
In the example above, the last commit will fail by design. This gives
2363
the user the opportunity to decide whether they want to commit the
2364
rename at the same time, separately first, or not at all. (As a general
2365
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2367
Note: A selected-file commit after a merge is not yet supported.
2369
# TODO: Run hooks on tree to-be-committed, and after commit.
2371
# TODO: Strict commit that fails if there are deleted files.
2372
# (what does "deleted files" mean ??)
2374
# TODO: Give better message for -s, --summary, used by tla people
2376
# XXX: verbose currently does nothing
2378
_see_also = ['bugs', 'uncommit']
2379
takes_args = ['selected*']
2381
ListOption('exclude', type=str, short_name='x',
2382
help="Do not consider changes made to a given path."),
2383
Option('message', type=unicode,
2385
help="Description of the new revision."),
2388
help='Commit even if nothing has changed.'),
2389
Option('file', type=str,
2392
help='Take commit message from this file.'),
2394
help="Refuse to commit if there are unknown "
2395
"files in the working tree."),
2396
ListOption('fixes', type=str,
2397
help="Mark a bug as being fixed by this revision."),
2398
Option('author', type=unicode,
2399
help="Set the author's name, if it's different "
2400
"from the committer."),
2402
help="Perform a local commit in a bound "
2403
"branch. Local commits are not pushed to "
2404
"the master branch until a normal commit "
2408
help='When no message is supplied, show the diff along'
2409
' with the status summary in the message editor.'),
2411
aliases = ['ci', 'checkin']
2413
def _get_bug_fix_properties(self, fixes, branch):
2415
# Configure the properties for bug fixing attributes.
2416
for fixed_bug in fixes:
2417
tokens = fixed_bug.split(':')
2418
if len(tokens) != 2:
2419
raise errors.BzrCommandError(
2420
"Invalid bug %s. Must be in the form of 'tag:id'. "
2421
"Commit refused." % fixed_bug)
2422
tag, bug_id = tokens
2424
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2425
except errors.UnknownBugTrackerAbbreviation:
2426
raise errors.BzrCommandError(
2427
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2428
except errors.MalformedBugIdentifier:
2429
raise errors.BzrCommandError(
2430
"Invalid bug identifier for %s. Commit refused."
2432
properties.append('%s fixed' % bug_url)
2433
return '\n'.join(properties)
2435
def run(self, message=None, file=None, verbose=False, selected_list=None,
2436
unchanged=False, strict=False, local=False, fixes=None,
2437
author=None, show_diff=False, exclude=None):
2438
from bzrlib.errors import (
2443
from bzrlib.msgeditor import (
2444
edit_commit_message_encoded,
2445
generate_commit_message_template,
2446
make_commit_message_template_encoded
2449
# TODO: Need a blackbox test for invoking the external editor; may be
2450
# slightly problematic to run this cross-platform.
2452
# TODO: do more checks that the commit will succeed before
2453
# spending the user's valuable time typing a commit message.
2457
tree, selected_list = tree_files(selected_list)
2458
if selected_list == ['']:
2459
# workaround - commit of root of tree should be exactly the same
2460
# as just default commit in that tree, and succeed even though
2461
# selected-file merge commit is not done yet
2466
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2468
properties['bugs'] = bug_property
2470
if local and not tree.branch.get_bound_location():
2471
raise errors.LocalRequiresBoundBranch()
2473
def get_message(commit_obj):
2474
"""Callback to get commit message"""
2475
my_message = message
2476
if my_message is None and not file:
2477
t = make_commit_message_template_encoded(tree,
2478
selected_list, diff=show_diff,
2479
output_encoding=osutils.get_user_encoding())
2480
start_message = generate_commit_message_template(commit_obj)
2481
my_message = edit_commit_message_encoded(t,
2482
start_message=start_message)
2483
if my_message is None:
2484
raise errors.BzrCommandError("please specify a commit"
2485
" message with either --message or --file")
2486
elif my_message and file:
2487
raise errors.BzrCommandError(
2488
"please specify either --message or --file")
2490
my_message = codecs.open(file, 'rt',
2491
osutils.get_user_encoding()).read()
2492
if my_message == "":
2493
raise errors.BzrCommandError("empty commit message specified")
2497
tree.commit(message_callback=get_message,
2498
specific_files=selected_list,
2499
allow_pointless=unchanged, strict=strict, local=local,
2500
reporter=None, verbose=verbose, revprops=properties,
2502
exclude=safe_relpath_files(tree, exclude))
2503
except PointlessCommit:
2504
# FIXME: This should really happen before the file is read in;
2505
# perhaps prepare the commit; get the message; then actually commit
2506
raise errors.BzrCommandError("no changes to commit."
2507
" use --unchanged to commit anyhow")
2508
except ConflictsInTree:
2509
raise errors.BzrCommandError('Conflicts detected in working '
2510
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2512
except StrictCommitFailed:
2513
raise errors.BzrCommandError("Commit refused because there are"
2514
" unknown files in the working tree.")
2515
except errors.BoundBranchOutOfDate, e:
2516
raise errors.BzrCommandError(str(e) + "\n"
2517
'To commit to master branch, run update and then commit.\n'
2518
'You can also pass --local to commit to continue working '
2522
class cmd_check(Command):
2523
"""Validate working tree structure, branch consistency and repository history.
2525
This command checks various invariants about branch and repository storage
2526
to detect data corruption or bzr bugs.
2528
The working tree and branch checks will only give output if a problem is
2529
detected. The output fields of the repository check are:
2531
revisions: This is just the number of revisions checked. It doesn't
2533
versionedfiles: This is just the number of versionedfiles checked. It
2534
doesn't indicate a problem.
2535
unreferenced ancestors: Texts that are ancestors of other texts, but
2536
are not properly referenced by the revision ancestry. This is a
2537
subtle problem that Bazaar can work around.
2538
unique file texts: This is the total number of unique file contents
2539
seen in the checked revisions. It does not indicate a problem.
2540
repeated file texts: This is the total number of repeated texts seen
2541
in the checked revisions. Texts can be repeated when their file
2542
entries are modified, but the file contents are not. It does not
2545
If no restrictions are specified, all Bazaar data that is found at the given
2546
location will be checked.
2550
Check the tree and branch at 'foo'::
2552
bzr check --tree --branch foo
2554
Check only the repository at 'bar'::
2556
bzr check --repo bar
2558
Check everything at 'baz'::
2563
_see_also = ['reconcile']
2564
takes_args = ['path?']
2565
takes_options = ['verbose',
2566
Option('branch', help="Check the branch related to the"
2567
" current directory."),
2568
Option('repo', help="Check the repository related to the"
2569
" current directory."),
2570
Option('tree', help="Check the working tree related to"
2571
" the current directory.")]
2573
def run(self, path=None, verbose=False, branch=False, repo=False,
2575
from bzrlib.check import check_dwim
2578
if not branch and not repo and not tree:
2579
branch = repo = tree = True
2580
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2583
class cmd_upgrade(Command):
2584
"""Upgrade branch storage to current format.
2586
The check command or bzr developers may sometimes advise you to run
2587
this command. When the default format has changed you may also be warned
2588
during other operations to upgrade.
2591
_see_also = ['check']
2592
takes_args = ['url?']
2594
RegistryOption('format',
2595
help='Upgrade to a specific format. See "bzr help'
2596
' formats" for details.',
2597
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2598
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2599
value_switches=True, title='Branch format'),
2602
def run(self, url='.', format=None):
2603
from bzrlib.upgrade import upgrade
2605
format = bzrdir.format_registry.make_bzrdir('default')
2606
upgrade(url, format)
2609
class cmd_whoami(Command):
2610
"""Show or set bzr user id.
2613
Show the email of the current user::
2617
Set the current user::
2619
bzr whoami "Frank Chu <fchu@example.com>"
2621
takes_options = [ Option('email',
2622
help='Display email address only.'),
2624
help='Set identity for the current branch instead of '
2627
takes_args = ['name?']
2628
encoding_type = 'replace'
2631
def run(self, email=False, branch=False, name=None):
2633
# use branch if we're inside one; otherwise global config
2635
c = Branch.open_containing('.')[0].get_config()
2636
except errors.NotBranchError:
2637
c = config.GlobalConfig()
2639
self.outf.write(c.user_email() + '\n')
2641
self.outf.write(c.username() + '\n')
2644
# display a warning if an email address isn't included in the given name.
2646
config.extract_email_address(name)
2647
except errors.NoEmailInUsername, e:
2648
warning('"%s" does not seem to contain an email address. '
2649
'This is allowed, but not recommended.', name)
2651
# use global config unless --branch given
2653
c = Branch.open_containing('.')[0].get_config()
2655
c = config.GlobalConfig()
2656
c.set_user_option('email', name)
2659
class cmd_nick(Command):
2660
"""Print or set the branch nickname.
2662
If unset, the tree root directory name is used as the nickname.
2663
To print the current nickname, execute with no argument.
2665
Bound branches use the nickname of its master branch unless it is set
2669
_see_also = ['info']
2670
takes_args = ['nickname?']
2671
def run(self, nickname=None):
2672
branch = Branch.open_containing(u'.')[0]
2673
if nickname is None:
2674
self.printme(branch)
2676
branch.nick = nickname
2679
def printme(self, branch):
2683
class cmd_alias(Command):
2684
"""Set/unset and display aliases.
2687
Show the current aliases::
2691
Show the alias specified for 'll'::
2695
Set an alias for 'll'::
2697
bzr alias ll="log --line -r-10..-1"
2699
To remove an alias for 'll'::
2701
bzr alias --remove ll
2704
takes_args = ['name?']
2706
Option('remove', help='Remove the alias.'),
2709
def run(self, name=None, remove=False):
2711
self.remove_alias(name)
2713
self.print_aliases()
2715
equal_pos = name.find('=')
2717
self.print_alias(name)
2719
self.set_alias(name[:equal_pos], name[equal_pos+1:])
2721
def remove_alias(self, alias_name):
2722
if alias_name is None:
2723
raise errors.BzrCommandError(
2724
'bzr alias --remove expects an alias to remove.')
2725
# If alias is not found, print something like:
2726
# unalias: foo: not found
2727
c = config.GlobalConfig()
2728
c.unset_alias(alias_name)
2731
def print_aliases(self):
2732
"""Print out the defined aliases in a similar format to bash."""
2733
aliases = config.GlobalConfig().get_aliases()
2734
for key, value in sorted(aliases.iteritems()):
2735
self.outf.write('bzr alias %s="%s"\n' % (key, value))
2738
def print_alias(self, alias_name):
2739
from bzrlib.commands import get_alias
2740
alias = get_alias(alias_name)
2742
self.outf.write("bzr alias: %s: not found\n" % alias_name)
2745
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2747
def set_alias(self, alias_name, alias_command):
2748
"""Save the alias in the global config."""
2749
c = config.GlobalConfig()
2750
c.set_alias(alias_name, alias_command)
2753
class cmd_selftest(Command):
2754
"""Run internal test suite.
2756
If arguments are given, they are regular expressions that say which tests
2757
should run. Tests matching any expression are run, and other tests are
2760
Alternatively if --first is given, matching tests are run first and then
2761
all other tests are run. This is useful if you have been working in a
2762
particular area, but want to make sure nothing else was broken.
2764
If --exclude is given, tests that match that regular expression are
2765
excluded, regardless of whether they match --first or not.
2767
To help catch accidential dependencies between tests, the --randomize
2768
option is useful. In most cases, the argument used is the word 'now'.
2769
Note that the seed used for the random number generator is displayed
2770
when this option is used. The seed can be explicitly passed as the
2771
argument to this option if required. This enables reproduction of the
2772
actual ordering used if and when an order sensitive problem is encountered.
2774
If --list-only is given, the tests that would be run are listed. This is
2775
useful when combined with --first, --exclude and/or --randomize to
2776
understand their impact. The test harness reports "Listed nn tests in ..."
2777
instead of "Ran nn tests in ..." when list mode is enabled.
2779
If the global option '--no-plugins' is given, plugins are not loaded
2780
before running the selftests. This has two effects: features provided or
2781
modified by plugins will not be tested, and tests provided by plugins will
2784
Tests that need working space on disk use a common temporary directory,
2785
typically inside $TMPDIR or /tmp.
2788
Run only tests relating to 'ignore'::
2792
Disable plugins and list tests as they're run::
2794
bzr --no-plugins selftest -v
2796
# NB: this is used from the class without creating an instance, which is
2797
# why it does not have a self parameter.
2798
def get_transport_type(typestring):
2799
"""Parse and return a transport specifier."""
2800
if typestring == "sftp":
2801
from bzrlib.transport.sftp import SFTPAbsoluteServer
2802
return SFTPAbsoluteServer
2803
if typestring == "memory":
2804
from bzrlib.transport.memory import MemoryServer
2806
if typestring == "fakenfs":
2807
from bzrlib.transport.fakenfs import FakeNFSServer
2808
return FakeNFSServer
2809
msg = "No known transport type %s. Supported types are: sftp\n" %\
2811
raise errors.BzrCommandError(msg)
2814
takes_args = ['testspecs*']
2815
takes_options = ['verbose',
2817
help='Stop when one test fails.',
2821
help='Use a different transport by default '
2822
'throughout the test suite.',
2823
type=get_transport_type),
2825
help='Run the benchmarks rather than selftests.'),
2826
Option('lsprof-timed',
2827
help='Generate lsprof output for benchmarked'
2828
' sections of code.'),
2829
Option('cache-dir', type=str,
2830
help='Cache intermediate benchmark output in this '
2833
help='Run all tests, but run specified tests first.',
2837
help='List the tests instead of running them.'),
2838
Option('randomize', type=str, argname="SEED",
2839
help='Randomize the order of tests using the given'
2840
' seed or "now" for the current time.'),
2841
Option('exclude', type=str, argname="PATTERN",
2843
help='Exclude tests that match this regular'
2845
Option('strict', help='Fail on missing dependencies or '
2847
Option('load-list', type=str, argname='TESTLISTFILE',
2848
help='Load a test id list from a text file.'),
2849
ListOption('debugflag', type=str, short_name='E',
2850
help='Turn on a selftest debug flag.'),
2851
ListOption('starting-with', type=str, argname='TESTID',
2852
param_name='starting_with', short_name='s',
2854
'Load only the tests starting with TESTID.'),
2856
encoding_type = 'replace'
2858
def run(self, testspecs_list=None, verbose=False, one=False,
2859
transport=None, benchmark=None,
2860
lsprof_timed=None, cache_dir=None,
2861
first=False, list_only=False,
2862
randomize=None, exclude=None, strict=False,
2863
load_list=None, debugflag=None, starting_with=None):
2864
from bzrlib.tests import selftest
2865
import bzrlib.benchmarks as benchmarks
2866
from bzrlib.benchmarks import tree_creator
2868
# Make deprecation warnings visible, unless -Werror is set
2869
symbol_versioning.activate_deprecation_warnings(override=False)
2871
if cache_dir is not None:
2872
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2874
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2875
print ' %s (%s python%s)' % (
2877
bzrlib.version_string,
2878
bzrlib._format_version_tuple(sys.version_info),
2881
if testspecs_list is not None:
2882
pattern = '|'.join(testspecs_list)
2886
test_suite_factory = benchmarks.test_suite
2887
# Unless user explicitly asks for quiet, be verbose in benchmarks
2888
verbose = not is_quiet()
2889
# TODO: should possibly lock the history file...
2890
benchfile = open(".perf_history", "at", buffering=1)
2892
test_suite_factory = None
2895
result = selftest(verbose=verbose,
2897
stop_on_failure=one,
2898
transport=transport,
2899
test_suite_factory=test_suite_factory,
2900
lsprof_timed=lsprof_timed,
2901
bench_history=benchfile,
2902
matching_tests_first=first,
2903
list_only=list_only,
2904
random_seed=randomize,
2905
exclude_pattern=exclude,
2907
load_list=load_list,
2908
debug_flags=debugflag,
2909
starting_with=starting_with,
2912
if benchfile is not None:
2915
note('tests passed')
2917
note('tests failed')
2918
return int(not result)
2921
class cmd_version(Command):
2922
"""Show version of bzr."""
2924
encoding_type = 'replace'
2926
Option("short", help="Print just the version number."),
2930
def run(self, short=False):
2931
from bzrlib.version import show_version
2933
self.outf.write(bzrlib.version_string + '\n')
2935
show_version(to_file=self.outf)
2938
class cmd_rocks(Command):
2939
"""Statement of optimism."""
2945
print "It sure does!"
2948
class cmd_find_merge_base(Command):
2949
"""Find and print a base revision for merging two branches."""
2950
# TODO: Options to specify revisions on either side, as if
2951
# merging only part of the history.
2952
takes_args = ['branch', 'other']
2956
def run(self, branch, other):
2957
from bzrlib.revision import ensure_null
2959
branch1 = Branch.open_containing(branch)[0]
2960
branch2 = Branch.open_containing(other)[0]
2965
last1 = ensure_null(branch1.last_revision())
2966
last2 = ensure_null(branch2.last_revision())
2968
graph = branch1.repository.get_graph(branch2.repository)
2969
base_rev_id = graph.find_unique_lca(last1, last2)
2971
print 'merge base is revision %s' % base_rev_id
2978
class cmd_merge(Command):
2979
"""Perform a three-way merge.
2981
The source of the merge can be specified either in the form of a branch,
2982
or in the form of a path to a file containing a merge directive generated
2983
with bzr send. If neither is specified, the default is the upstream branch
2984
or the branch most recently merged using --remember.
2986
When merging a branch, by default the tip will be merged. To pick a different
2987
revision, pass --revision. If you specify two values, the first will be used as
2988
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2989
available revisions, like this is commonly referred to as "cherrypicking".
2991
Revision numbers are always relative to the branch being merged.
2993
By default, bzr will try to merge in all new work from the other
2994
branch, automatically determining an appropriate base. If this
2995
fails, you may need to give an explicit base.
2997
Merge will do its best to combine the changes in two branches, but there
2998
are some kinds of problems only a human can fix. When it encounters those,
2999
it will mark a conflict. A conflict means that you need to fix something,
3000
before you should commit.
3002
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
3004
If there is no default branch set, the first merge will set it. After
3005
that, you can omit the branch to use the default. To change the
3006
default, use --remember. The value will only be saved if the remote
3007
location can be accessed.
3009
The results of the merge are placed into the destination working
3010
directory, where they can be reviewed (with bzr diff), tested, and then
3011
committed to record the result of the merge.
3013
merge refuses to run if there are any uncommitted changes, unless
3017
To merge the latest revision from bzr.dev::
3019
bzr merge ../bzr.dev
3021
To merge changes up to and including revision 82 from bzr.dev::
3023
bzr merge -r 82 ../bzr.dev
3025
To merge the changes introduced by 82, without previous changes::
3027
bzr merge -r 81..82 ../bzr.dev
3029
To apply a merge directive contained in in /tmp/merge:
3031
bzr merge /tmp/merge
3034
encoding_type = 'exact'
3035
_see_also = ['update', 'remerge', 'status-flags']
3036
takes_args = ['location?']
3041
help='Merge even if the destination tree has uncommitted changes.'),
3045
Option('show-base', help="Show base revision text in "
3047
Option('uncommitted', help='Apply uncommitted changes'
3048
' from a working copy, instead of branch changes.'),
3049
Option('pull', help='If the destination is already'
3050
' completely merged into the source, pull from the'
3051
' source rather than merging. When this happens,'
3052
' you do not need to commit the result.'),
3054
help='Branch to merge into, '
3055
'rather than the one containing the working directory.',
3059
Option('preview', help='Instead of merging, show a diff of the merge.')
3062
def run(self, location=None, revision=None, force=False,
3063
merge_type=None, show_base=False, reprocess=None, remember=False,
3064
uncommitted=False, pull=False,
3068
if merge_type is None:
3069
merge_type = _mod_merge.Merge3Merger
3071
if directory is None: directory = u'.'
3072
possible_transports = []
3074
allow_pending = True
3075
verified = 'inapplicable'
3076
tree = WorkingTree.open_containing(directory)[0]
3077
change_reporter = delta._ChangeReporter(
3078
unversioned_filter=tree.is_ignored)
3081
pb = ui.ui_factory.nested_progress_bar()
3082
cleanups.append(pb.finished)
3084
cleanups.append(tree.unlock)
3085
if location is not None:
3087
mergeable = bundle.read_mergeable_from_url(location,
3088
possible_transports=possible_transports)
3089
except errors.NotABundle:
3093
raise errors.BzrCommandError('Cannot use --uncommitted'
3094
' with bundles or merge directives.')
3096
if revision is not None:
3097
raise errors.BzrCommandError(
3098
'Cannot use -r with merge directives or bundles')
3099
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3102
if merger is None and uncommitted:
3103
if revision is not None and len(revision) > 0:
3104
raise errors.BzrCommandError('Cannot use --uncommitted and'
3105
' --revision at the same time.')
3106
location = self._select_branch_location(tree, location)[0]
3107
other_tree, other_path = WorkingTree.open_containing(location)
3108
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3110
allow_pending = False
3111
if other_path != '':
3112
merger.interesting_files = [other_path]
3115
merger, allow_pending = self._get_merger_from_branch(tree,
3116
location, revision, remember, possible_transports, pb)
3118
merger.merge_type = merge_type
3119
merger.reprocess = reprocess
3120
merger.show_base = show_base
3121
self.sanity_check_merger(merger)
3122
if (merger.base_rev_id == merger.other_rev_id and
3123
merger.other_rev_id is not None):
3124
note('Nothing to do.')
3127
if merger.interesting_files is not None:
3128
raise errors.BzrCommandError('Cannot pull individual files')
3129
if (merger.base_rev_id == tree.last_revision()):
3130
result = tree.pull(merger.other_branch, False,
3131
merger.other_rev_id)
3132
result.report(self.outf)
3134
merger.check_basis(not force)
3136
return self._do_preview(merger)
3138
return self._do_merge(merger, change_reporter, allow_pending,
3141
for cleanup in reversed(cleanups):
3144
def _do_preview(self, merger):
3145
from bzrlib.diff import show_diff_trees
3146
tree_merger = merger.make_merger()
3147
tt = tree_merger.make_preview_transform()
3149
result_tree = tt.get_preview_tree()
3150
show_diff_trees(merger.this_tree, result_tree, self.outf,
3151
old_label='', new_label='')
3155
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3156
merger.change_reporter = change_reporter
3157
conflict_count = merger.do_merge()
3159
merger.set_pending()
3160
if verified == 'failed':
3161
warning('Preview patch does not match changes')
3162
if conflict_count != 0:
3167
def sanity_check_merger(self, merger):
3168
if (merger.show_base and
3169
not merger.merge_type is _mod_merge.Merge3Merger):
3170
raise errors.BzrCommandError("Show-base is not supported for this"
3171
" merge type. %s" % merger.merge_type)
3172
if merger.reprocess is None:
3173
if merger.show_base:
3174
merger.reprocess = False
3176
# Use reprocess if the merger supports it
3177
merger.reprocess = merger.merge_type.supports_reprocess
3178
if merger.reprocess and not merger.merge_type.supports_reprocess:
3179
raise errors.BzrCommandError("Conflict reduction is not supported"
3180
" for merge type %s." %
3182
if merger.reprocess and merger.show_base:
3183
raise errors.BzrCommandError("Cannot do conflict reduction and"
3186
def _get_merger_from_branch(self, tree, location, revision, remember,
3187
possible_transports, pb):
3188
"""Produce a merger from a location, assuming it refers to a branch."""
3189
from bzrlib.tag import _merge_tags_if_possible
3190
# find the branch locations
3191
other_loc, user_location = self._select_branch_location(tree, location,
3193
if revision is not None and len(revision) == 2:
3194
base_loc, _unused = self._select_branch_location(tree,
3195
location, revision, 0)
3197
base_loc = other_loc
3199
other_branch, other_path = Branch.open_containing(other_loc,
3200
possible_transports)
3201
if base_loc == other_loc:
3202
base_branch = other_branch
3204
base_branch, base_path = Branch.open_containing(base_loc,
3205
possible_transports)
3206
# Find the revision ids
3207
if revision is None or len(revision) < 1 or revision[-1] is None:
3208
other_revision_id = _mod_revision.ensure_null(
3209
other_branch.last_revision())
3211
other_revision_id = revision[-1].as_revision_id(other_branch)
3212
if (revision is not None and len(revision) == 2
3213
and revision[0] is not None):
3214
base_revision_id = revision[0].as_revision_id(base_branch)
3216
base_revision_id = None
3217
# Remember where we merge from
3218
if ((remember or tree.branch.get_submit_branch() is None) and
3219
user_location is not None):
3220
tree.branch.set_submit_branch(other_branch.base)
3221
_merge_tags_if_possible(other_branch, tree.branch)
3222
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3223
other_revision_id, base_revision_id, other_branch, base_branch)
3224
if other_path != '':
3225
allow_pending = False
3226
merger.interesting_files = [other_path]
3228
allow_pending = True
3229
return merger, allow_pending
3231
def _select_branch_location(self, tree, user_location, revision=None,
3233
"""Select a branch location, according to possible inputs.
3235
If provided, branches from ``revision`` are preferred. (Both
3236
``revision`` and ``index`` must be supplied.)
3238
Otherwise, the ``location`` parameter is used. If it is None, then the
3239
``submit`` or ``parent`` location is used, and a note is printed.
3241
:param tree: The working tree to select a branch for merging into
3242
:param location: The location entered by the user
3243
:param revision: The revision parameter to the command
3244
:param index: The index to use for the revision parameter. Negative
3245
indices are permitted.
3246
:return: (selected_location, user_location). The default location
3247
will be the user-entered location.
3249
if (revision is not None and index is not None
3250
and revision[index] is not None):
3251
branch = revision[index].get_branch()
3252
if branch is not None:
3253
return branch, branch
3254
if user_location is None:
3255
location = self._get_remembered(tree, 'Merging from')
3257
location = user_location
3258
return location, user_location
3260
def _get_remembered(self, tree, verb_string):
3261
"""Use tree.branch's parent if none was supplied.
3263
Report if the remembered location was used.
3265
stored_location = tree.branch.get_submit_branch()
3266
stored_location_type = "submit"
3267
if stored_location is None:
3268
stored_location = tree.branch.get_parent()
3269
stored_location_type = "parent"
3270
mutter("%s", stored_location)
3271
if stored_location is None:
3272
raise errors.BzrCommandError("No location specified or remembered")
3273
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3274
note(u"%s remembered %s location %s", verb_string,
3275
stored_location_type, display_url)
3276
return stored_location
3279
class cmd_remerge(Command):
3282
Use this if you want to try a different merge technique while resolving
3283
conflicts. Some merge techniques are better than others, and remerge
3284
lets you try different ones on different files.
3286
The options for remerge have the same meaning and defaults as the ones for
3287
merge. The difference is that remerge can (only) be run when there is a
3288
pending merge, and it lets you specify particular files.
3291
Re-do the merge of all conflicted files, and show the base text in
3292
conflict regions, in addition to the usual THIS and OTHER texts::
3294
bzr remerge --show-base
3296
Re-do the merge of "foobar", using the weave merge algorithm, with
3297
additional processing to reduce the size of conflict regions::
3299
bzr remerge --merge-type weave --reprocess foobar
3301
takes_args = ['file*']
3306
help="Show base revision text in conflicts."),
3309
def run(self, file_list=None, merge_type=None, show_base=False,
3311
if merge_type is None:
3312
merge_type = _mod_merge.Merge3Merger
3313
tree, file_list = tree_files(file_list)
3316
parents = tree.get_parent_ids()
3317
if len(parents) != 2:
3318
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3319
" merges. Not cherrypicking or"
3321
repository = tree.branch.repository
3322
interesting_ids = None
3324
conflicts = tree.conflicts()
3325
if file_list is not None:
3326
interesting_ids = set()
3327
for filename in file_list:
3328
file_id = tree.path2id(filename)
3330
raise errors.NotVersionedError(filename)
3331
interesting_ids.add(file_id)
3332
if tree.kind(file_id) != "directory":
3335
for name, ie in tree.inventory.iter_entries(file_id):
3336
interesting_ids.add(ie.file_id)
3337
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3339
# Remerge only supports resolving contents conflicts
3340
allowed_conflicts = ('text conflict', 'contents conflict')
3341
restore_files = [c.path for c in conflicts
3342
if c.typestring in allowed_conflicts]
3343
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3344
tree.set_conflicts(ConflictList(new_conflicts))
3345
if file_list is not None:
3346
restore_files = file_list
3347
for filename in restore_files:
3349
restore(tree.abspath(filename))
3350
except errors.NotConflicted:
3352
# Disable pending merges, because the file texts we are remerging
3353
# have not had those merges performed. If we use the wrong parents
3354
# list, we imply that the working tree text has seen and rejected
3355
# all the changes from the other tree, when in fact those changes
3356
# have not yet been seen.
3357
pb = ui.ui_factory.nested_progress_bar()
3358
tree.set_parent_ids(parents[:1])
3360
merger = _mod_merge.Merger.from_revision_ids(pb,
3362
merger.interesting_ids = interesting_ids
3363
merger.merge_type = merge_type
3364
merger.show_base = show_base
3365
merger.reprocess = reprocess
3366
conflicts = merger.do_merge()
3368
tree.set_parent_ids(parents)
3378
class cmd_revert(Command):
3379
"""Revert files to a previous revision.
3381
Giving a list of files will revert only those files. Otherwise, all files
3382
will be reverted. If the revision is not specified with '--revision', the
3383
last committed revision is used.
3385
To remove only some changes, without reverting to a prior version, use
3386
merge instead. For example, "merge . --revision -2..-3" will remove the
3387
changes introduced by -2, without affecting the changes introduced by -1.
3388
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3390
By default, any files that have been manually changed will be backed up
3391
first. (Files changed only by merge are not backed up.) Backup files have
3392
'.~#~' appended to their name, where # is a number.
3394
When you provide files, you can use their current pathname or the pathname
3395
from the target revision. So you can use revert to "undelete" a file by
3396
name. If you name a directory, all the contents of that directory will be
3399
Any files that have been newly added since that revision will be deleted,
3400
with a backup kept if appropriate. Directories containing unknown files
3401
will not be deleted.
3403
The working tree contains a list of pending merged revisions, which will
3404
be included as parents in the next commit. Normally, revert clears that
3405
list as well as reverting the files. If any files are specified, revert
3406
leaves the pending merge list alone and reverts only the files. Use "bzr
3407
revert ." in the tree root to revert all files but keep the merge record,
3408
and "bzr revert --forget-merges" to clear the pending merge list without
3409
reverting any files.
3412
_see_also = ['cat', 'export']
3415
Option('no-backup', "Do not save backups of reverted files."),
3416
Option('forget-merges',
3417
'Remove pending merge marker, without changing any files.'),
3419
takes_args = ['file*']
3421
def run(self, revision=None, no_backup=False, file_list=None,
3422
forget_merges=None):
3423
tree, file_list = tree_files(file_list)
3427
tree.set_parent_ids(tree.get_parent_ids()[:1])
3429
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3434
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3435
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3436
pb = ui.ui_factory.nested_progress_bar()
3438
tree.revert(file_list, rev_tree, not no_backup, pb,
3439
report_changes=True)
3444
class cmd_assert_fail(Command):
3445
"""Test reporting of assertion failures"""
3446
# intended just for use in testing
3451
raise AssertionError("always fails")
3454
class cmd_help(Command):
3455
"""Show help on a command or other topic.
3458
_see_also = ['topics']
3460
Option('long', 'Show help on all commands.'),
3462
takes_args = ['topic?']
3463
aliases = ['?', '--help', '-?', '-h']
3466
def run(self, topic=None, long=False):
3468
if topic is None and long:
3470
bzrlib.help.help(topic)
3473
class cmd_shell_complete(Command):
3474
"""Show appropriate completions for context.
3476
For a list of all available commands, say 'bzr shell-complete'.
3478
takes_args = ['context?']
3483
def run(self, context=None):
3484
import shellcomplete
3485
shellcomplete.shellcomplete(context)
3488
class cmd_missing(Command):
3489
"""Show unmerged/unpulled revisions between two branches.
3491
OTHER_BRANCH may be local or remote.
3494
_see_also = ['merge', 'pull']
3495
takes_args = ['other_branch?']
3497
Option('reverse', 'Reverse the order of revisions.'),
3499
'Display changes in the local branch only.'),
3500
Option('this' , 'Same as --mine-only.'),
3501
Option('theirs-only',
3502
'Display changes in the remote branch only.'),
3503
Option('other', 'Same as --theirs-only.'),
3507
Option('include-merges', 'Show merged revisions.'),
3509
encoding_type = 'replace'
3512
def run(self, other_branch=None, reverse=False, mine_only=False,
3514
log_format=None, long=False, short=False, line=False,
3515
show_ids=False, verbose=False, this=False, other=False,
3516
include_merges=False):
3517
from bzrlib.missing import find_unmerged, iter_log_revisions
3526
# TODO: We should probably check that we don't have mine-only and
3527
# theirs-only set, but it gets complicated because we also have
3528
# this and other which could be used.
3535
local_branch = Branch.open_containing(u".")[0]
3536
parent = local_branch.get_parent()
3537
if other_branch is None:
3538
other_branch = parent
3539
if other_branch is None:
3540
raise errors.BzrCommandError("No peer location known"
3542
display_url = urlutils.unescape_for_display(parent,
3544
message("Using saved parent location: "
3545
+ display_url + "\n")
3547
remote_branch = Branch.open(other_branch)
3548
if remote_branch.base == local_branch.base:
3549
remote_branch = local_branch
3550
local_branch.lock_read()
3552
remote_branch.lock_read()
3554
local_extra, remote_extra = find_unmerged(
3555
local_branch, remote_branch, restrict,
3556
backward=not reverse,
3557
include_merges=include_merges)
3559
if log_format is None:
3560
registry = log.log_formatter_registry
3561
log_format = registry.get_default(local_branch)
3562
lf = log_format(to_file=self.outf,
3564
show_timezone='original')
3567
if local_extra and not theirs_only:
3568
message("You have %d extra revision(s):\n" %
3570
for revision in iter_log_revisions(local_extra,
3571
local_branch.repository,
3573
lf.log_revision(revision)
3574
printed_local = True
3577
printed_local = False
3579
if remote_extra and not mine_only:
3580
if printed_local is True:
3582
message("You are missing %d revision(s):\n" %
3584
for revision in iter_log_revisions(remote_extra,
3585
remote_branch.repository,
3587
lf.log_revision(revision)
3590
if mine_only and not local_extra:
3591
# We checked local, and found nothing extra
3592
message('This branch is up to date.\n')
3593
elif theirs_only and not remote_extra:
3594
# We checked remote, and found nothing extra
3595
message('Other branch is up to date.\n')
3596
elif not (mine_only or theirs_only or local_extra or
3598
# We checked both branches, and neither one had extra
3600
message("Branches are up to date.\n")
3602
remote_branch.unlock()
3604
local_branch.unlock()
3605
if not status_code and parent is None and other_branch is not None:
3606
local_branch.lock_write()
3608
# handle race conditions - a parent might be set while we run.
3609
if local_branch.get_parent() is None:
3610
local_branch.set_parent(remote_branch.base)
3612
local_branch.unlock()
3616
class cmd_pack(Command):
3617
"""Compress the data within a repository."""
3619
_see_also = ['repositories']
3620
takes_args = ['branch_or_repo?']
3622
def run(self, branch_or_repo='.'):
3623
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3625
branch = dir.open_branch()
3626
repository = branch.repository
3627
except errors.NotBranchError:
3628
repository = dir.open_repository()
3632
class cmd_plugins(Command):
3633
"""List the installed plugins.
3635
This command displays the list of installed plugins including
3636
version of plugin and a short description of each.
3638
--verbose shows the path where each plugin is located.
3640
A plugin is an external component for Bazaar that extends the
3641
revision control system, by adding or replacing code in Bazaar.
3642
Plugins can do a variety of things, including overriding commands,
3643
adding new commands, providing additional network transports and
3644
customizing log output.
3646
See the Bazaar web site, http://bazaar-vcs.org, for further
3647
information on plugins including where to find them and how to
3648
install them. Instructions are also provided there on how to
3649
write new plugins using the Python programming language.
3651
takes_options = ['verbose']
3654
def run(self, verbose=False):
3655
import bzrlib.plugin
3656
from inspect import getdoc
3658
for name, plugin in bzrlib.plugin.plugins().items():
3659
version = plugin.__version__
3660
if version == 'unknown':
3662
name_ver = '%s %s' % (name, version)
3663
d = getdoc(plugin.module)
3665
doc = d.split('\n')[0]
3667
doc = '(no description)'
3668
result.append((name_ver, doc, plugin.path()))
3669
for name_ver, doc, path in sorted(result):
3677
class cmd_testament(Command):
3678
"""Show testament (signing-form) of a revision."""
3681
Option('long', help='Produce long-format testament.'),
3683
help='Produce a strict-format testament.')]
3684
takes_args = ['branch?']
3686
def run(self, branch=u'.', revision=None, long=False, strict=False):
3687
from bzrlib.testament import Testament, StrictTestament
3689
testament_class = StrictTestament
3691
testament_class = Testament
3693
b = Branch.open_containing(branch)[0]
3695
b = Branch.open(branch)
3698
if revision is None:
3699
rev_id = b.last_revision()
3701
rev_id = revision[0].as_revision_id(b)
3702
t = testament_class.from_revision(b.repository, rev_id)
3704
sys.stdout.writelines(t.as_text_lines())
3706
sys.stdout.write(t.as_short_text())
3711
class cmd_annotate(Command):
3712
"""Show the origin of each line in a file.
3714
This prints out the given file with an annotation on the left side
3715
indicating which revision, author and date introduced the change.
3717
If the origin is the same for a run of consecutive lines, it is
3718
shown only at the top, unless the --all option is given.
3720
# TODO: annotate directories; showing when each file was last changed
3721
# TODO: if the working copy is modified, show annotations on that
3722
# with new uncommitted lines marked
3723
aliases = ['ann', 'blame', 'praise']
3724
takes_args = ['filename']
3725
takes_options = [Option('all', help='Show annotations on all lines.'),
3726
Option('long', help='Show commit date in annotations.'),
3730
encoding_type = 'exact'
3733
def run(self, filename, all=False, long=False, revision=None,
3735
from bzrlib.annotate import annotate_file, annotate_file_tree
3736
wt, branch, relpath = \
3737
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3743
tree = _get_one_revision_tree('annotate', revision, branch=branch)
3745
file_id = wt.path2id(relpath)
3747
file_id = tree.path2id(relpath)
3749
raise errors.NotVersionedError(filename)
3750
file_version = tree.inventory[file_id].revision
3751
if wt is not None and revision is None:
3752
# If there is a tree and we're not annotating historical
3753
# versions, annotate the working tree's content.
3754
annotate_file_tree(wt, file_id, self.outf, long, all,
3757
annotate_file(branch, file_version, file_id, long, all, self.outf,
3766
class cmd_re_sign(Command):
3767
"""Create a digital signature for an existing revision."""
3768
# TODO be able to replace existing ones.
3770
hidden = True # is this right ?
3771
takes_args = ['revision_id*']
3772
takes_options = ['revision']
3774
def run(self, revision_id_list=None, revision=None):
3775
if revision_id_list is not None and revision is not None:
3776
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3777
if revision_id_list is None and revision is None:
3778
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3779
b = WorkingTree.open_containing(u'.')[0].branch
3782
return self._run(b, revision_id_list, revision)
3786
def _run(self, b, revision_id_list, revision):
3787
import bzrlib.gpg as gpg
3788
gpg_strategy = gpg.GPGStrategy(b.get_config())
3789
if revision_id_list is not None:
3790
b.repository.start_write_group()
3792
for revision_id in revision_id_list:
3793
b.repository.sign_revision(revision_id, gpg_strategy)
3795
b.repository.abort_write_group()
3798
b.repository.commit_write_group()
3799
elif revision is not None:
3800
if len(revision) == 1:
3801
revno, rev_id = revision[0].in_history(b)
3802
b.repository.start_write_group()
3804
b.repository.sign_revision(rev_id, gpg_strategy)
3806
b.repository.abort_write_group()
3809
b.repository.commit_write_group()
3810
elif len(revision) == 2:
3811
# are they both on rh- if so we can walk between them
3812
# might be nice to have a range helper for arbitrary
3813
# revision paths. hmm.
3814
from_revno, from_revid = revision[0].in_history(b)
3815
to_revno, to_revid = revision[1].in_history(b)
3816
if to_revid is None:
3817
to_revno = b.revno()
3818
if from_revno is None or to_revno is None:
3819
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3820
b.repository.start_write_group()
3822
for revno in range(from_revno, to_revno + 1):
3823
b.repository.sign_revision(b.get_rev_id(revno),
3826
b.repository.abort_write_group()
3829
b.repository.commit_write_group()
3831
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3834
class cmd_bind(Command):
3835
"""Convert the current branch into a checkout of the supplied branch.
3837
Once converted into a checkout, commits must succeed on the master branch
3838
before they will be applied to the local branch.
3840
Bound branches use the nickname of its master branch unless it is set
3841
locally, in which case binding will update the the local nickname to be
3845
_see_also = ['checkouts', 'unbind']
3846
takes_args = ['location?']
3849
def run(self, location=None):
3850
b, relpath = Branch.open_containing(u'.')
3851
if location is None:
3853
location = b.get_old_bound_location()
3854
except errors.UpgradeRequired:
3855
raise errors.BzrCommandError('No location supplied. '
3856
'This format does not remember old locations.')
3858
if location is None:
3859
raise errors.BzrCommandError('No location supplied and no '
3860
'previous location known')
3861
b_other = Branch.open(location)
3864
except errors.DivergedBranches:
3865
raise errors.BzrCommandError('These branches have diverged.'
3866
' Try merging, and then bind again.')
3867
if b.get_config().has_explicit_nickname():
3868
b.nick = b_other.nick
3871
class cmd_unbind(Command):
3872
"""Convert the current checkout into a regular branch.
3874
After unbinding, the local branch is considered independent and subsequent
3875
commits will be local only.
3878
_see_also = ['checkouts', 'bind']
3883
b, relpath = Branch.open_containing(u'.')
3885
raise errors.BzrCommandError('Local branch is not bound')
3888
class cmd_uncommit(Command):
3889
"""Remove the last committed revision.
3891
--verbose will print out what is being removed.
3892
--dry-run will go through all the motions, but not actually
3895
If --revision is specified, uncommit revisions to leave the branch at the
3896
specified revision. For example, "bzr uncommit -r 15" will leave the
3897
branch at revision 15.
3899
Uncommit leaves the working tree ready for a new commit. The only change
3900
it may make is to restore any pending merges that were present before
3904
# TODO: jam 20060108 Add an option to allow uncommit to remove
3905
# unreferenced information in 'branch-as-repository' branches.
3906
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3907
# information in shared branches as well.
3908
_see_also = ['commit']
3909
takes_options = ['verbose', 'revision',
3910
Option('dry-run', help='Don\'t actually make changes.'),
3911
Option('force', help='Say yes to all questions.'),
3913
help="Only remove the commits from the local branch"
3914
" when in a checkout."
3917
takes_args = ['location?']
3919
encoding_type = 'replace'
3921
def run(self, location=None,
3922
dry_run=False, verbose=False,
3923
revision=None, force=False, local=False):
3924
if location is None:
3926
control, relpath = bzrdir.BzrDir.open_containing(location)
3928
tree = control.open_workingtree()
3930
except (errors.NoWorkingTree, errors.NotLocalUrl):
3932
b = control.open_branch()
3934
if tree is not None:
3939
return self._run(b, tree, dry_run, verbose, revision, force,
3942
if tree is not None:
3947
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3948
from bzrlib.log import log_formatter, show_log
3949
from bzrlib.uncommit import uncommit
3951
last_revno, last_rev_id = b.last_revision_info()
3954
if revision is None:
3956
rev_id = last_rev_id
3958
# 'bzr uncommit -r 10' actually means uncommit
3959
# so that the final tree is at revno 10.
3960
# but bzrlib.uncommit.uncommit() actually uncommits
3961
# the revisions that are supplied.
3962
# So we need to offset it by one
3963
revno = revision[0].in_history(b).revno + 1
3964
if revno <= last_revno:
3965
rev_id = b.get_rev_id(revno)
3967
if rev_id is None or _mod_revision.is_null(rev_id):
3968
self.outf.write('No revisions to uncommit.\n')
3971
lf = log_formatter('short',
3973
show_timezone='original')
3978
direction='forward',
3979
start_revision=revno,
3980
end_revision=last_revno)
3983
print 'Dry-run, pretending to remove the above revisions.'
3985
val = raw_input('Press <enter> to continue')
3987
print 'The above revision(s) will be removed.'
3989
val = raw_input('Are you sure [y/N]? ')
3990
if val.lower() not in ('y', 'yes'):
3994
mutter('Uncommitting from {%s} to {%s}',
3995
last_rev_id, rev_id)
3996
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3997
revno=revno, local=local)
3998
note('You can restore the old tip by running:\n'
3999
' bzr pull . -r revid:%s', last_rev_id)
4002
class cmd_break_lock(Command):
4003
"""Break a dead lock on a repository, branch or working directory.
4005
CAUTION: Locks should only be broken when you are sure that the process
4006
holding the lock has been stopped.
4008
You can get information on what locks are open via the 'bzr info' command.
4013
takes_args = ['location?']
4015
def run(self, location=None, show=False):
4016
if location is None:
4018
control, relpath = bzrdir.BzrDir.open_containing(location)
4020
control.break_lock()
4021
except NotImplementedError:
4025
class cmd_wait_until_signalled(Command):
4026
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4028
This just prints a line to signal when it is ready, then blocks on stdin.
4034
sys.stdout.write("running\n")
4036
sys.stdin.readline()
4039
class cmd_serve(Command):
4040
"""Run the bzr server."""
4042
aliases = ['server']
4046
help='Serve on stdin/out for use from inetd or sshd.'),
4048
help='Listen for connections on nominated port of the form '
4049
'[hostname:]portnumber. Passing 0 as the port number will '
4050
'result in a dynamically allocated port. The default port is '
4054
help='Serve contents of this directory.',
4056
Option('allow-writes',
4057
help='By default the server is a readonly server. Supplying '
4058
'--allow-writes enables write access to the contents of '
4059
'the served directory and below.'
4063
def run(self, port=None, inet=False, directory=None, allow_writes=False):
4064
from bzrlib import lockdir
4065
from bzrlib.smart import medium, server
4066
from bzrlib.transport import get_transport
4067
from bzrlib.transport.chroot import ChrootServer
4068
if directory is None:
4069
directory = os.getcwd()
4070
url = urlutils.local_path_to_url(directory)
4071
if not allow_writes:
4072
url = 'readonly+' + url
4073
chroot_server = ChrootServer(get_transport(url))
4074
chroot_server.setUp()
4075
t = get_transport(chroot_server.get_url())
4077
smart_server = medium.SmartServerPipeStreamMedium(
4078
sys.stdin, sys.stdout, t)
4080
host = medium.BZR_DEFAULT_INTERFACE
4082
port = medium.BZR_DEFAULT_PORT
4085
host, port = port.split(':')
4087
smart_server = server.SmartTCPServer(t, host=host, port=port)
4088
print 'listening on port: ', smart_server.port
4090
# for the duration of this server, no UI output is permitted.
4091
# note that this may cause problems with blackbox tests. This should
4092
# be changed with care though, as we dont want to use bandwidth sending
4093
# progress over stderr to smart server clients!
4094
old_factory = ui.ui_factory
4095
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4097
ui.ui_factory = ui.SilentUIFactory()
4098
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4099
smart_server.serve()
4101
ui.ui_factory = old_factory
4102
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4105
class cmd_join(Command):
4106
"""Combine a subtree into its containing tree.
4108
This command is for experimental use only. It requires the target tree
4109
to be in dirstate-with-subtree format, which cannot be converted into
4112
The TREE argument should be an independent tree, inside another tree, but
4113
not part of it. (Such trees can be produced by "bzr split", but also by
4114
running "bzr branch" with the target inside a tree.)
4116
The result is a combined tree, with the subtree no longer an independant
4117
part. This is marked as a merge of the subtree into the containing tree,
4118
and all history is preserved.
4120
If --reference is specified, the subtree retains its independence. It can
4121
be branched by itself, and can be part of multiple projects at the same
4122
time. But operations performed in the containing tree, such as commit
4123
and merge, will recurse into the subtree.
4126
_see_also = ['split']
4127
takes_args = ['tree']
4129
Option('reference', help='Join by reference.'),
4133
def run(self, tree, reference=False):
4134
sub_tree = WorkingTree.open(tree)
4135
parent_dir = osutils.dirname(sub_tree.basedir)
4136
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4137
repo = containing_tree.branch.repository
4138
if not repo.supports_rich_root():
4139
raise errors.BzrCommandError(
4140
"Can't join trees because %s doesn't support rich root data.\n"
4141
"You can use bzr upgrade on the repository."
4145
containing_tree.add_reference(sub_tree)
4146
except errors.BadReferenceTarget, e:
4147
# XXX: Would be better to just raise a nicely printable
4148
# exception from the real origin. Also below. mbp 20070306
4149
raise errors.BzrCommandError("Cannot join %s. %s" %
4153
containing_tree.subsume(sub_tree)
4154
except errors.BadSubsumeSource, e:
4155
raise errors.BzrCommandError("Cannot join %s. %s" %
4159
class cmd_split(Command):
4160
"""Split a subdirectory of a tree into a separate tree.
4162
This command will produce a target tree in a format that supports
4163
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4164
converted into earlier formats like 'dirstate-tags'.
4166
The TREE argument should be a subdirectory of a working tree. That
4167
subdirectory will be converted into an independent tree, with its own
4168
branch. Commits in the top-level tree will not apply to the new subtree.
4171
# join is not un-hidden yet
4172
#_see_also = ['join']
4173
takes_args = ['tree']
4175
def run(self, tree):
4176
containing_tree, subdir = WorkingTree.open_containing(tree)
4177
sub_id = containing_tree.path2id(subdir)
4179
raise errors.NotVersionedError(subdir)
4181
containing_tree.extract(sub_id)
4182
except errors.RootNotRich:
4183
raise errors.UpgradeRequired(containing_tree.branch.base)
4186
class cmd_merge_directive(Command):
4187
"""Generate a merge directive for auto-merge tools.
4189
A directive requests a merge to be performed, and also provides all the
4190
information necessary to do so. This means it must either include a
4191
revision bundle, or the location of a branch containing the desired
4194
A submit branch (the location to merge into) must be supplied the first
4195
time the command is issued. After it has been supplied once, it will
4196
be remembered as the default.
4198
A public branch is optional if a revision bundle is supplied, but required
4199
if --diff or --plain is specified. It will be remembered as the default
4200
after the first use.
4203
takes_args = ['submit_branch?', 'public_branch?']
4207
_see_also = ['send']
4210
RegistryOption.from_kwargs('patch-type',
4211
'The type of patch to include in the directive.',
4213
value_switches=True,
4215
bundle='Bazaar revision bundle (default).',
4216
diff='Normal unified diff.',
4217
plain='No patch, just directive.'),
4218
Option('sign', help='GPG-sign the directive.'), 'revision',
4219
Option('mail-to', type=str,
4220
help='Instead of printing the directive, email to this address.'),
4221
Option('message', type=str, short_name='m',
4222
help='Message to use when committing this merge.')
4225
encoding_type = 'exact'
4227
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4228
sign=False, revision=None, mail_to=None, message=None):
4229
from bzrlib.revision import ensure_null, NULL_REVISION
4230
include_patch, include_bundle = {
4231
'plain': (False, False),
4232
'diff': (True, False),
4233
'bundle': (True, True),
4235
branch = Branch.open('.')
4236
stored_submit_branch = branch.get_submit_branch()
4237
if submit_branch is None:
4238
submit_branch = stored_submit_branch
4240
if stored_submit_branch is None:
4241
branch.set_submit_branch(submit_branch)
4242
if submit_branch is None:
4243
submit_branch = branch.get_parent()
4244
if submit_branch is None:
4245
raise errors.BzrCommandError('No submit branch specified or known')
4247
stored_public_branch = branch.get_public_branch()
4248
if public_branch is None:
4249
public_branch = stored_public_branch
4250
elif stored_public_branch is None:
4251
branch.set_public_branch(public_branch)
4252
if not include_bundle and public_branch is None:
4253
raise errors.BzrCommandError('No public branch specified or'
4255
base_revision_id = None
4256
if revision is not None:
4257
if len(revision) > 2:
4258
raise errors.BzrCommandError('bzr merge-directive takes '
4259
'at most two one revision identifiers')
4260
revision_id = revision[-1].as_revision_id(branch)
4261
if len(revision) == 2:
4262
base_revision_id = revision[0].as_revision_id(branch)
4264
revision_id = branch.last_revision()
4265
revision_id = ensure_null(revision_id)
4266
if revision_id == NULL_REVISION:
4267
raise errors.BzrCommandError('No revisions to bundle.')
4268
directive = merge_directive.MergeDirective2.from_objects(
4269
branch.repository, revision_id, time.time(),
4270
osutils.local_time_offset(), submit_branch,
4271
public_branch=public_branch, include_patch=include_patch,
4272
include_bundle=include_bundle, message=message,
4273
base_revision_id=base_revision_id)
4276
self.outf.write(directive.to_signed(branch))
4278
self.outf.writelines(directive.to_lines())
4280
message = directive.to_email(mail_to, branch, sign)
4281
s = SMTPConnection(branch.get_config())
4282
s.send_email(message)
4285
class cmd_send(Command):
4286
"""Mail or create a merge-directive for submitting changes.
4288
A merge directive provides many things needed for requesting merges:
4290
* A machine-readable description of the merge to perform
4292
* An optional patch that is a preview of the changes requested
4294
* An optional bundle of revision data, so that the changes can be applied
4295
directly from the merge directive, without retrieving data from a
4298
If --no-bundle is specified, then public_branch is needed (and must be
4299
up-to-date), so that the receiver can perform the merge using the
4300
public_branch. The public_branch is always included if known, so that
4301
people can check it later.
4303
The submit branch defaults to the parent, but can be overridden. Both
4304
submit branch and public branch will be remembered if supplied.
4306
If a public_branch is known for the submit_branch, that public submit
4307
branch is used in the merge instructions. This means that a local mirror
4308
can be used as your actual submit branch, once you have set public_branch
4311
Mail is sent using your preferred mail program. This should be transparent
4312
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4313
If the preferred client can't be found (or used), your editor will be used.
4315
To use a specific mail program, set the mail_client configuration option.
4316
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4317
specific clients are "claws", "evolution", "kmail", "mutt", and
4318
"thunderbird"; generic options are "default", "editor", "emacsclient",
4319
"mapi", and "xdg-email". Plugins may also add supported clients.
4321
If mail is being sent, a to address is required. This can be supplied
4322
either on the commandline, by setting the submit_to configuration
4323
option in the branch itself or the child_submit_to configuration option
4324
in the submit branch.
4326
Two formats are currently supported: "4" uses revision bundle format 4 and
4327
merge directive format 2. It is significantly faster and smaller than
4328
older formats. It is compatible with Bazaar 0.19 and later. It is the
4329
default. "0.9" uses revision bundle format 0.9 and merge directive
4330
format 1. It is compatible with Bazaar 0.12 - 0.18.
4332
Merge directives are applied using the merge command or the pull command.
4335
encoding_type = 'exact'
4337
_see_also = ['merge', 'pull']
4339
takes_args = ['submit_branch?', 'public_branch?']
4343
help='Do not include a bundle in the merge directive.'),
4344
Option('no-patch', help='Do not include a preview patch in the merge'
4347
help='Remember submit and public branch.'),
4349
help='Branch to generate the submission from, '
4350
'rather than the one containing the working directory.',
4353
Option('output', short_name='o',
4354
help='Write merge directive to this file; '
4355
'use - for stdout.',
4357
Option('mail-to', help='Mail the request to this address.',
4361
RegistryOption.from_kwargs('format',
4362
'Use the specified output format.',
4363
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4364
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4367
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4368
no_patch=False, revision=None, remember=False, output=None,
4369
format='4', mail_to=None, message=None, **kwargs):
4370
return self._run(submit_branch, revision, public_branch, remember,
4371
format, no_bundle, no_patch, output,
4372
kwargs.get('from', '.'), mail_to, message)
4374
def _run(self, submit_branch, revision, public_branch, remember, format,
4375
no_bundle, no_patch, output, from_, mail_to, message):
4376
from bzrlib.revision import NULL_REVISION
4377
branch = Branch.open_containing(from_)[0]
4379
outfile = cStringIO.StringIO()
4383
outfile = open(output, 'wb')
4384
# we may need to write data into branch's repository to calculate
4389
config = branch.get_config()
4391
mail_to = config.get_user_option('submit_to')
4392
mail_client = config.get_mail_client()
4393
if remember and submit_branch is None:
4394
raise errors.BzrCommandError(
4395
'--remember requires a branch to be specified.')
4396
stored_submit_branch = branch.get_submit_branch()
4397
remembered_submit_branch = None
4398
if submit_branch is None:
4399
submit_branch = stored_submit_branch
4400
remembered_submit_branch = "submit"
4402
if stored_submit_branch is None or remember:
4403
branch.set_submit_branch(submit_branch)
4404
if submit_branch is None:
4405
submit_branch = branch.get_parent()
4406
remembered_submit_branch = "parent"
4407
if submit_branch is None:
4408
raise errors.BzrCommandError('No submit branch known or'
4410
if remembered_submit_branch is not None:
4411
note('Using saved %s location "%s" to determine what '
4412
'changes to submit.', remembered_submit_branch,
4416
submit_config = Branch.open(submit_branch).get_config()
4417
mail_to = submit_config.get_user_option("child_submit_to")
4419
stored_public_branch = branch.get_public_branch()
4420
if public_branch is None:
4421
public_branch = stored_public_branch
4422
elif stored_public_branch is None or remember:
4423
branch.set_public_branch(public_branch)
4424
if no_bundle and public_branch is None:
4425
raise errors.BzrCommandError('No public branch specified or'
4427
base_revision_id = None
4429
if revision is not None:
4430
if len(revision) > 2:
4431
raise errors.BzrCommandError('bzr send takes '
4432
'at most two one revision identifiers')
4433
revision_id = revision[-1].as_revision_id(branch)
4434
if len(revision) == 2:
4435
base_revision_id = revision[0].as_revision_id(branch)
4436
if revision_id is None:
4437
revision_id = branch.last_revision()
4438
if revision_id == NULL_REVISION:
4439
raise errors.BzrCommandError('No revisions to submit.')
4441
directive = merge_directive.MergeDirective2.from_objects(
4442
branch.repository, revision_id, time.time(),
4443
osutils.local_time_offset(), submit_branch,
4444
public_branch=public_branch, include_patch=not no_patch,
4445
include_bundle=not no_bundle, message=message,
4446
base_revision_id=base_revision_id)
4447
elif format == '0.9':
4450
patch_type = 'bundle'
4452
raise errors.BzrCommandError('Format 0.9 does not'
4453
' permit bundle with no patch')
4459
directive = merge_directive.MergeDirective.from_objects(
4460
branch.repository, revision_id, time.time(),
4461
osutils.local_time_offset(), submit_branch,
4462
public_branch=public_branch, patch_type=patch_type,
4465
outfile.writelines(directive.to_lines())
4467
subject = '[MERGE] '
4468
if message is not None:
4471
revision = branch.repository.get_revision(revision_id)
4472
subject += revision.get_summary()
4473
basename = directive.get_disk_name(branch)
4474
mail_client.compose_merge_request(mail_to, subject,
4475
outfile.getvalue(), basename)
4482
class cmd_bundle_revisions(cmd_send):
4484
"""Create a merge-directive for submitting changes.
4486
A merge directive provides many things needed for requesting merges:
4488
* A machine-readable description of the merge to perform
4490
* An optional patch that is a preview of the changes requested
4492
* An optional bundle of revision data, so that the changes can be applied
4493
directly from the merge directive, without retrieving data from a
4496
If --no-bundle is specified, then public_branch is needed (and must be
4497
up-to-date), so that the receiver can perform the merge using the
4498
public_branch. The public_branch is always included if known, so that
4499
people can check it later.
4501
The submit branch defaults to the parent, but can be overridden. Both
4502
submit branch and public branch will be remembered if supplied.
4504
If a public_branch is known for the submit_branch, that public submit
4505
branch is used in the merge instructions. This means that a local mirror
4506
can be used as your actual submit branch, once you have set public_branch
4509
Two formats are currently supported: "4" uses revision bundle format 4 and
4510
merge directive format 2. It is significantly faster and smaller than
4511
older formats. It is compatible with Bazaar 0.19 and later. It is the
4512
default. "0.9" uses revision bundle format 0.9 and merge directive
4513
format 1. It is compatible with Bazaar 0.12 - 0.18.
4518
help='Do not include a bundle in the merge directive.'),
4519
Option('no-patch', help='Do not include a preview patch in the merge'
4522
help='Remember submit and public branch.'),
4524
help='Branch to generate the submission from, '
4525
'rather than the one containing the working directory.',
4528
Option('output', short_name='o', help='Write directive to this file.',
4531
RegistryOption.from_kwargs('format',
4532
'Use the specified output format.',
4533
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4534
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4536
aliases = ['bundle']
4538
_see_also = ['send', 'merge']
4542
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4543
no_patch=False, revision=None, remember=False, output=None,
4544
format='4', **kwargs):
4547
return self._run(submit_branch, revision, public_branch, remember,
4548
format, no_bundle, no_patch, output,
4549
kwargs.get('from', '.'), None, None)
4552
class cmd_tag(Command):
4553
"""Create, remove or modify a tag naming a revision.
4555
Tags give human-meaningful names to revisions. Commands that take a -r
4556
(--revision) option can be given -rtag:X, where X is any previously
4559
Tags are stored in the branch. Tags are copied from one branch to another
4560
along when you branch, push, pull or merge.
4562
It is an error to give a tag name that already exists unless you pass
4563
--force, in which case the tag is moved to point to the new revision.
4565
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4566
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4569
_see_also = ['commit', 'tags']
4570
takes_args = ['tag_name']
4573
help='Delete this tag rather than placing it.',
4576
help='Branch in which to place the tag.',
4581
help='Replace existing tags.',
4586
def run(self, tag_name,
4592
branch, relpath = Branch.open_containing(directory)
4596
branch.tags.delete_tag(tag_name)
4597
self.outf.write('Deleted tag %s.\n' % tag_name)
4600
if len(revision) != 1:
4601
raise errors.BzrCommandError(
4602
"Tags can only be placed on a single revision, "
4604
revision_id = revision[0].as_revision_id(branch)
4606
revision_id = branch.last_revision()
4607
if (not force) and branch.tags.has_tag(tag_name):
4608
raise errors.TagAlreadyExists(tag_name)
4609
branch.tags.set_tag(tag_name, revision_id)
4610
self.outf.write('Created tag %s.\n' % tag_name)
4615
class cmd_tags(Command):
4618
This command shows a table of tag names and the revisions they reference.
4624
help='Branch whose tags should be displayed.',
4628
RegistryOption.from_kwargs('sort',
4629
'Sort tags by different criteria.', title='Sorting',
4630
alpha='Sort tags lexicographically (default).',
4631
time='Sort tags chronologically.',
4644
branch, relpath = Branch.open_containing(directory)
4646
tags = branch.tags.get_tag_dict().items()
4653
graph = branch.repository.get_graph()
4654
rev1, rev2 = _get_revision_range(revision, branch, self.name())
4655
revid1, revid2 = rev1.rev_id, rev2.rev_id
4656
# only show revisions between revid1 and revid2 (inclusive)
4657
tags = [(tag, revid) for tag, revid in tags if
4659
graph.is_ancestor(revid, revid2)) and
4661
graph.is_ancestor(revid1, revid))]
4666
elif sort == 'time':
4668
for tag, revid in tags:
4670
revobj = branch.repository.get_revision(revid)
4671
except errors.NoSuchRevision:
4672
timestamp = sys.maxint # place them at the end
4674
timestamp = revobj.timestamp
4675
timestamps[revid] = timestamp
4676
tags.sort(key=lambda x: timestamps[x[1]])
4678
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4679
revno_map = branch.get_revision_id_to_revno_map()
4680
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4681
for tag, revid in tags ]
4682
for tag, revspec in tags:
4683
self.outf.write('%-20s %s\n' % (tag, revspec))
4686
class cmd_reconfigure(Command):
4687
"""Reconfigure the type of a bzr directory.
4689
A target configuration must be specified.
4691
For checkouts, the bind-to location will be auto-detected if not specified.
4692
The order of preference is
4693
1. For a lightweight checkout, the current bound location.
4694
2. For branches that used to be checkouts, the previously-bound location.
4695
3. The push location.
4696
4. The parent location.
4697
If none of these is available, --bind-to must be specified.
4700
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4701
takes_args = ['location?']
4702
takes_options = [RegistryOption.from_kwargs('target_type',
4703
title='Target type',
4704
help='The type to reconfigure the directory to.',
4705
value_switches=True, enum_switch=False,
4706
branch='Reconfigure to be an unbound branch '
4707
'with no working tree.',
4708
tree='Reconfigure to be an unbound branch '
4709
'with a working tree.',
4710
checkout='Reconfigure to be a bound branch '
4711
'with a working tree.',
4712
lightweight_checkout='Reconfigure to be a lightweight'
4713
' checkout (with no local history).',
4714
standalone='Reconfigure to be a standalone branch '
4715
'(i.e. stop using shared repository).',
4716
use_shared='Reconfigure to use a shared repository.'),
4717
Option('bind-to', help='Branch to bind checkout to.',
4720
help='Perform reconfiguration even if local changes'
4724
def run(self, location=None, target_type=None, bind_to=None, force=False):
4725
directory = bzrdir.BzrDir.open(location)
4726
if target_type is None:
4727
raise errors.BzrCommandError('No target configuration specified')
4728
elif target_type == 'branch':
4729
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4730
elif target_type == 'tree':
4731
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4732
elif target_type == 'checkout':
4733
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4735
elif target_type == 'lightweight-checkout':
4736
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4738
elif target_type == 'use-shared':
4739
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4740
elif target_type == 'standalone':
4741
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4742
reconfiguration.apply(force)
4745
class cmd_switch(Command):
4746
"""Set the branch of a checkout and update.
4748
For lightweight checkouts, this changes the branch being referenced.
4749
For heavyweight checkouts, this checks that there are no local commits
4750
versus the current bound branch, then it makes the local branch a mirror
4751
of the new location and binds to it.
4753
In both cases, the working tree is updated and uncommitted changes
4754
are merged. The user can commit or revert these as they desire.
4756
Pending merges need to be committed or reverted before using switch.
4758
The path to the branch to switch to can be specified relative to the parent
4759
directory of the current branch. For example, if you are currently in a
4760
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4763
Bound branches use the nickname of its master branch unless it is set
4764
locally, in which case switching will update the the local nickname to be
4768
takes_args = ['to_location']
4769
takes_options = [Option('force',
4770
help='Switch even if local commits will be lost.')
4773
def run(self, to_location, force=False):
4774
from bzrlib import switch
4776
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4777
branch = control_dir.open_branch()
4779
to_branch = Branch.open(to_location)
4780
except errors.NotBranchError:
4781
this_branch = control_dir.open_branch()
4782
# This may be a heavy checkout, where we want the master branch
4783
this_url = this_branch.get_bound_location()
4784
# If not, use a local sibling
4785
if this_url is None:
4786
this_url = this_branch.base
4787
to_branch = Branch.open(
4788
urlutils.join(this_url, '..', to_location))
4789
switch.switch(control_dir, to_branch, force)
4790
if branch.get_config().has_explicit_nickname():
4791
branch = control_dir.open_branch() #get the new branch!
4792
branch.nick = to_branch.nick
4793
note('Switched to branch: %s',
4794
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4797
class cmd_hooks(Command):
4798
"""Show a branch's currently registered hooks.
4802
takes_args = ['path?']
4804
def run(self, path=None):
4807
branch_hooks = Branch.open(path).hooks
4808
for hook_type in branch_hooks:
4809
hooks = branch_hooks[hook_type]
4810
self.outf.write("%s:\n" % (hook_type,))
4813
self.outf.write(" %s\n" %
4814
(branch_hooks.get_hook_name(hook),))
4816
self.outf.write(" <no hooks installed>\n")
4819
class cmd_shelve(Command):
4820
"""Temporarily set aside some changes from the current tree.
4822
Shelve allows you to temporarily put changes you've made "on the shelf",
4823
ie. out of the way, until a later time when you can bring them back from
4824
the shelf with the 'unshelve' command.
4826
If shelve --list is specified, previously-shelved changes are listed.
4828
Shelve is intended to help separate several sets of changes that have
4829
been inappropriately mingled. If you just want to get rid of all changes
4830
and you don't need to restore them later, use revert. If you want to
4831
shelve all text changes at once, use shelve --all.
4833
If filenames are specified, only the changes to those files will be
4834
shelved. Other files will be left untouched.
4836
If a revision is specified, changes since that revision will be shelved.
4838
You can put multiple items on the shelf, and by default, 'unshelve' will
4839
restore the most recently shelved changes.
4842
takes_args = ['file*']
4846
Option('all', help='Shelve all changes.'),
4848
RegistryOption('writer', 'Method to use for writing diffs.',
4849
bzrlib.option.diff_writer_registry,
4850
value_switches=True, enum_switch=False),
4852
Option('list', help='List shelved changes.'),
4854
_see_also = ['unshelve']
4856
def run(self, revision=None, all=False, file_list=None, message=None,
4857
writer=None, list=False):
4859
return self.run_for_list()
4860
from bzrlib.shelf_ui import Shelver
4862
writer = bzrlib.option.diff_writer_registry.get()
4864
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
4866
except errors.UserAbort:
4869
def run_for_list(self):
4870
tree = WorkingTree.open_containing('.')[0]
4873
manager = tree.get_shelf_manager()
4874
shelves = manager.active_shelves()
4875
if len(shelves) == 0:
4876
note('No shelved changes.')
4878
for shelf_id in reversed(shelves):
4879
message = manager.get_metadata(shelf_id).get('message')
4881
message = '<no message>'
4882
self.outf.write('%3d: %s\n' % (shelf_id, message))
4888
class cmd_unshelve(Command):
4889
"""Restore shelved changes.
4891
By default, the most recently shelved changes are restored. However if you
4892
specify a patch by name those changes will be restored instead. This
4893
works best when the changes don't depend on each other.
4896
takes_args = ['shelf_id?']
4898
RegistryOption.from_kwargs(
4899
'action', help="The action to perform.",
4900
enum_switch=False, value_switches=True,
4901
apply="Apply changes and remove from the shelf.",
4902
dry_run="Show changes, but do not apply or remove them.",
4903
delete_only="Delete changes without applying them."
4906
_see_also = ['shelve']
4908
def run(self, shelf_id=None, action='apply'):
4909
from bzrlib.shelf_ui import Unshelver
4910
Unshelver.from_args(shelf_id, action).run()
4913
def _create_prefix(cur_transport):
4914
needed = [cur_transport]
4915
# Recurse upwards until we can create a directory successfully
4917
new_transport = cur_transport.clone('..')
4918
if new_transport.base == cur_transport.base:
4919
raise errors.BzrCommandError(
4920
"Failed to create path prefix for %s."
4921
% cur_transport.base)
4923
new_transport.mkdir('.')
4924
except errors.NoSuchFile:
4925
needed.append(new_transport)
4926
cur_transport = new_transport
4929
# Now we only need to create child directories
4931
cur_transport = needed.pop()
4932
cur_transport.ensure_base()
4935
# these get imported and then picked up by the scan for cmd_*
4936
# TODO: Some more consistent way to split command definitions across files;
4937
# we do need to load at least some information about them to know of
4938
# aliases. ideally we would avoid loading the implementation until the
4939
# details were needed.
4940
from bzrlib.cmd_version_info import cmd_version_info
4941
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4942
from bzrlib.bundle.commands import (
4945
from bzrlib.sign_my_commits import cmd_sign_my_commits
4946
from bzrlib.weave_commands import cmd_versionedfile_list, \
4947
cmd_weave_plan_merge, cmd_weave_merge_text