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 (
65
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
68
def tree_files(file_list, default_branch=u'.'):
70
return internal_tree_files(file_list, default_branch)
71
except errors.FileInWrongBranch, e:
72
raise errors.BzrCommandError("%s is not in the same branch as %s" %
73
(e.path, file_list[0]))
76
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
81
rev_tree = tree.basis_tree()
83
rev_tree = branch.basis_tree()
85
if len(revisions) != 1:
86
raise errors.BzrCommandError(
87
'bzr %s --revision takes exactly one revision identifier' % (
89
rev_tree = revisions[0].as_tree(branch)
93
# XXX: Bad function name; should possibly also be a class method of
94
# WorkingTree rather than a function.
95
def internal_tree_files(file_list, default_branch=u'.'):
96
"""Convert command-line paths to a WorkingTree and relative paths.
98
This is typically used for command-line processors that take one or
99
more filenames, and infer the workingtree that contains them.
101
The filenames given are not required to exist.
103
:param file_list: Filenames to convert.
105
:param default_branch: Fallback tree path to use if file_list is empty or
108
:return: workingtree, [relative_paths]
110
if file_list is None or len(file_list) == 0:
111
return WorkingTree.open_containing(default_branch)[0], file_list
112
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
113
return tree, safe_relpath_files(tree, file_list)
116
def safe_relpath_files(tree, file_list):
117
"""Convert file_list into a list of relpaths in tree.
119
:param tree: A tree to operate on.
120
:param file_list: A list of user provided paths or None.
121
:return: A list of relative paths.
122
:raises errors.PathNotChild: When a provided path is in a different tree
125
if file_list is None:
128
for filename in file_list:
130
new_list.append(tree.relpath(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)
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
from_id = tree.path2id(rel_names[0])
685
if (not osutils.lexists(names_list[0]) and
686
from_id and inv.get_file_kind(from_id) == "directory"):
687
into_existing = False
690
# move into existing directory
691
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
692
self.outf.write("%s => %s\n" % pair)
694
if len(names_list) != 2:
695
raise errors.BzrCommandError('to mv multiple files the'
696
' destination must be a versioned'
698
tree.rename_one(rel_names[0], rel_names[1], after=after)
699
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
702
class cmd_pull(Command):
703
"""Turn this branch into a mirror of another branch.
705
This command only works on branches that have not diverged. Branches are
706
considered diverged if the destination branch's most recent commit is one
707
that has not been merged (directly or indirectly) into the parent.
709
If branches have diverged, you can use 'bzr merge' to integrate the changes
710
from one into the other. Once one branch has merged, the other should
711
be able to pull it again.
713
If you want to forget your local changes and just update your branch to
714
match the remote one, use pull --overwrite.
716
If there is no default location set, the first pull will set it. After
717
that, you can omit the location to use the default. To change the
718
default, use --remember. The value will only be saved if the remote
719
location can be accessed.
721
Note: The location can be specified either in the form of a branch,
722
or in the form of a path to a file containing a merge directive generated
726
_see_also = ['push', 'update', 'status-flags']
727
takes_options = ['remember', 'overwrite', 'revision',
728
custom_help('verbose',
729
help='Show logs of pulled revisions.'),
731
help='Branch to pull into, '
732
'rather than the one containing the working directory.',
737
takes_args = ['location?']
738
encoding_type = 'replace'
740
def run(self, location=None, remember=False, overwrite=False,
741
revision=None, verbose=False,
743
# FIXME: too much stuff is in the command class
746
if directory is None:
749
tree_to = WorkingTree.open_containing(directory)[0]
750
branch_to = tree_to.branch
751
except errors.NoWorkingTree:
753
branch_to = Branch.open_containing(directory)[0]
755
possible_transports = []
756
if location is not None:
758
mergeable = bundle.read_mergeable_from_url(location,
759
possible_transports=possible_transports)
760
except errors.NotABundle:
763
stored_loc = branch_to.get_parent()
765
if stored_loc is None:
766
raise errors.BzrCommandError("No pull location known or"
769
display_url = urlutils.unescape_for_display(stored_loc,
772
self.outf.write("Using saved parent location: %s\n" % display_url)
773
location = stored_loc
775
if mergeable is not None:
776
if revision is not None:
777
raise errors.BzrCommandError(
778
'Cannot use -r with merge directives or bundles')
779
mergeable.install_revisions(branch_to.repository)
780
base_revision_id, revision_id, verified = \
781
mergeable.get_merge_request(branch_to.repository)
782
branch_from = branch_to
784
branch_from = Branch.open(location,
785
possible_transports=possible_transports)
787
if branch_to.get_parent() is None or remember:
788
branch_to.set_parent(branch_from.base)
790
if revision is not None:
791
if len(revision) == 1:
792
revision_id = revision[0].as_revision_id(branch_from)
794
raise errors.BzrCommandError(
795
'bzr pull --revision takes one value.')
797
branch_to.lock_write()
799
if tree_to is not None:
800
change_reporter = delta._ChangeReporter(
801
unversioned_filter=tree_to.is_ignored)
802
result = tree_to.pull(branch_from, overwrite, revision_id,
804
possible_transports=possible_transports)
806
result = branch_to.pull(branch_from, overwrite, revision_id)
808
result.report(self.outf)
809
if verbose and result.old_revid != result.new_revid:
811
branch_to.repository.iter_reverse_revision_history(
814
new_rh = branch_to.revision_history()
815
log_format = branch_to.get_config().log_format()
816
log.show_changed_revisions(branch_to, old_rh, new_rh,
818
log_format=log_format)
823
class cmd_push(Command):
824
"""Update a mirror of this branch.
826
The target branch will not have its working tree populated because this
827
is both expensive, and is not supported on remote file systems.
829
Some smart servers or protocols *may* put the working tree in place in
832
This command only works on branches that have not diverged. Branches are
833
considered diverged if the destination branch's most recent commit is one
834
that has not been merged (directly or indirectly) by the source branch.
836
If branches have diverged, you can use 'bzr push --overwrite' to replace
837
the other branch completely, discarding its unmerged changes.
839
If you want to ensure you have the different changes in the other branch,
840
do a merge (see bzr help merge) from the other branch, and commit that.
841
After that you will be able to do a push without '--overwrite'.
843
If there is no default push location set, the first push will set it.
844
After that, you can omit the location to use the default. To change the
845
default, use --remember. The value will only be saved if the remote
846
location can be accessed.
849
_see_also = ['pull', 'update', 'working-trees']
850
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
851
Option('create-prefix',
852
help='Create the path leading up to the branch '
853
'if it does not already exist.'),
855
help='Branch to push from, '
856
'rather than the one containing the working directory.',
860
Option('use-existing-dir',
861
help='By default push will fail if the target'
862
' directory exists, but does not already'
863
' have a control directory. This flag will'
864
' allow push to proceed.'),
866
help='Create a stacked branch that references the public location '
867
'of the parent branch.'),
869
help='Create a stacked branch that refers to another branch '
870
'for the commit history. Only the work not present in the '
871
'referenced branch is included in the branch created.',
874
takes_args = ['location?']
875
encoding_type = 'replace'
877
def run(self, location=None, remember=False, overwrite=False,
878
create_prefix=False, verbose=False, revision=None,
879
use_existing_dir=False, directory=None, stacked_on=None,
881
from bzrlib.push import _show_push_branch
883
# Get the source branch and revision_id
884
if directory is None:
886
br_from = Branch.open_containing(directory)[0]
887
if revision is not None:
888
if len(revision) == 1:
889
revision_id = revision[0].in_history(br_from).rev_id
891
raise errors.BzrCommandError(
892
'bzr push --revision takes one value.')
894
revision_id = br_from.last_revision()
896
# Get the stacked_on branch, if any
897
if stacked_on is not None:
898
stacked_on = urlutils.normalize_url(stacked_on)
900
parent_url = br_from.get_parent()
902
parent = Branch.open(parent_url)
903
stacked_on = parent.get_public_branch()
905
# I considered excluding non-http url's here, thus forcing
906
# 'public' branches only, but that only works for some
907
# users, so it's best to just depend on the user spotting an
908
# error by the feedback given to them. RBC 20080227.
909
stacked_on = parent_url
911
raise errors.BzrCommandError(
912
"Could not determine branch to refer to.")
914
# Get the destination location
916
stored_loc = br_from.get_push_location()
917
if stored_loc is None:
918
raise errors.BzrCommandError(
919
"No push location known or specified.")
921
display_url = urlutils.unescape_for_display(stored_loc,
923
self.outf.write("Using saved push location: %s\n" % display_url)
924
location = stored_loc
926
_show_push_branch(br_from, revision_id, location, self.outf,
927
verbose=verbose, overwrite=overwrite, remember=remember,
928
stacked_on=stacked_on, create_prefix=create_prefix,
929
use_existing_dir=use_existing_dir)
932
class cmd_branch(Command):
933
"""Create a new copy of a branch.
935
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
936
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
937
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
938
is derived from the FROM_LOCATION by stripping a leading scheme or drive
939
identifier, if any. For example, "branch lp:foo-bar" will attempt to
942
To retrieve the branch as of a particular revision, supply the --revision
943
parameter, as in "branch foo/bar -r 5".
946
_see_also = ['checkout']
947
takes_args = ['from_location', 'to_location?']
948
takes_options = ['revision', Option('hardlink',
949
help='Hard-link working tree files where possible.'),
951
help='Create a stacked branch referring to the source branch. '
952
'The new branch will depend on the availability of the source '
953
'branch for all operations.'),
955
help='Do not use a shared repository, even if available.'),
957
aliases = ['get', 'clone']
959
def run(self, from_location, to_location=None, revision=None,
960
hardlink=False, stacked=False, standalone=False):
961
from bzrlib.tag import _merge_tags_if_possible
964
elif len(revision) > 1:
965
raise errors.BzrCommandError(
966
'bzr branch --revision takes exactly 1 revision value')
968
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
972
if len(revision) == 1 and revision[0] is not None:
973
revision_id = revision[0].as_revision_id(br_from)
975
# FIXME - wt.last_revision, fallback to branch, fall back to
976
# None or perhaps NULL_REVISION to mean copy nothing
978
revision_id = br_from.last_revision()
979
if to_location is None:
980
to_location = urlutils.derive_to_location(from_location)
981
to_transport = transport.get_transport(to_location)
983
to_transport.mkdir('.')
984
except errors.FileExists:
985
raise errors.BzrCommandError('Target directory "%s" already'
986
' exists.' % to_location)
987
except errors.NoSuchFile:
988
raise errors.BzrCommandError('Parent of "%s" does not exist.'
991
# preserve whatever source format we have.
992
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
993
possible_transports=[to_transport],
994
accelerator_tree=accelerator_tree,
995
hardlink=hardlink, stacked=stacked,
996
force_new_repo=standalone,
997
source_branch=br_from)
998
branch = dir.open_branch()
999
except errors.NoSuchRevision:
1000
to_transport.delete_tree('.')
1001
msg = "The branch %s has no revision %s." % (from_location,
1003
raise errors.BzrCommandError(msg)
1004
_merge_tags_if_possible(br_from, branch)
1005
# If the source branch is stacked, the new branch may
1006
# be stacked whether we asked for that explicitly or not.
1007
# We therefore need a try/except here and not just 'if stacked:'
1009
note('Created new stacked branch referring to %s.' %
1010
branch.get_stacked_on_url())
1011
except (errors.NotStacked, errors.UnstackableBranchFormat,
1012
errors.UnstackableRepositoryFormat), e:
1013
note('Branched %d revision(s).' % branch.revno())
1018
class cmd_checkout(Command):
1019
"""Create a new checkout of an existing branch.
1021
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1022
the branch found in '.'. This is useful if you have removed the working tree
1023
or if it was never created - i.e. if you pushed the branch to its current
1024
location using SFTP.
1026
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1027
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1028
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1029
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1030
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1033
To retrieve the branch as of a particular revision, supply the --revision
1034
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1035
out of date [so you cannot commit] but it may be useful (i.e. to examine old
1039
_see_also = ['checkouts', 'branch']
1040
takes_args = ['branch_location?', 'to_location?']
1041
takes_options = ['revision',
1042
Option('lightweight',
1043
help="Perform a lightweight checkout. Lightweight "
1044
"checkouts depend on access to the branch for "
1045
"every operation. Normal checkouts can perform "
1046
"common operations like diff and status without "
1047
"such access, and also support local commits."
1049
Option('files-from', type=str,
1050
help="Get file contents from this tree."),
1052
help='Hard-link working tree files where possible.'
1057
def run(self, branch_location=None, to_location=None, revision=None,
1058
lightweight=False, files_from=None, hardlink=False):
1059
if revision is None:
1061
elif len(revision) > 1:
1062
raise errors.BzrCommandError(
1063
'bzr checkout --revision takes exactly 1 revision value')
1064
if branch_location is None:
1065
branch_location = osutils.getcwd()
1066
to_location = branch_location
1067
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1069
if files_from is not None:
1070
accelerator_tree = WorkingTree.open(files_from)
1071
if len(revision) == 1 and revision[0] is not None:
1072
revision_id = revision[0].as_revision_id(source)
1075
if to_location is None:
1076
to_location = urlutils.derive_to_location(branch_location)
1077
# if the source and to_location are the same,
1078
# and there is no working tree,
1079
# then reconstitute a branch
1080
if (osutils.abspath(to_location) ==
1081
osutils.abspath(branch_location)):
1083
source.bzrdir.open_workingtree()
1084
except errors.NoWorkingTree:
1085
source.bzrdir.create_workingtree(revision_id)
1087
source.create_checkout(to_location, revision_id, lightweight,
1088
accelerator_tree, hardlink)
1091
class cmd_renames(Command):
1092
"""Show list of renamed files.
1094
# TODO: Option to show renames between two historical versions.
1096
# TODO: Only show renames under dir, rather than in the whole branch.
1097
_see_also = ['status']
1098
takes_args = ['dir?']
1101
def run(self, dir=u'.'):
1102
tree = WorkingTree.open_containing(dir)[0]
1105
new_inv = tree.inventory
1106
old_tree = tree.basis_tree()
1107
old_tree.lock_read()
1109
old_inv = old_tree.inventory
1111
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1112
for f, paths, c, v, p, n, k, e in iterator:
1113
if paths[0] == paths[1]:
1117
renames.append(paths)
1119
for old_name, new_name in renames:
1120
self.outf.write("%s => %s\n" % (old_name, new_name))
1127
class cmd_update(Command):
1128
"""Update a tree to have the latest code committed to its branch.
1130
This will perform a merge into the working tree, and may generate
1131
conflicts. If you have any local changes, you will still
1132
need to commit them after the update for the update to be complete.
1134
If you want to discard your local changes, you can just do a
1135
'bzr revert' instead of 'bzr commit' after the update.
1138
_see_also = ['pull', 'working-trees', 'status-flags']
1139
takes_args = ['dir?']
1142
def run(self, dir='.'):
1143
tree = WorkingTree.open_containing(dir)[0]
1144
possible_transports = []
1145
master = tree.branch.get_master_branch(
1146
possible_transports=possible_transports)
1147
if master is not None:
1150
tree.lock_tree_write()
1152
existing_pending_merges = tree.get_parent_ids()[1:]
1153
last_rev = _mod_revision.ensure_null(tree.last_revision())
1154
if last_rev == _mod_revision.ensure_null(
1155
tree.branch.last_revision()):
1156
# may be up to date, check master too.
1157
if master is None or last_rev == _mod_revision.ensure_null(
1158
master.last_revision()):
1159
revno = tree.branch.revision_id_to_revno(last_rev)
1160
note("Tree is up to date at revision %d." % (revno,))
1162
conflicts = tree.update(
1163
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1164
possible_transports=possible_transports)
1165
revno = tree.branch.revision_id_to_revno(
1166
_mod_revision.ensure_null(tree.last_revision()))
1167
note('Updated to revision %d.' % (revno,))
1168
if tree.get_parent_ids()[1:] != existing_pending_merges:
1169
note('Your local commits will now show as pending merges with '
1170
"'bzr status', and can be committed with 'bzr commit'.")
1179
class cmd_info(Command):
1180
"""Show information about a working tree, branch or repository.
1182
This command will show all known locations and formats associated to the
1183
tree, branch or repository. Statistical information is included with
1186
Branches and working trees will also report any missing revisions.
1188
_see_also = ['revno', 'working-trees', 'repositories']
1189
takes_args = ['location?']
1190
takes_options = ['verbose']
1191
encoding_type = 'replace'
1194
def run(self, location=None, verbose=False):
1199
from bzrlib.info import show_bzrdir_info
1200
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1201
verbose=noise_level, outfile=self.outf)
1204
class cmd_remove(Command):
1205
"""Remove files or directories.
1207
This makes bzr stop tracking changes to the specified files. bzr will delete
1208
them if they can easily be recovered using revert. If no options or
1209
parameters are given bzr will scan for files that are being tracked by bzr
1210
but missing in your tree and stop tracking them for you.
1212
takes_args = ['file*']
1213
takes_options = ['verbose',
1214
Option('new', help='Only remove files that have never been committed.'),
1215
RegistryOption.from_kwargs('file-deletion-strategy',
1216
'The file deletion mode to be used.',
1217
title='Deletion Strategy', value_switches=True, enum_switch=False,
1218
safe='Only delete files if they can be'
1219
' safely recovered (default).',
1220
keep="Don't delete any files.",
1221
force='Delete all the specified files, even if they can not be '
1222
'recovered and even if they are non-empty directories.')]
1223
aliases = ['rm', 'del']
1224
encoding_type = 'replace'
1226
def run(self, file_list, verbose=False, new=False,
1227
file_deletion_strategy='safe'):
1228
tree, file_list = tree_files(file_list)
1230
if file_list is not None:
1231
file_list = [f for f in file_list]
1235
# Heuristics should probably all move into tree.remove_smart or
1238
added = tree.changes_from(tree.basis_tree(),
1239
specific_files=file_list).added
1240
file_list = sorted([f[0] for f in added], reverse=True)
1241
if len(file_list) == 0:
1242
raise errors.BzrCommandError('No matching files.')
1243
elif file_list is None:
1244
# missing files show up in iter_changes(basis) as
1245
# versioned-with-no-kind.
1247
for change in tree.iter_changes(tree.basis_tree()):
1248
# Find paths in the working tree that have no kind:
1249
if change[1][1] is not None and change[6][1] is None:
1250
missing.append(change[1][1])
1251
file_list = sorted(missing, reverse=True)
1252
file_deletion_strategy = 'keep'
1253
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1254
keep_files=file_deletion_strategy=='keep',
1255
force=file_deletion_strategy=='force')
1260
class cmd_file_id(Command):
1261
"""Print file_id of a particular file or directory.
1263
The file_id is assigned when the file is first added and remains the
1264
same through all revisions where the file exists, even when it is
1269
_see_also = ['inventory', 'ls']
1270
takes_args = ['filename']
1273
def run(self, filename):
1274
tree, relpath = WorkingTree.open_containing(filename)
1275
i = tree.path2id(relpath)
1277
raise errors.NotVersionedError(filename)
1279
self.outf.write(i + '\n')
1282
class cmd_file_path(Command):
1283
"""Print path of file_ids to a file or directory.
1285
This prints one line for each directory down to the target,
1286
starting at the branch root.
1290
takes_args = ['filename']
1293
def run(self, filename):
1294
tree, relpath = WorkingTree.open_containing(filename)
1295
fid = tree.path2id(relpath)
1297
raise errors.NotVersionedError(filename)
1298
segments = osutils.splitpath(relpath)
1299
for pos in range(1, len(segments) + 1):
1300
path = osutils.joinpath(segments[:pos])
1301
self.outf.write("%s\n" % tree.path2id(path))
1304
class cmd_reconcile(Command):
1305
"""Reconcile bzr metadata in a branch.
1307
This can correct data mismatches that may have been caused by
1308
previous ghost operations or bzr upgrades. You should only
1309
need to run this command if 'bzr check' or a bzr developer
1310
advises you to run it.
1312
If a second branch is provided, cross-branch reconciliation is
1313
also attempted, which will check that data like the tree root
1314
id which was not present in very early bzr versions is represented
1315
correctly in both branches.
1317
At the same time it is run it may recompress data resulting in
1318
a potential saving in disk space or performance gain.
1320
The branch *MUST* be on a listable system such as local disk or sftp.
1323
_see_also = ['check']
1324
takes_args = ['branch?']
1326
def run(self, branch="."):
1327
from bzrlib.reconcile import reconcile
1328
dir = bzrdir.BzrDir.open(branch)
1332
class cmd_revision_history(Command):
1333
"""Display the list of revision ids on a branch."""
1336
takes_args = ['location?']
1341
def run(self, location="."):
1342
branch = Branch.open_containing(location)[0]
1343
for revid in branch.revision_history():
1344
self.outf.write(revid)
1345
self.outf.write('\n')
1348
class cmd_ancestry(Command):
1349
"""List all revisions merged into this branch."""
1351
_see_also = ['log', 'revision-history']
1352
takes_args = ['location?']
1357
def run(self, location="."):
1359
wt = WorkingTree.open_containing(location)[0]
1360
except errors.NoWorkingTree:
1361
b = Branch.open(location)
1362
last_revision = b.last_revision()
1365
last_revision = wt.last_revision()
1367
revision_ids = b.repository.get_ancestry(last_revision)
1369
for revision_id in revision_ids:
1370
self.outf.write(revision_id + '\n')
1373
class cmd_init(Command):
1374
"""Make a directory into a versioned branch.
1376
Use this to create an empty branch, or before importing an
1379
If there is a repository in a parent directory of the location, then
1380
the history of the branch will be stored in the repository. Otherwise
1381
init creates a standalone branch which carries its own history
1382
in the .bzr directory.
1384
If there is already a branch at the location but it has no working tree,
1385
the tree can be populated with 'bzr checkout'.
1387
Recipe for importing a tree of files::
1393
bzr commit -m "imported project"
1396
_see_also = ['init-repository', 'branch', 'checkout']
1397
takes_args = ['location?']
1399
Option('create-prefix',
1400
help='Create the path leading up to the branch '
1401
'if it does not already exist.'),
1402
RegistryOption('format',
1403
help='Specify a format for this branch. '
1404
'See "help formats".',
1405
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1406
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1407
value_switches=True,
1408
title="Branch Format",
1410
Option('append-revisions-only',
1411
help='Never change revnos or the existing log.'
1412
' Append revisions to it only.')
1414
def run(self, location=None, format=None, append_revisions_only=False,
1415
create_prefix=False):
1417
format = bzrdir.format_registry.make_bzrdir('default')
1418
if location is None:
1421
to_transport = transport.get_transport(location)
1423
# The path has to exist to initialize a
1424
# branch inside of it.
1425
# Just using os.mkdir, since I don't
1426
# believe that we want to create a bunch of
1427
# locations if the user supplies an extended path
1429
to_transport.ensure_base()
1430
except errors.NoSuchFile:
1431
if not create_prefix:
1432
raise errors.BzrCommandError("Parent directory of %s"
1434
"\nYou may supply --create-prefix to create all"
1435
" leading parent directories."
1437
_create_prefix(to_transport)
1440
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1441
except errors.NotBranchError:
1442
# really a NotBzrDir error...
1443
create_branch = bzrdir.BzrDir.create_branch_convenience
1444
branch = create_branch(to_transport.base, format=format,
1445
possible_transports=[to_transport])
1446
a_bzrdir = branch.bzrdir
1448
from bzrlib.transport.local import LocalTransport
1449
if a_bzrdir.has_branch():
1450
if (isinstance(to_transport, LocalTransport)
1451
and not a_bzrdir.has_workingtree()):
1452
raise errors.BranchExistsWithoutWorkingTree(location)
1453
raise errors.AlreadyBranchError(location)
1454
branch = a_bzrdir.create_branch()
1455
a_bzrdir.create_workingtree()
1456
if append_revisions_only:
1458
branch.set_append_revisions_only(True)
1459
except errors.UpgradeRequired:
1460
raise errors.BzrCommandError('This branch format cannot be set'
1461
' to append-revisions-only. Try --experimental-branch6')
1463
from bzrlib.info import show_bzrdir_info
1464
show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1467
class cmd_init_repository(Command):
1468
"""Create a shared repository to hold branches.
1470
New branches created under the repository directory will store their
1471
revisions in the repository, not in the branch directory.
1473
If the --no-trees option is used then the branches in the repository
1474
will not have working trees by default.
1477
Create a shared repositories holding just branches::
1479
bzr init-repo --no-trees repo
1482
Make a lightweight checkout elsewhere::
1484
bzr checkout --lightweight repo/trunk trunk-checkout
1489
_see_also = ['init', 'branch', 'checkout', 'repositories']
1490
takes_args = ["location"]
1491
takes_options = [RegistryOption('format',
1492
help='Specify a format for this repository. See'
1493
' "bzr help formats" for details.',
1494
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1495
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1496
value_switches=True, title='Repository format'),
1498
help='Branches in the repository will default to'
1499
' not having a working tree.'),
1501
aliases = ["init-repo"]
1503
def run(self, location, format=None, no_trees=False):
1505
format = bzrdir.format_registry.make_bzrdir('default')
1507
if location is None:
1510
to_transport = transport.get_transport(location)
1511
to_transport.ensure_base()
1513
newdir = format.initialize_on_transport(to_transport)
1514
repo = newdir.create_repository(shared=True)
1515
repo.set_make_working_trees(not no_trees)
1517
from bzrlib.info import show_bzrdir_info
1518
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1521
class cmd_diff(Command):
1522
"""Show differences in the working tree, between revisions or branches.
1524
If no arguments are given, all changes for the current tree are listed.
1525
If files are given, only the changes in those files are listed.
1526
Remote and multiple branches can be compared by using the --old and
1527
--new options. If not provided, the default for both is derived from
1528
the first argument, if any, or the current tree if no arguments are
1531
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1532
produces patches suitable for "patch -p1".
1536
2 - unrepresentable changes
1541
Shows the difference in the working tree versus the last commit::
1545
Difference between the working tree and revision 1::
1549
Difference between revision 2 and revision 1::
1553
Difference between revision 2 and revision 1 for branch xxx::
1557
Show just the differences for file NEWS::
1561
Show the differences in working tree xxx for file NEWS::
1565
Show the differences from branch xxx to this working tree:
1569
Show the differences between two branches for file NEWS::
1571
bzr diff --old xxx --new yyy NEWS
1573
Same as 'bzr diff' but prefix paths with old/ and new/::
1575
bzr diff --prefix old/:new/
1577
_see_also = ['status']
1578
takes_args = ['file*']
1580
Option('diff-options', type=str,
1581
help='Pass these options to the external diff program.'),
1582
Option('prefix', type=str,
1584
help='Set prefixes added to old and new filenames, as '
1585
'two values separated by a colon. (eg "old/:new/").'),
1587
help='Branch/tree to compare from.',
1591
help='Branch/tree to compare to.',
1597
help='Use this command to compare files.',
1601
aliases = ['di', 'dif']
1602
encoding_type = 'exact'
1605
def run(self, revision=None, file_list=None, diff_options=None,
1606
prefix=None, old=None, new=None, using=None):
1607
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1609
if (prefix is None) or (prefix == '0'):
1617
old_label, new_label = prefix.split(":")
1619
raise errors.BzrCommandError(
1620
'--prefix expects two values separated by a colon'
1621
' (eg "old/:new/")')
1623
if revision and len(revision) > 2:
1624
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1625
' one or two revision specifiers')
1627
old_tree, new_tree, specific_files, extra_trees = \
1628
_get_trees_to_diff(file_list, revision, old, new)
1629
return show_diff_trees(old_tree, new_tree, sys.stdout,
1630
specific_files=specific_files,
1631
external_diff_options=diff_options,
1632
old_label=old_label, new_label=new_label,
1633
extra_trees=extra_trees, using=using)
1636
class cmd_deleted(Command):
1637
"""List files deleted in the working tree.
1639
# TODO: Show files deleted since a previous revision, or
1640
# between two revisions.
1641
# TODO: Much more efficient way to do this: read in new
1642
# directories with readdir, rather than stating each one. Same
1643
# level of effort but possibly much less IO. (Or possibly not,
1644
# if the directories are very large...)
1645
_see_also = ['status', 'ls']
1646
takes_options = ['show-ids']
1649
def run(self, show_ids=False):
1650
tree = WorkingTree.open_containing(u'.')[0]
1653
old = tree.basis_tree()
1656
for path, ie in old.inventory.iter_entries():
1657
if not tree.has_id(ie.file_id):
1658
self.outf.write(path)
1660
self.outf.write(' ')
1661
self.outf.write(ie.file_id)
1662
self.outf.write('\n')
1669
class cmd_modified(Command):
1670
"""List files modified in working tree.
1674
_see_also = ['status', 'ls']
1677
help='Write an ascii NUL (\\0) separator '
1678
'between files rather than a newline.')
1682
def run(self, null=False):
1683
tree = WorkingTree.open_containing(u'.')[0]
1684
td = tree.changes_from(tree.basis_tree())
1685
for path, id, kind, text_modified, meta_modified in td.modified:
1687
self.outf.write(path + '\0')
1689
self.outf.write(osutils.quotefn(path) + '\n')
1692
class cmd_added(Command):
1693
"""List files added in working tree.
1697
_see_also = ['status', 'ls']
1700
help='Write an ascii NUL (\\0) separator '
1701
'between files rather than a newline.')
1705
def run(self, null=False):
1706
wt = WorkingTree.open_containing(u'.')[0]
1709
basis = wt.basis_tree()
1712
basis_inv = basis.inventory
1715
if file_id in basis_inv:
1717
if inv.is_root(file_id) and len(basis_inv) == 0:
1719
path = inv.id2path(file_id)
1720
if not os.access(osutils.abspath(path), os.F_OK):
1723
self.outf.write(path + '\0')
1725
self.outf.write(osutils.quotefn(path) + '\n')
1732
class cmd_root(Command):
1733
"""Show the tree root directory.
1735
The root is the nearest enclosing directory with a .bzr control
1738
takes_args = ['filename?']
1740
def run(self, filename=None):
1741
"""Print the branch root."""
1742
tree = WorkingTree.open_containing(filename)[0]
1743
self.outf.write(tree.basedir + '\n')
1746
def _parse_limit(limitstring):
1748
return int(limitstring)
1750
msg = "The limit argument must be an integer."
1751
raise errors.BzrCommandError(msg)
1754
class cmd_log(Command):
1755
"""Show log of a branch, file, or directory.
1757
By default show the log of the branch containing the working directory.
1759
To request a range of logs, you can use the command -r begin..end
1760
-r revision requests a specific revision, -r ..end or -r begin.. are
1764
Log the current branch::
1772
Log the last 10 revisions of a branch::
1774
bzr log -r -10.. http://server/branch
1777
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1779
takes_args = ['location?']
1782
help='Show from oldest to newest.'),
1784
custom_help('verbose',
1785
help='Show files changed in each revision.'),
1789
type=bzrlib.option._parse_revision_str,
1791
help='Show just the specified revision.'
1792
' See also "help revisionspec".'),
1796
help='Show revisions whose message matches this '
1797
'regular expression.',
1801
help='Limit the output to the first N revisions.',
1805
encoding_type = 'replace'
1808
def run(self, location=None, timezone='original',
1817
from bzrlib.log import show_log
1818
direction = (forward and 'forward') or 'reverse'
1820
if change is not None:
1822
raise errors.RangeInChangeOption()
1823
if revision is not None:
1824
raise errors.BzrCommandError(
1825
'--revision and --change are mutually exclusive')
1832
# find the file id to log:
1834
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1838
tree = b.basis_tree()
1839
file_id = tree.path2id(fp)
1841
raise errors.BzrCommandError(
1842
"Path does not have any revision history: %s" %
1846
# FIXME ? log the current subdir only RBC 20060203
1847
if revision is not None \
1848
and len(revision) > 0 and revision[0].get_branch():
1849
location = revision[0].get_branch()
1852
dir, relpath = bzrdir.BzrDir.open_containing(location)
1853
b = dir.open_branch()
1857
rev1, rev2 = _get_revision_range(revision, b, self.name())
1858
if log_format is None:
1859
log_format = log.log_formatter_registry.get_default(b)
1861
lf = log_format(show_ids=show_ids, to_file=self.outf,
1862
show_timezone=timezone,
1863
delta_format=get_verbosity_level())
1869
direction=direction,
1870
start_revision=rev1,
1877
def _get_revision_range(revisionspec_list, branch, command_name):
1878
"""Take the input of a revision option and turn it into a revision range.
1880
It returns RevisionInfo objects which can be used to obtain the rev_id's
1881
of the desired revisons. It does some user input validations.
1883
if revisionspec_list is None:
1886
elif len(revisionspec_list) == 1:
1887
rev1 = rev2 = revisionspec_list[0].in_history(branch)
1888
elif len(revisionspec_list) == 2:
1889
if revisionspec_list[1].get_branch() != revisionspec_list[0
1891
# b is taken from revision[0].get_branch(), and
1892
# show_log will use its revision_history. Having
1893
# different branches will lead to weird behaviors.
1894
raise errors.BzrCommandError(
1895
"bzr %s doesn't accept two revisions in different"
1896
" branches." % command_name)
1897
rev1 = revisionspec_list[0].in_history(branch)
1898
rev2 = revisionspec_list[1].in_history(branch)
1900
raise errors.BzrCommandError(
1901
'bzr %s --revision takes one or two values.' % command_name)
1905
def _revision_range_to_revid_range(revision_range):
1908
if revision_range[0] is not None:
1909
rev_id1 = revision_range[0].rev_id
1910
if revision_range[1] is not None:
1911
rev_id2 = revision_range[1].rev_id
1912
return rev_id1, rev_id2
1914
def get_log_format(long=False, short=False, line=False, default='long'):
1915
log_format = default
1919
log_format = 'short'
1925
class cmd_touching_revisions(Command):
1926
"""Return revision-ids which affected a particular file.
1928
A more user-friendly interface is "bzr log FILE".
1932
takes_args = ["filename"]
1935
def run(self, filename):
1936
tree, relpath = WorkingTree.open_containing(filename)
1938
file_id = tree.path2id(relpath)
1939
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1940
self.outf.write("%6d %s\n" % (revno, what))
1943
class cmd_ls(Command):
1944
"""List files in a tree.
1947
_see_also = ['status', 'cat']
1948
takes_args = ['path?']
1949
# TODO: Take a revision or remote path and list that tree instead.
1953
Option('non-recursive',
1954
help='Don\'t recurse into subdirectories.'),
1956
help='Print paths relative to the root of the branch.'),
1957
Option('unknown', help='Print unknown files.'),
1958
Option('versioned', help='Print versioned files.',
1960
Option('ignored', help='Print ignored files.'),
1962
help='Write an ascii NUL (\\0) separator '
1963
'between files rather than a newline.'),
1965
help='List entries of a particular kind: file, directory, symlink.',
1970
def run(self, revision=None, verbose=False,
1971
non_recursive=False, from_root=False,
1972
unknown=False, versioned=False, ignored=False,
1973
null=False, kind=None, show_ids=False, path=None):
1975
if kind and kind not in ('file', 'directory', 'symlink'):
1976
raise errors.BzrCommandError('invalid kind specified')
1978
if verbose and null:
1979
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1980
all = not (unknown or versioned or ignored)
1982
selection = {'I':ignored, '?':unknown, 'V':versioned}
1989
raise errors.BzrCommandError('cannot specify both --from-root'
1993
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1999
if revision is not None or tree is None:
2000
tree = _get_one_revision_tree('ls', revision, branch=branch)
2004
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2005
if fp.startswith(relpath):
2006
fp = osutils.pathjoin(prefix, fp[len(relpath):])
2007
if non_recursive and '/' in fp:
2009
if not all and not selection[fc]:
2011
if kind is not None and fkind != kind:
2013
kindch = entry.kind_character()
2014
outstring = fp + kindch
2016
outstring = '%-8s %s' % (fc, outstring)
2017
if show_ids and fid is not None:
2018
outstring = "%-50s %s" % (outstring, fid)
2019
self.outf.write(outstring + '\n')
2021
self.outf.write(fp + '\0')
2024
self.outf.write(fid)
2025
self.outf.write('\0')
2033
self.outf.write('%-50s %s\n' % (outstring, my_id))
2035
self.outf.write(outstring + '\n')
2040
class cmd_unknowns(Command):
2041
"""List unknown files.
2049
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2050
self.outf.write(osutils.quotefn(f) + '\n')
2053
class cmd_ignore(Command):
2054
"""Ignore specified files or patterns.
2056
See ``bzr help patterns`` for details on the syntax of patterns.
2058
To remove patterns from the ignore list, edit the .bzrignore file.
2059
After adding, editing or deleting that file either indirectly by
2060
using this command or directly by using an editor, be sure to commit
2063
Note: ignore patterns containing shell wildcards must be quoted from
2067
Ignore the top level Makefile::
2069
bzr ignore ./Makefile
2071
Ignore class files in all directories::
2073
bzr ignore "*.class"
2075
Ignore .o files under the lib directory::
2077
bzr ignore "lib/**/*.o"
2079
Ignore .o files under the lib directory::
2081
bzr ignore "RE:lib/.*\.o"
2083
Ignore everything but the "debian" toplevel directory::
2085
bzr ignore "RE:(?!debian/).*"
2088
_see_also = ['status', 'ignored', 'patterns']
2089
takes_args = ['name_pattern*']
2091
Option('old-default-rules',
2092
help='Write out the ignore rules bzr < 0.9 always used.')
2095
def run(self, name_pattern_list=None, old_default_rules=None):
2096
from bzrlib import ignores
2097
if old_default_rules is not None:
2098
# dump the rules and exit
2099
for pattern in ignores.OLD_DEFAULTS:
2102
if not name_pattern_list:
2103
raise errors.BzrCommandError("ignore requires at least one "
2104
"NAME_PATTERN or --old-default-rules")
2105
name_pattern_list = [globbing.normalize_pattern(p)
2106
for p in name_pattern_list]
2107
for name_pattern in name_pattern_list:
2108
if (name_pattern[0] == '/' or
2109
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2110
raise errors.BzrCommandError(
2111
"NAME_PATTERN should not be an absolute path")
2112
tree, relpath = WorkingTree.open_containing(u'.')
2113
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2114
ignored = globbing.Globster(name_pattern_list)
2117
for entry in tree.list_files():
2121
if ignored.match(filename):
2122
matches.append(filename.encode('utf-8'))
2124
if len(matches) > 0:
2125
print "Warning: the following files are version controlled and" \
2126
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2129
class cmd_ignored(Command):
2130
"""List ignored files and the patterns that matched them.
2132
List all the ignored files and the ignore pattern that caused the file to
2135
Alternatively, to list just the files::
2140
encoding_type = 'replace'
2141
_see_also = ['ignore', 'ls']
2145
tree = WorkingTree.open_containing(u'.')[0]
2148
for path, file_class, kind, file_id, entry in tree.list_files():
2149
if file_class != 'I':
2151
## XXX: Slightly inefficient since this was already calculated
2152
pat = tree.is_ignored(path)
2153
self.outf.write('%-50s %s\n' % (path, pat))
2158
class cmd_lookup_revision(Command):
2159
"""Lookup the revision-id from a revision-number
2162
bzr lookup-revision 33
2165
takes_args = ['revno']
2168
def run(self, revno):
2172
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2174
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2177
class cmd_export(Command):
2178
"""Export current or past revision to a destination directory or archive.
2180
If no revision is specified this exports the last committed revision.
2182
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2183
given, try to find the format with the extension. If no extension
2184
is found exports to a directory (equivalent to --format=dir).
2186
If root is supplied, it will be used as the root directory inside
2187
container formats (tar, zip, etc). If it is not supplied it will default
2188
to the exported filename. The root option has no effect for 'dir' format.
2190
If branch is omitted then the branch containing the current working
2191
directory will be used.
2193
Note: Export of tree with non-ASCII filenames to zip is not supported.
2195
================= =========================
2196
Supported formats Autodetected by extension
2197
================= =========================
2200
tbz2 .tar.bz2, .tbz2
2203
================= =========================
2205
takes_args = ['dest', 'branch_or_subdir?']
2208
help="Type of file to export to.",
2213
help="Name of the root directory inside the exported file."),
2215
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2217
from bzrlib.export import export
2219
if branch_or_subdir is None:
2220
tree = WorkingTree.open_containing(u'.')[0]
2224
b, subdir = Branch.open_containing(branch_or_subdir)
2227
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2229
export(rev_tree, dest, format, root, subdir)
2230
except errors.NoSuchExportFormat, e:
2231
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2234
class cmd_cat(Command):
2235
"""Write the contents of a file as of a given revision to standard output.
2237
If no revision is nominated, the last revision is used.
2239
Note: Take care to redirect standard output when using this command on a
2245
Option('name-from-revision', help='The path name in the old tree.'),
2248
takes_args = ['filename']
2249
encoding_type = 'exact'
2252
def run(self, filename, revision=None, name_from_revision=False):
2253
if revision is not None and len(revision) != 1:
2254
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2255
" one revision specifier")
2256
tree, branch, relpath = \
2257
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2260
return self._run(tree, branch, relpath, filename, revision,
2265
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2267
tree = b.basis_tree()
2268
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2270
cur_file_id = tree.path2id(relpath)
2271
old_file_id = rev_tree.path2id(relpath)
2273
if name_from_revision:
2274
if old_file_id is None:
2275
raise errors.BzrCommandError(
2276
"%r is not present in revision %s" % (
2277
filename, rev_tree.get_revision_id()))
2279
content = rev_tree.get_file_text(old_file_id)
2280
elif cur_file_id is not None:
2281
content = rev_tree.get_file_text(cur_file_id)
2282
elif old_file_id is not None:
2283
content = rev_tree.get_file_text(old_file_id)
2285
raise errors.BzrCommandError(
2286
"%r is not present in revision %s" % (
2287
filename, rev_tree.get_revision_id()))
2288
self.outf.write(content)
2291
class cmd_local_time_offset(Command):
2292
"""Show the offset in seconds from GMT to local time."""
2296
print osutils.local_time_offset()
2300
class cmd_commit(Command):
2301
"""Commit changes into a new revision.
2303
If no arguments are given, the entire tree is committed.
2305
If selected files are specified, only changes to those files are
2306
committed. If a directory is specified then the directory and everything
2307
within it is committed.
2309
When excludes are given, they take precedence over selected files.
2310
For example, too commit only changes within foo, but not changes within
2313
bzr commit foo -x foo/bar
2315
If author of the change is not the same person as the committer, you can
2316
specify the author's name using the --author option. The name should be
2317
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2319
A selected-file commit may fail in some cases where the committed
2320
tree would be invalid. Consider::
2325
bzr commit foo -m "committing foo"
2326
bzr mv foo/bar foo/baz
2329
bzr commit foo/bar -m "committing bar but not baz"
2331
In the example above, the last commit will fail by design. This gives
2332
the user the opportunity to decide whether they want to commit the
2333
rename at the same time, separately first, or not at all. (As a general
2334
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2336
Note: A selected-file commit after a merge is not yet supported.
2338
# TODO: Run hooks on tree to-be-committed, and after commit.
2340
# TODO: Strict commit that fails if there are deleted files.
2341
# (what does "deleted files" mean ??)
2343
# TODO: Give better message for -s, --summary, used by tla people
2345
# XXX: verbose currently does nothing
2347
_see_also = ['bugs', 'uncommit']
2348
takes_args = ['selected*']
2350
ListOption('exclude', type=str, short_name='x',
2351
help="Do not consider changes made to a given path."),
2352
Option('message', type=unicode,
2354
help="Description of the new revision."),
2357
help='Commit even if nothing has changed.'),
2358
Option('file', type=str,
2361
help='Take commit message from this file.'),
2363
help="Refuse to commit if there are unknown "
2364
"files in the working tree."),
2365
ListOption('fixes', type=str,
2366
help="Mark a bug as being fixed by this revision."),
2367
Option('author', type=unicode,
2368
help="Set the author's name, if it's different "
2369
"from the committer."),
2371
help="Perform a local commit in a bound "
2372
"branch. Local commits are not pushed to "
2373
"the master branch until a normal commit "
2377
help='When no message is supplied, show the diff along'
2378
' with the status summary in the message editor.'),
2380
aliases = ['ci', 'checkin']
2382
def _get_bug_fix_properties(self, fixes, branch):
2384
# Configure the properties for bug fixing attributes.
2385
for fixed_bug in fixes:
2386
tokens = fixed_bug.split(':')
2387
if len(tokens) != 2:
2388
raise errors.BzrCommandError(
2389
"Invalid bug %s. Must be in the form of 'tag:id'. "
2390
"Commit refused." % fixed_bug)
2391
tag, bug_id = tokens
2393
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2394
except errors.UnknownBugTrackerAbbreviation:
2395
raise errors.BzrCommandError(
2396
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2397
except errors.MalformedBugIdentifier:
2398
raise errors.BzrCommandError(
2399
"Invalid bug identifier for %s. Commit refused."
2401
properties.append('%s fixed' % bug_url)
2402
return '\n'.join(properties)
2404
def run(self, message=None, file=None, verbose=False, selected_list=None,
2405
unchanged=False, strict=False, local=False, fixes=None,
2406
author=None, show_diff=False, exclude=None):
2407
from bzrlib.errors import (
2412
from bzrlib.msgeditor import (
2413
edit_commit_message_encoded,
2414
generate_commit_message_template,
2415
make_commit_message_template_encoded
2418
# TODO: Need a blackbox test for invoking the external editor; may be
2419
# slightly problematic to run this cross-platform.
2421
# TODO: do more checks that the commit will succeed before
2422
# spending the user's valuable time typing a commit message.
2426
tree, selected_list = tree_files(selected_list)
2427
if selected_list == ['']:
2428
# workaround - commit of root of tree should be exactly the same
2429
# as just default commit in that tree, and succeed even though
2430
# selected-file merge commit is not done yet
2435
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2437
properties['bugs'] = bug_property
2439
if local and not tree.branch.get_bound_location():
2440
raise errors.LocalRequiresBoundBranch()
2442
def get_message(commit_obj):
2443
"""Callback to get commit message"""
2444
my_message = message
2445
if my_message is None and not file:
2446
t = make_commit_message_template_encoded(tree,
2447
selected_list, diff=show_diff,
2448
output_encoding=osutils.get_user_encoding())
2449
start_message = generate_commit_message_template(commit_obj)
2450
my_message = edit_commit_message_encoded(t,
2451
start_message=start_message)
2452
if my_message is None:
2453
raise errors.BzrCommandError("please specify a commit"
2454
" message with either --message or --file")
2455
elif my_message and file:
2456
raise errors.BzrCommandError(
2457
"please specify either --message or --file")
2459
my_message = codecs.open(file, 'rt',
2460
osutils.get_user_encoding()).read()
2461
if my_message == "":
2462
raise errors.BzrCommandError("empty commit message specified")
2466
tree.commit(message_callback=get_message,
2467
specific_files=selected_list,
2468
allow_pointless=unchanged, strict=strict, local=local,
2469
reporter=None, verbose=verbose, revprops=properties,
2471
exclude=safe_relpath_files(tree, exclude))
2472
except PointlessCommit:
2473
# FIXME: This should really happen before the file is read in;
2474
# perhaps prepare the commit; get the message; then actually commit
2475
raise errors.BzrCommandError("no changes to commit."
2476
" use --unchanged to commit anyhow")
2477
except ConflictsInTree:
2478
raise errors.BzrCommandError('Conflicts detected in working '
2479
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2481
except StrictCommitFailed:
2482
raise errors.BzrCommandError("Commit refused because there are"
2483
" unknown files in the working tree.")
2484
except errors.BoundBranchOutOfDate, e:
2485
raise errors.BzrCommandError(str(e) + "\n"
2486
'To commit to master branch, run update and then commit.\n'
2487
'You can also pass --local to commit to continue working '
2491
class cmd_check(Command):
2492
"""Validate working tree structure, branch consistency and repository history.
2494
This command checks various invariants about branch and repository storage
2495
to detect data corruption or bzr bugs.
2497
The working tree and branch checks will only give output if a problem is
2498
detected. The output fields of the repository check are:
2500
revisions: This is just the number of revisions checked. It doesn't
2502
versionedfiles: This is just the number of versionedfiles checked. It
2503
doesn't indicate a problem.
2504
unreferenced ancestors: Texts that are ancestors of other texts, but
2505
are not properly referenced by the revision ancestry. This is a
2506
subtle problem that Bazaar can work around.
2507
unique file texts: This is the total number of unique file contents
2508
seen in the checked revisions. It does not indicate a problem.
2509
repeated file texts: This is the total number of repeated texts seen
2510
in the checked revisions. Texts can be repeated when their file
2511
entries are modified, but the file contents are not. It does not
2514
If no restrictions are specified, all Bazaar data that is found at the given
2515
location will be checked.
2519
Check the tree and branch at 'foo'::
2521
bzr check --tree --branch foo
2523
Check only the repository at 'bar'::
2525
bzr check --repo bar
2527
Check everything at 'baz'::
2532
_see_also = ['reconcile']
2533
takes_args = ['path?']
2534
takes_options = ['verbose',
2535
Option('branch', help="Check the branch related to the"
2536
" current directory."),
2537
Option('repo', help="Check the repository related to the"
2538
" current directory."),
2539
Option('tree', help="Check the working tree related to"
2540
" the current directory.")]
2542
def run(self, path=None, verbose=False, branch=False, repo=False,
2544
from bzrlib.check import check_dwim
2547
if not branch and not repo and not tree:
2548
branch = repo = tree = True
2549
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2552
class cmd_upgrade(Command):
2553
"""Upgrade branch storage to current format.
2555
The check command or bzr developers may sometimes advise you to run
2556
this command. When the default format has changed you may also be warned
2557
during other operations to upgrade.
2560
_see_also = ['check']
2561
takes_args = ['url?']
2563
RegistryOption('format',
2564
help='Upgrade to a specific format. See "bzr help'
2565
' formats" for details.',
2566
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2567
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2568
value_switches=True, title='Branch format'),
2571
def run(self, url='.', format=None):
2572
from bzrlib.upgrade import upgrade
2574
format = bzrdir.format_registry.make_bzrdir('default')
2575
upgrade(url, format)
2578
class cmd_whoami(Command):
2579
"""Show or set bzr user id.
2582
Show the email of the current user::
2586
Set the current user::
2588
bzr whoami "Frank Chu <fchu@example.com>"
2590
takes_options = [ Option('email',
2591
help='Display email address only.'),
2593
help='Set identity for the current branch instead of '
2596
takes_args = ['name?']
2597
encoding_type = 'replace'
2600
def run(self, email=False, branch=False, name=None):
2602
# use branch if we're inside one; otherwise global config
2604
c = Branch.open_containing('.')[0].get_config()
2605
except errors.NotBranchError:
2606
c = config.GlobalConfig()
2608
self.outf.write(c.user_email() + '\n')
2610
self.outf.write(c.username() + '\n')
2613
# display a warning if an email address isn't included in the given name.
2615
config.extract_email_address(name)
2616
except errors.NoEmailInUsername, e:
2617
warning('"%s" does not seem to contain an email address. '
2618
'This is allowed, but not recommended.', name)
2620
# use global config unless --branch given
2622
c = Branch.open_containing('.')[0].get_config()
2624
c = config.GlobalConfig()
2625
c.set_user_option('email', name)
2628
class cmd_nick(Command):
2629
"""Print or set the branch nickname.
2631
If unset, the tree root directory name is used as the nickname.
2632
To print the current nickname, execute with no argument.
2634
Bound branches use the nickname of its master branch unless it is set
2638
_see_also = ['info']
2639
takes_args = ['nickname?']
2640
def run(self, nickname=None):
2641
branch = Branch.open_containing(u'.')[0]
2642
if nickname is None:
2643
self.printme(branch)
2645
branch.nick = nickname
2648
def printme(self, branch):
2652
class cmd_alias(Command):
2653
"""Set/unset and display aliases.
2656
Show the current aliases::
2660
Show the alias specified for 'll'::
2664
Set an alias for 'll'::
2666
bzr alias ll="log --line -r-10..-1"
2668
To remove an alias for 'll'::
2670
bzr alias --remove ll
2673
takes_args = ['name?']
2675
Option('remove', help='Remove the alias.'),
2678
def run(self, name=None, remove=False):
2680
self.remove_alias(name)
2682
self.print_aliases()
2684
equal_pos = name.find('=')
2686
self.print_alias(name)
2688
self.set_alias(name[:equal_pos], name[equal_pos+1:])
2690
def remove_alias(self, alias_name):
2691
if alias_name is None:
2692
raise errors.BzrCommandError(
2693
'bzr alias --remove expects an alias to remove.')
2694
# If alias is not found, print something like:
2695
# unalias: foo: not found
2696
c = config.GlobalConfig()
2697
c.unset_alias(alias_name)
2700
def print_aliases(self):
2701
"""Print out the defined aliases in a similar format to bash."""
2702
aliases = config.GlobalConfig().get_aliases()
2703
for key, value in sorted(aliases.iteritems()):
2704
self.outf.write('bzr alias %s="%s"\n' % (key, value))
2707
def print_alias(self, alias_name):
2708
from bzrlib.commands import get_alias
2709
alias = get_alias(alias_name)
2711
self.outf.write("bzr alias: %s: not found\n" % alias_name)
2714
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2716
def set_alias(self, alias_name, alias_command):
2717
"""Save the alias in the global config."""
2718
c = config.GlobalConfig()
2719
c.set_alias(alias_name, alias_command)
2722
class cmd_selftest(Command):
2723
"""Run internal test suite.
2725
If arguments are given, they are regular expressions that say which tests
2726
should run. Tests matching any expression are run, and other tests are
2729
Alternatively if --first is given, matching tests are run first and then
2730
all other tests are run. This is useful if you have been working in a
2731
particular area, but want to make sure nothing else was broken.
2733
If --exclude is given, tests that match that regular expression are
2734
excluded, regardless of whether they match --first or not.
2736
To help catch accidential dependencies between tests, the --randomize
2737
option is useful. In most cases, the argument used is the word 'now'.
2738
Note that the seed used for the random number generator is displayed
2739
when this option is used. The seed can be explicitly passed as the
2740
argument to this option if required. This enables reproduction of the
2741
actual ordering used if and when an order sensitive problem is encountered.
2743
If --list-only is given, the tests that would be run are listed. This is
2744
useful when combined with --first, --exclude and/or --randomize to
2745
understand their impact. The test harness reports "Listed nn tests in ..."
2746
instead of "Ran nn tests in ..." when list mode is enabled.
2748
If the global option '--no-plugins' is given, plugins are not loaded
2749
before running the selftests. This has two effects: features provided or
2750
modified by plugins will not be tested, and tests provided by plugins will
2753
Tests that need working space on disk use a common temporary directory,
2754
typically inside $TMPDIR or /tmp.
2757
Run only tests relating to 'ignore'::
2761
Disable plugins and list tests as they're run::
2763
bzr --no-plugins selftest -v
2765
# NB: this is used from the class without creating an instance, which is
2766
# why it does not have a self parameter.
2767
def get_transport_type(typestring):
2768
"""Parse and return a transport specifier."""
2769
if typestring == "sftp":
2770
from bzrlib.transport.sftp import SFTPAbsoluteServer
2771
return SFTPAbsoluteServer
2772
if typestring == "memory":
2773
from bzrlib.transport.memory import MemoryServer
2775
if typestring == "fakenfs":
2776
from bzrlib.transport.fakenfs import FakeNFSServer
2777
return FakeNFSServer
2778
msg = "No known transport type %s. Supported types are: sftp\n" %\
2780
raise errors.BzrCommandError(msg)
2783
takes_args = ['testspecs*']
2784
takes_options = ['verbose',
2786
help='Stop when one test fails.',
2790
help='Use a different transport by default '
2791
'throughout the test suite.',
2792
type=get_transport_type),
2794
help='Run the benchmarks rather than selftests.'),
2795
Option('lsprof-timed',
2796
help='Generate lsprof output for benchmarked'
2797
' sections of code.'),
2798
Option('cache-dir', type=str,
2799
help='Cache intermediate benchmark output in this '
2802
help='Run all tests, but run specified tests first.',
2806
help='List the tests instead of running them.'),
2807
Option('randomize', type=str, argname="SEED",
2808
help='Randomize the order of tests using the given'
2809
' seed or "now" for the current time.'),
2810
Option('exclude', type=str, argname="PATTERN",
2812
help='Exclude tests that match this regular'
2814
Option('strict', help='Fail on missing dependencies or '
2816
Option('load-list', type=str, argname='TESTLISTFILE',
2817
help='Load a test id list from a text file.'),
2818
ListOption('debugflag', type=str, short_name='E',
2819
help='Turn on a selftest debug flag.'),
2820
ListOption('starting-with', type=str, argname='TESTID',
2821
param_name='starting_with', short_name='s',
2823
'Load only the tests starting with TESTID.'),
2825
encoding_type = 'replace'
2827
def run(self, testspecs_list=None, verbose=False, one=False,
2828
transport=None, benchmark=None,
2829
lsprof_timed=None, cache_dir=None,
2830
first=False, list_only=False,
2831
randomize=None, exclude=None, strict=False,
2832
load_list=None, debugflag=None, starting_with=None):
2833
from bzrlib.tests import selftest
2834
import bzrlib.benchmarks as benchmarks
2835
from bzrlib.benchmarks import tree_creator
2837
# Make deprecation warnings visible, unless -Werror is set
2838
symbol_versioning.activate_deprecation_warnings(override=False)
2840
if cache_dir is not None:
2841
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2843
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2844
print ' %s (%s python%s)' % (
2846
bzrlib.version_string,
2847
bzrlib._format_version_tuple(sys.version_info),
2850
if testspecs_list is not None:
2851
pattern = '|'.join(testspecs_list)
2855
test_suite_factory = benchmarks.test_suite
2856
# Unless user explicitly asks for quiet, be verbose in benchmarks
2857
verbose = not is_quiet()
2858
# TODO: should possibly lock the history file...
2859
benchfile = open(".perf_history", "at", buffering=1)
2861
test_suite_factory = None
2864
result = selftest(verbose=verbose,
2866
stop_on_failure=one,
2867
transport=transport,
2868
test_suite_factory=test_suite_factory,
2869
lsprof_timed=lsprof_timed,
2870
bench_history=benchfile,
2871
matching_tests_first=first,
2872
list_only=list_only,
2873
random_seed=randomize,
2874
exclude_pattern=exclude,
2876
load_list=load_list,
2877
debug_flags=debugflag,
2878
starting_with=starting_with,
2881
if benchfile is not None:
2884
note('tests passed')
2886
note('tests failed')
2887
return int(not result)
2890
class cmd_version(Command):
2891
"""Show version of bzr."""
2893
encoding_type = 'replace'
2895
Option("short", help="Print just the version number."),
2899
def run(self, short=False):
2900
from bzrlib.version import show_version
2902
self.outf.write(bzrlib.version_string + '\n')
2904
show_version(to_file=self.outf)
2907
class cmd_rocks(Command):
2908
"""Statement of optimism."""
2914
print "It sure does!"
2917
class cmd_find_merge_base(Command):
2918
"""Find and print a base revision for merging two branches."""
2919
# TODO: Options to specify revisions on either side, as if
2920
# merging only part of the history.
2921
takes_args = ['branch', 'other']
2925
def run(self, branch, other):
2926
from bzrlib.revision import ensure_null
2928
branch1 = Branch.open_containing(branch)[0]
2929
branch2 = Branch.open_containing(other)[0]
2934
last1 = ensure_null(branch1.last_revision())
2935
last2 = ensure_null(branch2.last_revision())
2937
graph = branch1.repository.get_graph(branch2.repository)
2938
base_rev_id = graph.find_unique_lca(last1, last2)
2940
print 'merge base is revision %s' % base_rev_id
2947
class cmd_merge(Command):
2948
"""Perform a three-way merge.
2950
The source of the merge can be specified either in the form of a branch,
2951
or in the form of a path to a file containing a merge directive generated
2952
with bzr send. If neither is specified, the default is the upstream branch
2953
or the branch most recently merged using --remember.
2955
When merging a branch, by default the tip will be merged. To pick a different
2956
revision, pass --revision. If you specify two values, the first will be used as
2957
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2958
available revisions, like this is commonly referred to as "cherrypicking".
2960
Revision numbers are always relative to the branch being merged.
2962
By default, bzr will try to merge in all new work from the other
2963
branch, automatically determining an appropriate base. If this
2964
fails, you may need to give an explicit base.
2966
Merge will do its best to combine the changes in two branches, but there
2967
are some kinds of problems only a human can fix. When it encounters those,
2968
it will mark a conflict. A conflict means that you need to fix something,
2969
before you should commit.
2971
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2973
If there is no default branch set, the first merge will set it. After
2974
that, you can omit the branch to use the default. To change the
2975
default, use --remember. The value will only be saved if the remote
2976
location can be accessed.
2978
The results of the merge are placed into the destination working
2979
directory, where they can be reviewed (with bzr diff), tested, and then
2980
committed to record the result of the merge.
2982
merge refuses to run if there are any uncommitted changes, unless
2986
To merge the latest revision from bzr.dev::
2988
bzr merge ../bzr.dev
2990
To merge changes up to and including revision 82 from bzr.dev::
2992
bzr merge -r 82 ../bzr.dev
2994
To merge the changes introduced by 82, without previous changes::
2996
bzr merge -r 81..82 ../bzr.dev
2998
To apply a merge directive contained in in /tmp/merge:
3000
bzr merge /tmp/merge
3003
encoding_type = 'exact'
3004
_see_also = ['update', 'remerge', 'status-flags']
3005
takes_args = ['location?']
3010
help='Merge even if the destination tree has uncommitted changes.'),
3014
Option('show-base', help="Show base revision text in "
3016
Option('uncommitted', help='Apply uncommitted changes'
3017
' from a working copy, instead of branch changes.'),
3018
Option('pull', help='If the destination is already'
3019
' completely merged into the source, pull from the'
3020
' source rather than merging. When this happens,'
3021
' you do not need to commit the result.'),
3023
help='Branch to merge into, '
3024
'rather than the one containing the working directory.',
3028
Option('preview', help='Instead of merging, show a diff of the merge.')
3031
def run(self, location=None, revision=None, force=False,
3032
merge_type=None, show_base=False, reprocess=None, remember=False,
3033
uncommitted=False, pull=False,
3037
if merge_type is None:
3038
merge_type = _mod_merge.Merge3Merger
3040
if directory is None: directory = u'.'
3041
possible_transports = []
3043
allow_pending = True
3044
verified = 'inapplicable'
3045
tree = WorkingTree.open_containing(directory)[0]
3046
change_reporter = delta._ChangeReporter(
3047
unversioned_filter=tree.is_ignored)
3050
pb = ui.ui_factory.nested_progress_bar()
3051
cleanups.append(pb.finished)
3053
cleanups.append(tree.unlock)
3054
if location is not None:
3056
mergeable = bundle.read_mergeable_from_url(location,
3057
possible_transports=possible_transports)
3058
except errors.NotABundle:
3062
raise errors.BzrCommandError('Cannot use --uncommitted'
3063
' with bundles or merge directives.')
3065
if revision is not None:
3066
raise errors.BzrCommandError(
3067
'Cannot use -r with merge directives or bundles')
3068
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3071
if merger is None and uncommitted:
3072
if revision is not None and len(revision) > 0:
3073
raise errors.BzrCommandError('Cannot use --uncommitted and'
3074
' --revision at the same time.')
3075
location = self._select_branch_location(tree, location)[0]
3076
other_tree, other_path = WorkingTree.open_containing(location)
3077
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3079
allow_pending = False
3080
if other_path != '':
3081
merger.interesting_files = [other_path]
3084
merger, allow_pending = self._get_merger_from_branch(tree,
3085
location, revision, remember, possible_transports, pb)
3087
merger.merge_type = merge_type
3088
merger.reprocess = reprocess
3089
merger.show_base = show_base
3090
self.sanity_check_merger(merger)
3091
if (merger.base_rev_id == merger.other_rev_id and
3092
merger.other_rev_id is not None):
3093
note('Nothing to do.')
3096
if merger.interesting_files is not None:
3097
raise errors.BzrCommandError('Cannot pull individual files')
3098
if (merger.base_rev_id == tree.last_revision()):
3099
result = tree.pull(merger.other_branch, False,
3100
merger.other_rev_id)
3101
result.report(self.outf)
3103
merger.check_basis(not force)
3105
return self._do_preview(merger)
3107
return self._do_merge(merger, change_reporter, allow_pending,
3110
for cleanup in reversed(cleanups):
3113
def _do_preview(self, merger):
3114
from bzrlib.diff import show_diff_trees
3115
tree_merger = merger.make_merger()
3116
tt = tree_merger.make_preview_transform()
3118
result_tree = tt.get_preview_tree()
3119
show_diff_trees(merger.this_tree, result_tree, self.outf,
3120
old_label='', new_label='')
3124
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3125
merger.change_reporter = change_reporter
3126
conflict_count = merger.do_merge()
3128
merger.set_pending()
3129
if verified == 'failed':
3130
warning('Preview patch does not match changes')
3131
if conflict_count != 0:
3136
def sanity_check_merger(self, merger):
3137
if (merger.show_base and
3138
not merger.merge_type is _mod_merge.Merge3Merger):
3139
raise errors.BzrCommandError("Show-base is not supported for this"
3140
" merge type. %s" % merger.merge_type)
3141
if merger.reprocess is None:
3142
if merger.show_base:
3143
merger.reprocess = False
3145
# Use reprocess if the merger supports it
3146
merger.reprocess = merger.merge_type.supports_reprocess
3147
if merger.reprocess and not merger.merge_type.supports_reprocess:
3148
raise errors.BzrCommandError("Conflict reduction is not supported"
3149
" for merge type %s." %
3151
if merger.reprocess and merger.show_base:
3152
raise errors.BzrCommandError("Cannot do conflict reduction and"
3155
def _get_merger_from_branch(self, tree, location, revision, remember,
3156
possible_transports, pb):
3157
"""Produce a merger from a location, assuming it refers to a branch."""
3158
from bzrlib.tag import _merge_tags_if_possible
3159
# find the branch locations
3160
other_loc, user_location = self._select_branch_location(tree, location,
3162
if revision is not None and len(revision) == 2:
3163
base_loc, _unused = self._select_branch_location(tree,
3164
location, revision, 0)
3166
base_loc = other_loc
3168
other_branch, other_path = Branch.open_containing(other_loc,
3169
possible_transports)
3170
if base_loc == other_loc:
3171
base_branch = other_branch
3173
base_branch, base_path = Branch.open_containing(base_loc,
3174
possible_transports)
3175
# Find the revision ids
3176
if revision is None or len(revision) < 1 or revision[-1] is None:
3177
other_revision_id = _mod_revision.ensure_null(
3178
other_branch.last_revision())
3180
other_revision_id = revision[-1].as_revision_id(other_branch)
3181
if (revision is not None and len(revision) == 2
3182
and revision[0] is not None):
3183
base_revision_id = revision[0].as_revision_id(base_branch)
3185
base_revision_id = None
3186
# Remember where we merge from
3187
if ((remember or tree.branch.get_submit_branch() is None) and
3188
user_location is not None):
3189
tree.branch.set_submit_branch(other_branch.base)
3190
_merge_tags_if_possible(other_branch, tree.branch)
3191
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3192
other_revision_id, base_revision_id, other_branch, base_branch)
3193
if other_path != '':
3194
allow_pending = False
3195
merger.interesting_files = [other_path]
3197
allow_pending = True
3198
return merger, allow_pending
3200
def _select_branch_location(self, tree, user_location, revision=None,
3202
"""Select a branch location, according to possible inputs.
3204
If provided, branches from ``revision`` are preferred. (Both
3205
``revision`` and ``index`` must be supplied.)
3207
Otherwise, the ``location`` parameter is used. If it is None, then the
3208
``submit`` or ``parent`` location is used, and a note is printed.
3210
:param tree: The working tree to select a branch for merging into
3211
:param location: The location entered by the user
3212
:param revision: The revision parameter to the command
3213
:param index: The index to use for the revision parameter. Negative
3214
indices are permitted.
3215
:return: (selected_location, user_location). The default location
3216
will be the user-entered location.
3218
if (revision is not None and index is not None
3219
and revision[index] is not None):
3220
branch = revision[index].get_branch()
3221
if branch is not None:
3222
return branch, branch
3223
if user_location is None:
3224
location = self._get_remembered(tree, 'Merging from')
3226
location = user_location
3227
return location, user_location
3229
def _get_remembered(self, tree, verb_string):
3230
"""Use tree.branch's parent if none was supplied.
3232
Report if the remembered location was used.
3234
stored_location = tree.branch.get_submit_branch()
3235
stored_location_type = "submit"
3236
if stored_location is None:
3237
stored_location = tree.branch.get_parent()
3238
stored_location_type = "parent"
3239
mutter("%s", stored_location)
3240
if stored_location is None:
3241
raise errors.BzrCommandError("No location specified or remembered")
3242
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3243
note(u"%s remembered %s location %s", verb_string,
3244
stored_location_type, display_url)
3245
return stored_location
3248
class cmd_remerge(Command):
3251
Use this if you want to try a different merge technique while resolving
3252
conflicts. Some merge techniques are better than others, and remerge
3253
lets you try different ones on different files.
3255
The options for remerge have the same meaning and defaults as the ones for
3256
merge. The difference is that remerge can (only) be run when there is a
3257
pending merge, and it lets you specify particular files.
3260
Re-do the merge of all conflicted files, and show the base text in
3261
conflict regions, in addition to the usual THIS and OTHER texts::
3263
bzr remerge --show-base
3265
Re-do the merge of "foobar", using the weave merge algorithm, with
3266
additional processing to reduce the size of conflict regions::
3268
bzr remerge --merge-type weave --reprocess foobar
3270
takes_args = ['file*']
3275
help="Show base revision text in conflicts."),
3278
def run(self, file_list=None, merge_type=None, show_base=False,
3280
if merge_type is None:
3281
merge_type = _mod_merge.Merge3Merger
3282
tree, file_list = tree_files(file_list)
3285
parents = tree.get_parent_ids()
3286
if len(parents) != 2:
3287
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3288
" merges. Not cherrypicking or"
3290
repository = tree.branch.repository
3291
interesting_ids = None
3293
conflicts = tree.conflicts()
3294
if file_list is not None:
3295
interesting_ids = set()
3296
for filename in file_list:
3297
file_id = tree.path2id(filename)
3299
raise errors.NotVersionedError(filename)
3300
interesting_ids.add(file_id)
3301
if tree.kind(file_id) != "directory":
3304
for name, ie in tree.inventory.iter_entries(file_id):
3305
interesting_ids.add(ie.file_id)
3306
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3308
# Remerge only supports resolving contents conflicts
3309
allowed_conflicts = ('text conflict', 'contents conflict')
3310
restore_files = [c.path for c in conflicts
3311
if c.typestring in allowed_conflicts]
3312
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3313
tree.set_conflicts(ConflictList(new_conflicts))
3314
if file_list is not None:
3315
restore_files = file_list
3316
for filename in restore_files:
3318
restore(tree.abspath(filename))
3319
except errors.NotConflicted:
3321
# Disable pending merges, because the file texts we are remerging
3322
# have not had those merges performed. If we use the wrong parents
3323
# list, we imply that the working tree text has seen and rejected
3324
# all the changes from the other tree, when in fact those changes
3325
# have not yet been seen.
3326
pb = ui.ui_factory.nested_progress_bar()
3327
tree.set_parent_ids(parents[:1])
3329
merger = _mod_merge.Merger.from_revision_ids(pb,
3331
merger.interesting_ids = interesting_ids
3332
merger.merge_type = merge_type
3333
merger.show_base = show_base
3334
merger.reprocess = reprocess
3335
conflicts = merger.do_merge()
3337
tree.set_parent_ids(parents)
3347
class cmd_revert(Command):
3348
"""Revert files to a previous revision.
3350
Giving a list of files will revert only those files. Otherwise, all files
3351
will be reverted. If the revision is not specified with '--revision', the
3352
last committed revision is used.
3354
To remove only some changes, without reverting to a prior version, use
3355
merge instead. For example, "merge . --revision -2..-3" will remove the
3356
changes introduced by -2, without affecting the changes introduced by -1.
3357
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3359
By default, any files that have been manually changed will be backed up
3360
first. (Files changed only by merge are not backed up.) Backup files have
3361
'.~#~' appended to their name, where # is a number.
3363
When you provide files, you can use their current pathname or the pathname
3364
from the target revision. So you can use revert to "undelete" a file by
3365
name. If you name a directory, all the contents of that directory will be
3368
Any files that have been newly added since that revision will be deleted,
3369
with a backup kept if appropriate. Directories containing unknown files
3370
will not be deleted.
3372
The working tree contains a list of pending merged revisions, which will
3373
be included as parents in the next commit. Normally, revert clears that
3374
list as well as reverting the files. If any files are specified, revert
3375
leaves the pending merge list alone and reverts only the files. Use "bzr
3376
revert ." in the tree root to revert all files but keep the merge record,
3377
and "bzr revert --forget-merges" to clear the pending merge list without
3378
reverting any files.
3381
_see_also = ['cat', 'export']
3384
Option('no-backup', "Do not save backups of reverted files."),
3385
Option('forget-merges',
3386
'Remove pending merge marker, without changing any files.'),
3388
takes_args = ['file*']
3390
def run(self, revision=None, no_backup=False, file_list=None,
3391
forget_merges=None):
3392
tree, file_list = tree_files(file_list)
3396
tree.set_parent_ids(tree.get_parent_ids()[:1])
3398
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3403
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3404
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3405
pb = ui.ui_factory.nested_progress_bar()
3407
tree.revert(file_list, rev_tree, not no_backup, pb,
3408
report_changes=True)
3413
class cmd_assert_fail(Command):
3414
"""Test reporting of assertion failures"""
3415
# intended just for use in testing
3420
raise AssertionError("always fails")
3423
class cmd_help(Command):
3424
"""Show help on a command or other topic.
3427
_see_also = ['topics']
3429
Option('long', 'Show help on all commands.'),
3431
takes_args = ['topic?']
3432
aliases = ['?', '--help', '-?', '-h']
3435
def run(self, topic=None, long=False):
3437
if topic is None and long:
3439
bzrlib.help.help(topic)
3442
class cmd_shell_complete(Command):
3443
"""Show appropriate completions for context.
3445
For a list of all available commands, say 'bzr shell-complete'.
3447
takes_args = ['context?']
3452
def run(self, context=None):
3453
import shellcomplete
3454
shellcomplete.shellcomplete(context)
3457
class cmd_missing(Command):
3458
"""Show unmerged/unpulled revisions between two branches.
3460
OTHER_BRANCH may be local or remote.
3463
_see_also = ['merge', 'pull']
3464
takes_args = ['other_branch?']
3466
Option('reverse', 'Reverse the order of revisions.'),
3468
'Display changes in the local branch only.'),
3469
Option('this' , 'Same as --mine-only.'),
3470
Option('theirs-only',
3471
'Display changes in the remote branch only.'),
3472
Option('other', 'Same as --theirs-only.'),
3476
custom_help('revision',
3477
help='Filter on local branch revisions (inclusive). '
3478
'See "help revisionspec" for details.'),
3479
Option('other-revision',
3480
type=_parse_revision_str,
3482
help='Filter on other branch revisions (inclusive). '
3483
'See "help revisionspec" for details.'),
3484
Option('include-merges', 'Show merged revisions.'),
3486
encoding_type = 'replace'
3489
def run(self, other_branch=None, reverse=False, mine_only=False,
3491
log_format=None, long=False, short=False, line=False,
3492
show_ids=False, verbose=False, this=False, other=False,
3493
include_merges=False, revision=None, other_revision=None):
3494
from bzrlib.missing import find_unmerged, iter_log_revisions
3503
# TODO: We should probably check that we don't have mine-only and
3504
# theirs-only set, but it gets complicated because we also have
3505
# this and other which could be used.
3512
local_branch = Branch.open_containing(u".")[0]
3513
parent = local_branch.get_parent()
3514
if other_branch is None:
3515
other_branch = parent
3516
if other_branch is None:
3517
raise errors.BzrCommandError("No peer location known"
3519
display_url = urlutils.unescape_for_display(parent,
3521
message("Using saved parent location: "
3522
+ display_url + "\n")
3524
remote_branch = Branch.open(other_branch)
3525
if remote_branch.base == local_branch.base:
3526
remote_branch = local_branch
3528
local_revid_range = _revision_range_to_revid_range(
3529
_get_revision_range(revision, local_branch,
3532
remote_revid_range = _revision_range_to_revid_range(
3533
_get_revision_range(other_revision,
3534
remote_branch, self.name()))
3536
local_branch.lock_read()
3538
remote_branch.lock_read()
3540
local_extra, remote_extra = find_unmerged(
3541
local_branch, remote_branch, restrict,
3542
backward=not reverse,
3543
include_merges=include_merges,
3544
local_revid_range=local_revid_range,
3545
remote_revid_range=remote_revid_range)
3547
if log_format is None:
3548
registry = log.log_formatter_registry
3549
log_format = registry.get_default(local_branch)
3550
lf = log_format(to_file=self.outf,
3552
show_timezone='original')
3555
if local_extra and not theirs_only:
3556
message("You have %d extra revision(s):\n" %
3558
for revision in iter_log_revisions(local_extra,
3559
local_branch.repository,
3561
lf.log_revision(revision)
3562
printed_local = True
3565
printed_local = False
3567
if remote_extra and not mine_only:
3568
if printed_local is True:
3570
message("You are missing %d revision(s):\n" %
3572
for revision in iter_log_revisions(remote_extra,
3573
remote_branch.repository,
3575
lf.log_revision(revision)
3578
if mine_only and not local_extra:
3579
# We checked local, and found nothing extra
3580
message('This branch is up to date.\n')
3581
elif theirs_only and not remote_extra:
3582
# We checked remote, and found nothing extra
3583
message('Other branch is up to date.\n')
3584
elif not (mine_only or theirs_only or local_extra or
3586
# We checked both branches, and neither one had extra
3588
message("Branches are up to date.\n")
3590
remote_branch.unlock()
3592
local_branch.unlock()
3593
if not status_code and parent is None and other_branch is not None:
3594
local_branch.lock_write()
3596
# handle race conditions - a parent might be set while we run.
3597
if local_branch.get_parent() is None:
3598
local_branch.set_parent(remote_branch.base)
3600
local_branch.unlock()
3604
class cmd_pack(Command):
3605
"""Compress the data within a repository."""
3607
_see_also = ['repositories']
3608
takes_args = ['branch_or_repo?']
3610
def run(self, branch_or_repo='.'):
3611
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3613
branch = dir.open_branch()
3614
repository = branch.repository
3615
except errors.NotBranchError:
3616
repository = dir.open_repository()
3620
class cmd_plugins(Command):
3621
"""List the installed plugins.
3623
This command displays the list of installed plugins including
3624
version of plugin and a short description of each.
3626
--verbose shows the path where each plugin is located.
3628
A plugin is an external component for Bazaar that extends the
3629
revision control system, by adding or replacing code in Bazaar.
3630
Plugins can do a variety of things, including overriding commands,
3631
adding new commands, providing additional network transports and
3632
customizing log output.
3634
See the Bazaar web site, http://bazaar-vcs.org, for further
3635
information on plugins including where to find them and how to
3636
install them. Instructions are also provided there on how to
3637
write new plugins using the Python programming language.
3639
takes_options = ['verbose']
3642
def run(self, verbose=False):
3643
import bzrlib.plugin
3644
from inspect import getdoc
3646
for name, plugin in bzrlib.plugin.plugins().items():
3647
version = plugin.__version__
3648
if version == 'unknown':
3650
name_ver = '%s %s' % (name, version)
3651
d = getdoc(plugin.module)
3653
doc = d.split('\n')[0]
3655
doc = '(no description)'
3656
result.append((name_ver, doc, plugin.path()))
3657
for name_ver, doc, path in sorted(result):
3665
class cmd_testament(Command):
3666
"""Show testament (signing-form) of a revision."""
3669
Option('long', help='Produce long-format testament.'),
3671
help='Produce a strict-format testament.')]
3672
takes_args = ['branch?']
3674
def run(self, branch=u'.', revision=None, long=False, strict=False):
3675
from bzrlib.testament import Testament, StrictTestament
3677
testament_class = StrictTestament
3679
testament_class = Testament
3681
b = Branch.open_containing(branch)[0]
3683
b = Branch.open(branch)
3686
if revision is None:
3687
rev_id = b.last_revision()
3689
rev_id = revision[0].as_revision_id(b)
3690
t = testament_class.from_revision(b.repository, rev_id)
3692
sys.stdout.writelines(t.as_text_lines())
3694
sys.stdout.write(t.as_short_text())
3699
class cmd_annotate(Command):
3700
"""Show the origin of each line in a file.
3702
This prints out the given file with an annotation on the left side
3703
indicating which revision, author and date introduced the change.
3705
If the origin is the same for a run of consecutive lines, it is
3706
shown only at the top, unless the --all option is given.
3708
# TODO: annotate directories; showing when each file was last changed
3709
# TODO: if the working copy is modified, show annotations on that
3710
# with new uncommitted lines marked
3711
aliases = ['ann', 'blame', 'praise']
3712
takes_args = ['filename']
3713
takes_options = [Option('all', help='Show annotations on all lines.'),
3714
Option('long', help='Show commit date in annotations.'),
3718
encoding_type = 'exact'
3721
def run(self, filename, all=False, long=False, revision=None,
3723
from bzrlib.annotate import annotate_file, annotate_file_tree
3724
wt, branch, relpath = \
3725
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3731
tree = _get_one_revision_tree('annotate', revision, branch=branch)
3733
file_id = wt.path2id(relpath)
3735
file_id = tree.path2id(relpath)
3737
raise errors.NotVersionedError(filename)
3738
file_version = tree.inventory[file_id].revision
3739
if wt is not None and revision is None:
3740
# If there is a tree and we're not annotating historical
3741
# versions, annotate the working tree's content.
3742
annotate_file_tree(wt, file_id, self.outf, long, all,
3745
annotate_file(branch, file_version, file_id, long, all, self.outf,
3754
class cmd_re_sign(Command):
3755
"""Create a digital signature for an existing revision."""
3756
# TODO be able to replace existing ones.
3758
hidden = True # is this right ?
3759
takes_args = ['revision_id*']
3760
takes_options = ['revision']
3762
def run(self, revision_id_list=None, revision=None):
3763
if revision_id_list is not None and revision is not None:
3764
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3765
if revision_id_list is None and revision is None:
3766
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3767
b = WorkingTree.open_containing(u'.')[0].branch
3770
return self._run(b, revision_id_list, revision)
3774
def _run(self, b, revision_id_list, revision):
3775
import bzrlib.gpg as gpg
3776
gpg_strategy = gpg.GPGStrategy(b.get_config())
3777
if revision_id_list is not None:
3778
b.repository.start_write_group()
3780
for revision_id in revision_id_list:
3781
b.repository.sign_revision(revision_id, gpg_strategy)
3783
b.repository.abort_write_group()
3786
b.repository.commit_write_group()
3787
elif revision is not None:
3788
if len(revision) == 1:
3789
revno, rev_id = revision[0].in_history(b)
3790
b.repository.start_write_group()
3792
b.repository.sign_revision(rev_id, gpg_strategy)
3794
b.repository.abort_write_group()
3797
b.repository.commit_write_group()
3798
elif len(revision) == 2:
3799
# are they both on rh- if so we can walk between them
3800
# might be nice to have a range helper for arbitrary
3801
# revision paths. hmm.
3802
from_revno, from_revid = revision[0].in_history(b)
3803
to_revno, to_revid = revision[1].in_history(b)
3804
if to_revid is None:
3805
to_revno = b.revno()
3806
if from_revno is None or to_revno is None:
3807
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3808
b.repository.start_write_group()
3810
for revno in range(from_revno, to_revno + 1):
3811
b.repository.sign_revision(b.get_rev_id(revno),
3814
b.repository.abort_write_group()
3817
b.repository.commit_write_group()
3819
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3822
class cmd_bind(Command):
3823
"""Convert the current branch into a checkout of the supplied branch.
3825
Once converted into a checkout, commits must succeed on the master branch
3826
before they will be applied to the local branch.
3828
Bound branches use the nickname of its master branch unless it is set
3829
locally, in which case binding will update the the local nickname to be
3833
_see_also = ['checkouts', 'unbind']
3834
takes_args = ['location?']
3837
def run(self, location=None):
3838
b, relpath = Branch.open_containing(u'.')
3839
if location is None:
3841
location = b.get_old_bound_location()
3842
except errors.UpgradeRequired:
3843
raise errors.BzrCommandError('No location supplied. '
3844
'This format does not remember old locations.')
3846
if location is None:
3847
raise errors.BzrCommandError('No location supplied and no '
3848
'previous location known')
3849
b_other = Branch.open(location)
3852
except errors.DivergedBranches:
3853
raise errors.BzrCommandError('These branches have diverged.'
3854
' Try merging, and then bind again.')
3855
if b.get_config().has_explicit_nickname():
3856
b.nick = b_other.nick
3859
class cmd_unbind(Command):
3860
"""Convert the current checkout into a regular branch.
3862
After unbinding, the local branch is considered independent and subsequent
3863
commits will be local only.
3866
_see_also = ['checkouts', 'bind']
3871
b, relpath = Branch.open_containing(u'.')
3873
raise errors.BzrCommandError('Local branch is not bound')
3876
class cmd_uncommit(Command):
3877
"""Remove the last committed revision.
3879
--verbose will print out what is being removed.
3880
--dry-run will go through all the motions, but not actually
3883
If --revision is specified, uncommit revisions to leave the branch at the
3884
specified revision. For example, "bzr uncommit -r 15" will leave the
3885
branch at revision 15.
3887
Uncommit leaves the working tree ready for a new commit. The only change
3888
it may make is to restore any pending merges that were present before
3892
# TODO: jam 20060108 Add an option to allow uncommit to remove
3893
# unreferenced information in 'branch-as-repository' branches.
3894
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3895
# information in shared branches as well.
3896
_see_also = ['commit']
3897
takes_options = ['verbose', 'revision',
3898
Option('dry-run', help='Don\'t actually make changes.'),
3899
Option('force', help='Say yes to all questions.'),
3901
help="Only remove the commits from the local branch"
3902
" when in a checkout."
3905
takes_args = ['location?']
3907
encoding_type = 'replace'
3909
def run(self, location=None,
3910
dry_run=False, verbose=False,
3911
revision=None, force=False, local=False):
3912
if location is None:
3914
control, relpath = bzrdir.BzrDir.open_containing(location)
3916
tree = control.open_workingtree()
3918
except (errors.NoWorkingTree, errors.NotLocalUrl):
3920
b = control.open_branch()
3922
if tree is not None:
3927
return self._run(b, tree, dry_run, verbose, revision, force,
3930
if tree is not None:
3935
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3936
from bzrlib.log import log_formatter, show_log
3937
from bzrlib.uncommit import uncommit
3939
last_revno, last_rev_id = b.last_revision_info()
3942
if revision is None:
3944
rev_id = last_rev_id
3946
# 'bzr uncommit -r 10' actually means uncommit
3947
# so that the final tree is at revno 10.
3948
# but bzrlib.uncommit.uncommit() actually uncommits
3949
# the revisions that are supplied.
3950
# So we need to offset it by one
3951
revno = revision[0].in_history(b).revno + 1
3952
if revno <= last_revno:
3953
rev_id = b.get_rev_id(revno)
3955
if rev_id is None or _mod_revision.is_null(rev_id):
3956
self.outf.write('No revisions to uncommit.\n')
3959
lf = log_formatter('short',
3961
show_timezone='original')
3966
direction='forward',
3967
start_revision=revno,
3968
end_revision=last_revno)
3971
print 'Dry-run, pretending to remove the above revisions.'
3973
val = raw_input('Press <enter> to continue')
3975
print 'The above revision(s) will be removed.'
3977
val = raw_input('Are you sure [y/N]? ')
3978
if val.lower() not in ('y', 'yes'):
3982
mutter('Uncommitting from {%s} to {%s}',
3983
last_rev_id, rev_id)
3984
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3985
revno=revno, local=local)
3986
note('You can restore the old tip by running:\n'
3987
' bzr pull . -r revid:%s', last_rev_id)
3990
class cmd_break_lock(Command):
3991
"""Break a dead lock on a repository, branch or working directory.
3993
CAUTION: Locks should only be broken when you are sure that the process
3994
holding the lock has been stopped.
3996
You can get information on what locks are open via the 'bzr info' command.
4001
takes_args = ['location?']
4003
def run(self, location=None, show=False):
4004
if location is None:
4006
control, relpath = bzrdir.BzrDir.open_containing(location)
4008
control.break_lock()
4009
except NotImplementedError:
4013
class cmd_wait_until_signalled(Command):
4014
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4016
This just prints a line to signal when it is ready, then blocks on stdin.
4022
sys.stdout.write("running\n")
4024
sys.stdin.readline()
4027
class cmd_serve(Command):
4028
"""Run the bzr server."""
4030
aliases = ['server']
4034
help='Serve on stdin/out for use from inetd or sshd.'),
4036
help='Listen for connections on nominated port of the form '
4037
'[hostname:]portnumber. Passing 0 as the port number will '
4038
'result in a dynamically allocated port. The default port is '
4042
help='Serve contents of this directory.',
4044
Option('allow-writes',
4045
help='By default the server is a readonly server. Supplying '
4046
'--allow-writes enables write access to the contents of '
4047
'the served directory and below.'
4051
def run(self, port=None, inet=False, directory=None, allow_writes=False):
4052
from bzrlib import lockdir
4053
from bzrlib.smart import medium, server
4054
from bzrlib.transport import get_transport
4055
from bzrlib.transport.chroot import ChrootServer
4056
if directory is None:
4057
directory = os.getcwd()
4058
url = urlutils.local_path_to_url(directory)
4059
if not allow_writes:
4060
url = 'readonly+' + url
4061
chroot_server = ChrootServer(get_transport(url))
4062
chroot_server.setUp()
4063
t = get_transport(chroot_server.get_url())
4065
smart_server = medium.SmartServerPipeStreamMedium(
4066
sys.stdin, sys.stdout, t)
4068
host = medium.BZR_DEFAULT_INTERFACE
4070
port = medium.BZR_DEFAULT_PORT
4073
host, port = port.split(':')
4075
smart_server = server.SmartTCPServer(t, host=host, port=port)
4076
print 'listening on port: ', smart_server.port
4078
# for the duration of this server, no UI output is permitted.
4079
# note that this may cause problems with blackbox tests. This should
4080
# be changed with care though, as we dont want to use bandwidth sending
4081
# progress over stderr to smart server clients!
4082
old_factory = ui.ui_factory
4083
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4085
ui.ui_factory = ui.SilentUIFactory()
4086
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4087
smart_server.serve()
4089
ui.ui_factory = old_factory
4090
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4093
class cmd_join(Command):
4094
"""Combine a subtree into its containing tree.
4096
This command is for experimental use only. It requires the target tree
4097
to be in dirstate-with-subtree format, which cannot be converted into
4100
The TREE argument should be an independent tree, inside another tree, but
4101
not part of it. (Such trees can be produced by "bzr split", but also by
4102
running "bzr branch" with the target inside a tree.)
4104
The result is a combined tree, with the subtree no longer an independant
4105
part. This is marked as a merge of the subtree into the containing tree,
4106
and all history is preserved.
4108
If --reference is specified, the subtree retains its independence. It can
4109
be branched by itself, and can be part of multiple projects at the same
4110
time. But operations performed in the containing tree, such as commit
4111
and merge, will recurse into the subtree.
4114
_see_also = ['split']
4115
takes_args = ['tree']
4117
Option('reference', help='Join by reference.'),
4121
def run(self, tree, reference=False):
4122
sub_tree = WorkingTree.open(tree)
4123
parent_dir = osutils.dirname(sub_tree.basedir)
4124
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4125
repo = containing_tree.branch.repository
4126
if not repo.supports_rich_root():
4127
raise errors.BzrCommandError(
4128
"Can't join trees because %s doesn't support rich root data.\n"
4129
"You can use bzr upgrade on the repository."
4133
containing_tree.add_reference(sub_tree)
4134
except errors.BadReferenceTarget, e:
4135
# XXX: Would be better to just raise a nicely printable
4136
# exception from the real origin. Also below. mbp 20070306
4137
raise errors.BzrCommandError("Cannot join %s. %s" %
4141
containing_tree.subsume(sub_tree)
4142
except errors.BadSubsumeSource, e:
4143
raise errors.BzrCommandError("Cannot join %s. %s" %
4147
class cmd_split(Command):
4148
"""Split a subdirectory of a tree into a separate tree.
4150
This command will produce a target tree in a format that supports
4151
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4152
converted into earlier formats like 'dirstate-tags'.
4154
The TREE argument should be a subdirectory of a working tree. That
4155
subdirectory will be converted into an independent tree, with its own
4156
branch. Commits in the top-level tree will not apply to the new subtree.
4159
# join is not un-hidden yet
4160
#_see_also = ['join']
4161
takes_args = ['tree']
4163
def run(self, tree):
4164
containing_tree, subdir = WorkingTree.open_containing(tree)
4165
sub_id = containing_tree.path2id(subdir)
4167
raise errors.NotVersionedError(subdir)
4169
containing_tree.extract(sub_id)
4170
except errors.RootNotRich:
4171
raise errors.UpgradeRequired(containing_tree.branch.base)
4174
class cmd_merge_directive(Command):
4175
"""Generate a merge directive for auto-merge tools.
4177
A directive requests a merge to be performed, and also provides all the
4178
information necessary to do so. This means it must either include a
4179
revision bundle, or the location of a branch containing the desired
4182
A submit branch (the location to merge into) must be supplied the first
4183
time the command is issued. After it has been supplied once, it will
4184
be remembered as the default.
4186
A public branch is optional if a revision bundle is supplied, but required
4187
if --diff or --plain is specified. It will be remembered as the default
4188
after the first use.
4191
takes_args = ['submit_branch?', 'public_branch?']
4195
_see_also = ['send']
4198
RegistryOption.from_kwargs('patch-type',
4199
'The type of patch to include in the directive.',
4201
value_switches=True,
4203
bundle='Bazaar revision bundle (default).',
4204
diff='Normal unified diff.',
4205
plain='No patch, just directive.'),
4206
Option('sign', help='GPG-sign the directive.'), 'revision',
4207
Option('mail-to', type=str,
4208
help='Instead of printing the directive, email to this address.'),
4209
Option('message', type=str, short_name='m',
4210
help='Message to use when committing this merge.')
4213
encoding_type = 'exact'
4215
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4216
sign=False, revision=None, mail_to=None, message=None):
4217
from bzrlib.revision import ensure_null, NULL_REVISION
4218
include_patch, include_bundle = {
4219
'plain': (False, False),
4220
'diff': (True, False),
4221
'bundle': (True, True),
4223
branch = Branch.open('.')
4224
stored_submit_branch = branch.get_submit_branch()
4225
if submit_branch is None:
4226
submit_branch = stored_submit_branch
4228
if stored_submit_branch is None:
4229
branch.set_submit_branch(submit_branch)
4230
if submit_branch is None:
4231
submit_branch = branch.get_parent()
4232
if submit_branch is None:
4233
raise errors.BzrCommandError('No submit branch specified or known')
4235
stored_public_branch = branch.get_public_branch()
4236
if public_branch is None:
4237
public_branch = stored_public_branch
4238
elif stored_public_branch is None:
4239
branch.set_public_branch(public_branch)
4240
if not include_bundle and public_branch is None:
4241
raise errors.BzrCommandError('No public branch specified or'
4243
base_revision_id = None
4244
if revision is not None:
4245
if len(revision) > 2:
4246
raise errors.BzrCommandError('bzr merge-directive takes '
4247
'at most two one revision identifiers')
4248
revision_id = revision[-1].as_revision_id(branch)
4249
if len(revision) == 2:
4250
base_revision_id = revision[0].as_revision_id(branch)
4252
revision_id = branch.last_revision()
4253
revision_id = ensure_null(revision_id)
4254
if revision_id == NULL_REVISION:
4255
raise errors.BzrCommandError('No revisions to bundle.')
4256
directive = merge_directive.MergeDirective2.from_objects(
4257
branch.repository, revision_id, time.time(),
4258
osutils.local_time_offset(), submit_branch,
4259
public_branch=public_branch, include_patch=include_patch,
4260
include_bundle=include_bundle, message=message,
4261
base_revision_id=base_revision_id)
4264
self.outf.write(directive.to_signed(branch))
4266
self.outf.writelines(directive.to_lines())
4268
message = directive.to_email(mail_to, branch, sign)
4269
s = SMTPConnection(branch.get_config())
4270
s.send_email(message)
4273
class cmd_send(Command):
4274
"""Mail or create a merge-directive for submitting changes.
4276
A merge directive provides many things needed for requesting merges:
4278
* A machine-readable description of the merge to perform
4280
* An optional patch that is a preview of the changes requested
4282
* An optional bundle of revision data, so that the changes can be applied
4283
directly from the merge directive, without retrieving data from a
4286
If --no-bundle is specified, then public_branch is needed (and must be
4287
up-to-date), so that the receiver can perform the merge using the
4288
public_branch. The public_branch is always included if known, so that
4289
people can check it later.
4291
The submit branch defaults to the parent, but can be overridden. Both
4292
submit branch and public branch will be remembered if supplied.
4294
If a public_branch is known for the submit_branch, that public submit
4295
branch is used in the merge instructions. This means that a local mirror
4296
can be used as your actual submit branch, once you have set public_branch
4299
Mail is sent using your preferred mail program. This should be transparent
4300
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4301
If the preferred client can't be found (or used), your editor will be used.
4303
To use a specific mail program, set the mail_client configuration option.
4304
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4305
specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4306
generic options are "default", "editor", "emacsclient", "mapi", and
4307
"xdg-email". Plugins may also add supported clients.
4309
If mail is being sent, a to address is required. This can be supplied
4310
either on the commandline, by setting the submit_to configuration
4311
option in the branch itself or the child_submit_to configuration option
4312
in the submit branch.
4314
Two formats are currently supported: "4" uses revision bundle format 4 and
4315
merge directive format 2. It is significantly faster and smaller than
4316
older formats. It is compatible with Bazaar 0.19 and later. It is the
4317
default. "0.9" uses revision bundle format 0.9 and merge directive
4318
format 1. It is compatible with Bazaar 0.12 - 0.18.
4320
Merge directives are applied using the merge command or the pull command.
4323
encoding_type = 'exact'
4325
_see_also = ['merge', 'pull']
4327
takes_args = ['submit_branch?', 'public_branch?']
4331
help='Do not include a bundle in the merge directive.'),
4332
Option('no-patch', help='Do not include a preview patch in the merge'
4335
help='Remember submit and public branch.'),
4337
help='Branch to generate the submission from, '
4338
'rather than the one containing the working directory.',
4341
Option('output', short_name='o',
4342
help='Write merge directive to this file; '
4343
'use - for stdout.',
4345
Option('mail-to', help='Mail the request to this address.',
4349
RegistryOption.from_kwargs('format',
4350
'Use the specified output format.',
4351
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4352
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4355
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4356
no_patch=False, revision=None, remember=False, output=None,
4357
format='4', mail_to=None, message=None, **kwargs):
4358
return self._run(submit_branch, revision, public_branch, remember,
4359
format, no_bundle, no_patch, output,
4360
kwargs.get('from', '.'), mail_to, message)
4362
def _run(self, submit_branch, revision, public_branch, remember, format,
4363
no_bundle, no_patch, output, from_, mail_to, message):
4364
from bzrlib.revision import NULL_REVISION
4365
branch = Branch.open_containing(from_)[0]
4367
outfile = cStringIO.StringIO()
4371
outfile = open(output, 'wb')
4372
# we may need to write data into branch's repository to calculate
4377
config = branch.get_config()
4379
mail_to = config.get_user_option('submit_to')
4380
mail_client = config.get_mail_client()
4381
if remember and submit_branch is None:
4382
raise errors.BzrCommandError(
4383
'--remember requires a branch to be specified.')
4384
stored_submit_branch = branch.get_submit_branch()
4385
remembered_submit_branch = None
4386
if submit_branch is None:
4387
submit_branch = stored_submit_branch
4388
remembered_submit_branch = "submit"
4390
if stored_submit_branch is None or remember:
4391
branch.set_submit_branch(submit_branch)
4392
if submit_branch is None:
4393
submit_branch = branch.get_parent()
4394
remembered_submit_branch = "parent"
4395
if submit_branch is None:
4396
raise errors.BzrCommandError('No submit branch known or'
4398
if remembered_submit_branch is not None:
4399
note('Using saved %s location "%s" to determine what '
4400
'changes to submit.', remembered_submit_branch,
4404
submit_config = Branch.open(submit_branch).get_config()
4405
mail_to = submit_config.get_user_option("child_submit_to")
4407
stored_public_branch = branch.get_public_branch()
4408
if public_branch is None:
4409
public_branch = stored_public_branch
4410
elif stored_public_branch is None or remember:
4411
branch.set_public_branch(public_branch)
4412
if no_bundle and public_branch is None:
4413
raise errors.BzrCommandError('No public branch specified or'
4415
base_revision_id = None
4417
if revision is not None:
4418
if len(revision) > 2:
4419
raise errors.BzrCommandError('bzr send takes '
4420
'at most two one revision identifiers')
4421
revision_id = revision[-1].as_revision_id(branch)
4422
if len(revision) == 2:
4423
base_revision_id = revision[0].as_revision_id(branch)
4424
if revision_id is None:
4425
revision_id = branch.last_revision()
4426
if revision_id == NULL_REVISION:
4427
raise errors.BzrCommandError('No revisions to submit.')
4429
directive = merge_directive.MergeDirective2.from_objects(
4430
branch.repository, revision_id, time.time(),
4431
osutils.local_time_offset(), submit_branch,
4432
public_branch=public_branch, include_patch=not no_patch,
4433
include_bundle=not no_bundle, message=message,
4434
base_revision_id=base_revision_id)
4435
elif format == '0.9':
4438
patch_type = 'bundle'
4440
raise errors.BzrCommandError('Format 0.9 does not'
4441
' permit bundle with no patch')
4447
directive = merge_directive.MergeDirective.from_objects(
4448
branch.repository, revision_id, time.time(),
4449
osutils.local_time_offset(), submit_branch,
4450
public_branch=public_branch, patch_type=patch_type,
4453
outfile.writelines(directive.to_lines())
4455
subject = '[MERGE] '
4456
if message is not None:
4459
revision = branch.repository.get_revision(revision_id)
4460
subject += revision.get_summary()
4461
basename = directive.get_disk_name(branch)
4462
mail_client.compose_merge_request(mail_to, subject,
4463
outfile.getvalue(), basename)
4470
class cmd_bundle_revisions(cmd_send):
4472
"""Create a merge-directive for submitting changes.
4474
A merge directive provides many things needed for requesting merges:
4476
* A machine-readable description of the merge to perform
4478
* An optional patch that is a preview of the changes requested
4480
* An optional bundle of revision data, so that the changes can be applied
4481
directly from the merge directive, without retrieving data from a
4484
If --no-bundle is specified, then public_branch is needed (and must be
4485
up-to-date), so that the receiver can perform the merge using the
4486
public_branch. The public_branch is always included if known, so that
4487
people can check it later.
4489
The submit branch defaults to the parent, but can be overridden. Both
4490
submit branch and public branch will be remembered if supplied.
4492
If a public_branch is known for the submit_branch, that public submit
4493
branch is used in the merge instructions. This means that a local mirror
4494
can be used as your actual submit branch, once you have set public_branch
4497
Two formats are currently supported: "4" uses revision bundle format 4 and
4498
merge directive format 2. It is significantly faster and smaller than
4499
older formats. It is compatible with Bazaar 0.19 and later. It is the
4500
default. "0.9" uses revision bundle format 0.9 and merge directive
4501
format 1. It is compatible with Bazaar 0.12 - 0.18.
4506
help='Do not include a bundle in the merge directive.'),
4507
Option('no-patch', help='Do not include a preview patch in the merge'
4510
help='Remember submit and public branch.'),
4512
help='Branch to generate the submission from, '
4513
'rather than the one containing the working directory.',
4516
Option('output', short_name='o', help='Write directive to this file.',
4519
RegistryOption.from_kwargs('format',
4520
'Use the specified output format.',
4521
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4522
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4524
aliases = ['bundle']
4526
_see_also = ['send', 'merge']
4530
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4531
no_patch=False, revision=None, remember=False, output=None,
4532
format='4', **kwargs):
4535
return self._run(submit_branch, revision, public_branch, remember,
4536
format, no_bundle, no_patch, output,
4537
kwargs.get('from', '.'), None, None)
4540
class cmd_tag(Command):
4541
"""Create, remove or modify a tag naming a revision.
4543
Tags give human-meaningful names to revisions. Commands that take a -r
4544
(--revision) option can be given -rtag:X, where X is any previously
4547
Tags are stored in the branch. Tags are copied from one branch to another
4548
along when you branch, push, pull or merge.
4550
It is an error to give a tag name that already exists unless you pass
4551
--force, in which case the tag is moved to point to the new revision.
4553
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4554
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4557
_see_also = ['commit', 'tags']
4558
takes_args = ['tag_name']
4561
help='Delete this tag rather than placing it.',
4564
help='Branch in which to place the tag.',
4569
help='Replace existing tags.',
4574
def run(self, tag_name,
4580
branch, relpath = Branch.open_containing(directory)
4584
branch.tags.delete_tag(tag_name)
4585
self.outf.write('Deleted tag %s.\n' % tag_name)
4588
if len(revision) != 1:
4589
raise errors.BzrCommandError(
4590
"Tags can only be placed on a single revision, "
4592
revision_id = revision[0].as_revision_id(branch)
4594
revision_id = branch.last_revision()
4595
if (not force) and branch.tags.has_tag(tag_name):
4596
raise errors.TagAlreadyExists(tag_name)
4597
branch.tags.set_tag(tag_name, revision_id)
4598
self.outf.write('Created tag %s.\n' % tag_name)
4603
class cmd_tags(Command):
4606
This command shows a table of tag names and the revisions they reference.
4612
help='Branch whose tags should be displayed.',
4616
RegistryOption.from_kwargs('sort',
4617
'Sort tags by different criteria.', title='Sorting',
4618
alpha='Sort tags lexicographically (default).',
4619
time='Sort tags chronologically.',
4632
branch, relpath = Branch.open_containing(directory)
4634
tags = branch.tags.get_tag_dict().items()
4641
graph = branch.repository.get_graph()
4642
rev1, rev2 = _get_revision_range(revision, branch, self.name())
4643
revid1, revid2 = rev1.rev_id, rev2.rev_id
4644
# only show revisions between revid1 and revid2 (inclusive)
4645
tags = [(tag, revid) for tag, revid in tags if
4646
graph.is_between(revid, revid1, revid2)]
4651
elif sort == 'time':
4653
for tag, revid in tags:
4655
revobj = branch.repository.get_revision(revid)
4656
except errors.NoSuchRevision:
4657
timestamp = sys.maxint # place them at the end
4659
timestamp = revobj.timestamp
4660
timestamps[revid] = timestamp
4661
tags.sort(key=lambda x: timestamps[x[1]])
4663
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4664
revno_map = branch.get_revision_id_to_revno_map()
4665
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4666
for tag, revid in tags ]
4667
for tag, revspec in tags:
4668
self.outf.write('%-20s %s\n' % (tag, revspec))
4671
class cmd_reconfigure(Command):
4672
"""Reconfigure the type of a bzr directory.
4674
A target configuration must be specified.
4676
For checkouts, the bind-to location will be auto-detected if not specified.
4677
The order of preference is
4678
1. For a lightweight checkout, the current bound location.
4679
2. For branches that used to be checkouts, the previously-bound location.
4680
3. The push location.
4681
4. The parent location.
4682
If none of these is available, --bind-to must be specified.
4685
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4686
takes_args = ['location?']
4687
takes_options = [RegistryOption.from_kwargs('target_type',
4688
title='Target type',
4689
help='The type to reconfigure the directory to.',
4690
value_switches=True, enum_switch=False,
4691
branch='Reconfigure to be an unbound branch '
4692
'with no working tree.',
4693
tree='Reconfigure to be an unbound branch '
4694
'with a working tree.',
4695
checkout='Reconfigure to be a bound branch '
4696
'with a working tree.',
4697
lightweight_checkout='Reconfigure to be a lightweight'
4698
' checkout (with no local history).',
4699
standalone='Reconfigure to be a standalone branch '
4700
'(i.e. stop using shared repository).',
4701
use_shared='Reconfigure to use a shared repository.'),
4702
Option('bind-to', help='Branch to bind checkout to.',
4705
help='Perform reconfiguration even if local changes'
4709
def run(self, location=None, target_type=None, bind_to=None, force=False):
4710
directory = bzrdir.BzrDir.open(location)
4711
if target_type is None:
4712
raise errors.BzrCommandError('No target configuration specified')
4713
elif target_type == 'branch':
4714
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4715
elif target_type == 'tree':
4716
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4717
elif target_type == 'checkout':
4718
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4720
elif target_type == 'lightweight-checkout':
4721
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4723
elif target_type == 'use-shared':
4724
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4725
elif target_type == 'standalone':
4726
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4727
reconfiguration.apply(force)
4730
class cmd_switch(Command):
4731
"""Set the branch of a checkout and update.
4733
For lightweight checkouts, this changes the branch being referenced.
4734
For heavyweight checkouts, this checks that there are no local commits
4735
versus the current bound branch, then it makes the local branch a mirror
4736
of the new location and binds to it.
4738
In both cases, the working tree is updated and uncommitted changes
4739
are merged. The user can commit or revert these as they desire.
4741
Pending merges need to be committed or reverted before using switch.
4743
The path to the branch to switch to can be specified relative to the parent
4744
directory of the current branch. For example, if you are currently in a
4745
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4748
Bound branches use the nickname of its master branch unless it is set
4749
locally, in which case switching will update the the local nickname to be
4753
takes_args = ['to_location']
4754
takes_options = [Option('force',
4755
help='Switch even if local commits will be lost.')
4758
def run(self, to_location, force=False):
4759
from bzrlib import switch
4761
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4762
branch = control_dir.open_branch()
4764
to_branch = Branch.open(to_location)
4765
except errors.NotBranchError:
4766
this_branch = control_dir.open_branch()
4767
# This may be a heavy checkout, where we want the master branch
4768
this_url = this_branch.get_bound_location()
4769
# If not, use a local sibling
4770
if this_url is None:
4771
this_url = this_branch.base
4772
to_branch = Branch.open(
4773
urlutils.join(this_url, '..', to_location))
4774
switch.switch(control_dir, to_branch, force)
4775
if branch.get_config().has_explicit_nickname():
4776
branch = control_dir.open_branch() #get the new branch!
4777
branch.nick = to_branch.nick
4778
note('Switched to branch: %s',
4779
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4782
class cmd_hooks(Command):
4783
"""Show a branch's currently registered hooks.
4787
takes_args = ['path?']
4789
def run(self, path=None):
4792
branch_hooks = Branch.open(path).hooks
4793
for hook_type in branch_hooks:
4794
hooks = branch_hooks[hook_type]
4795
self.outf.write("%s:\n" % (hook_type,))
4798
self.outf.write(" %s\n" %
4799
(branch_hooks.get_hook_name(hook),))
4801
self.outf.write(" <no hooks installed>\n")
4804
class cmd_shelve(Command):
4805
"""Temporarily set aside some changes from the current tree.
4807
Shelve allows you to temporarily put changes you've made "on the shelf",
4808
ie. out of the way, until a later time when you can bring them back from
4809
the shelf with the 'unshelve' command.
4811
If shelve --list is specified, previously-shelved changes are listed.
4813
Shelve is intended to help separate several sets of changes that have
4814
been inappropriately mingled. If you just want to get rid of all changes
4815
and you don't need to restore them later, use revert. If you want to
4816
shelve all text changes at once, use shelve --all.
4818
If filenames are specified, only the changes to those files will be
4819
shelved. Other files will be left untouched.
4821
If a revision is specified, changes since that revision will be shelved.
4823
You can put multiple items on the shelf, and by default, 'unshelve' will
4824
restore the most recently shelved changes.
4827
takes_args = ['file*']
4831
Option('all', help='Shelve all changes.'),
4833
RegistryOption('writer', 'Method to use for writing diffs.',
4834
bzrlib.option.diff_writer_registry,
4835
value_switches=True, enum_switch=False),
4837
Option('list', help='List shelved changes.'),
4839
_see_also = ['unshelve']
4841
def run(self, revision=None, all=False, file_list=None, message=None,
4842
writer=None, list=False):
4844
return self.run_for_list()
4845
from bzrlib.shelf_ui import Shelver
4847
writer = bzrlib.option.diff_writer_registry.get()
4849
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
4851
except errors.UserAbort:
4854
def run_for_list(self):
4855
tree = WorkingTree.open_containing('.')[0]
4858
manager = tree.get_shelf_manager()
4859
shelves = manager.active_shelves()
4860
if len(shelves) == 0:
4861
note('No shelved changes.')
4863
for shelf_id in reversed(shelves):
4864
message = manager.get_metadata(shelf_id).get('message')
4866
message = '<no message>'
4867
self.outf.write('%3d: %s\n' % (shelf_id, message))
4873
class cmd_unshelve(Command):
4874
"""Restore shelved changes.
4876
By default, the most recently shelved changes are restored. However if you
4877
specify a patch by name those changes will be restored instead. This
4878
works best when the changes don't depend on each other.
4881
takes_args = ['shelf_id?']
4883
RegistryOption.from_kwargs(
4884
'action', help="The action to perform.",
4885
enum_switch=False, value_switches=True,
4886
apply="Apply changes and remove from the shelf.",
4887
dry_run="Show changes, but do not apply or remove them.",
4888
delete_only="Delete changes without applying them."
4891
_see_also = ['shelve']
4893
def run(self, shelf_id=None, action='apply'):
4894
from bzrlib.shelf_ui import Unshelver
4895
Unshelver.from_args(shelf_id, action).run()
4898
def _create_prefix(cur_transport):
4899
needed = [cur_transport]
4900
# Recurse upwards until we can create a directory successfully
4902
new_transport = cur_transport.clone('..')
4903
if new_transport.base == cur_transport.base:
4904
raise errors.BzrCommandError(
4905
"Failed to create path prefix for %s."
4906
% cur_transport.base)
4908
new_transport.mkdir('.')
4909
except errors.NoSuchFile:
4910
needed.append(new_transport)
4911
cur_transport = new_transport
4914
# Now we only need to create child directories
4916
cur_transport = needed.pop()
4917
cur_transport.ensure_base()
4920
# these get imported and then picked up by the scan for cmd_*
4921
# TODO: Some more consistent way to split command definitions across files;
4922
# we do need to load at least some information about them to know of
4923
# aliases. ideally we would avoid loading the implementation until the
4924
# details were needed.
4925
from bzrlib.cmd_version_info import cmd_version_info
4926
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4927
from bzrlib.bundle.commands import (
4930
from bzrlib.sign_my_commits import cmd_sign_my_commits
4931
from bzrlib.weave_commands import cmd_versionedfile_list, \
4932
cmd_weave_plan_merge, cmd_weave_merge_text