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.option import _parse_revision_str
53
from bzrlib.revisionspec import RevisionSpec
54
from bzrlib.smtp_connection import SMTPConnection
55
from bzrlib.workingtree import WorkingTree
58
from bzrlib.commands import Command, display_command
59
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
60
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
63
def tree_files(file_list, default_branch=u'.'):
65
return internal_tree_files(file_list, default_branch)
66
except errors.FileInWrongBranch, e:
67
raise errors.BzrCommandError("%s is not in the same branch as %s" %
68
(e.path, file_list[0]))
71
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
76
rev_tree = tree.basis_tree()
78
rev_tree = branch.basis_tree()
80
if len(revisions) != 1:
81
raise errors.BzrCommandError(
82
'bzr %s --revision takes exactly one revision identifier' % (
84
rev_tree = revisions[0].as_tree(branch)
88
# XXX: Bad function name; should possibly also be a class method of
89
# WorkingTree rather than a function.
90
def internal_tree_files(file_list, default_branch=u'.'):
91
"""Convert command-line paths to a WorkingTree and relative paths.
93
This is typically used for command-line processors that take one or
94
more filenames, and infer the workingtree that contains them.
96
The filenames given are not required to exist.
98
:param file_list: Filenames to convert.
100
:param default_branch: Fallback tree path to use if file_list is empty or
103
:return: workingtree, [relative_paths]
105
if file_list is None or len(file_list) == 0:
106
return WorkingTree.open_containing(default_branch)[0], file_list
107
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
108
return tree, safe_relpath_files(tree, file_list)
111
def safe_relpath_files(tree, file_list):
112
"""Convert file_list into a list of relpaths in tree.
114
:param tree: A tree to operate on.
115
:param file_list: A list of user provided paths or None.
116
:return: A list of relative paths.
117
:raises errors.PathNotChild: When a provided path is in a different tree
120
if file_list is None:
123
for filename in file_list:
125
new_list.append(tree.relpath(osutils.dereference_path(filename)))
126
except errors.PathNotChild:
127
raise errors.FileInWrongBranch(tree.branch, filename)
131
# TODO: Make sure no commands unconditionally use the working directory as a
132
# branch. If a filename argument is used, the first of them should be used to
133
# specify the branch. (Perhaps this can be factored out into some kind of
134
# Argument class, representing a file in a branch, where the first occurrence
137
class cmd_status(Command):
138
"""Display status summary.
140
This reports on versioned and unknown files, reporting them
141
grouped by state. Possible states are:
144
Versioned in the working copy but not in the previous revision.
147
Versioned in the previous revision but removed or deleted
151
Path of this file changed from the previous revision;
152
the text may also have changed. This includes files whose
153
parent directory was renamed.
156
Text has changed since the previous revision.
159
File kind has been changed (e.g. from file to directory).
162
Not versioned and not matching an ignore pattern.
164
To see ignored files use 'bzr ignored'. For details on the
165
changes to file texts, use 'bzr diff'.
167
Note that --short or -S gives status flags for each item, similar
168
to Subversion's status command. To get output similar to svn -q,
171
If no arguments are specified, the status of the entire working
172
directory is shown. Otherwise, only the status of the specified
173
files or directories is reported. If a directory is given, status
174
is reported for everything inside that directory.
176
If a revision argument is given, the status is calculated against
177
that revision, or between two revisions if two are provided.
180
# TODO: --no-recurse, --recurse options
182
takes_args = ['file*']
183
takes_options = ['show-ids', 'revision', 'change',
184
Option('short', help='Use short status indicators.',
186
Option('versioned', help='Only show versioned files.',
188
Option('no-pending', help='Don\'t show pending merges.',
191
aliases = ['st', 'stat']
193
encoding_type = 'replace'
194
_see_also = ['diff', 'revert', 'status-flags']
197
def run(self, show_ids=False, file_list=None, revision=None, short=False,
198
versioned=False, no_pending=False):
199
from bzrlib.status import show_tree_status
201
if revision and len(revision) > 2:
202
raise errors.BzrCommandError('bzr status --revision takes exactly'
203
' one or two revision specifiers')
205
tree, relfile_list = tree_files(file_list)
206
# Avoid asking for specific files when that is not needed.
207
if relfile_list == ['']:
209
# Don't disable pending merges for full trees other than '.'.
210
if file_list == ['.']:
212
# A specific path within a tree was given.
213
elif relfile_list is not None:
215
show_tree_status(tree, show_ids=show_ids,
216
specific_files=relfile_list, revision=revision,
217
to_file=self.outf, short=short, versioned=versioned,
218
show_pending=(not no_pending))
221
class cmd_cat_revision(Command):
222
"""Write out metadata for a revision.
224
The revision to print can either be specified by a specific
225
revision identifier, or you can use --revision.
229
takes_args = ['revision_id?']
230
takes_options = ['revision']
231
# cat-revision is more for frontends so should be exact
235
def run(self, revision_id=None, revision=None):
236
if revision_id is not None and revision is not None:
237
raise errors.BzrCommandError('You can only supply one of'
238
' revision_id or --revision')
239
if revision_id is None and revision is None:
240
raise errors.BzrCommandError('You must supply either'
241
' --revision or a revision_id')
242
b = WorkingTree.open_containing(u'.')[0].branch
244
# TODO: jam 20060112 should cat-revision always output utf-8?
245
if revision_id is not None:
246
revision_id = osutils.safe_revision_id(revision_id, warn=False)
248
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
249
except errors.NoSuchRevision:
250
msg = "The repository %s contains no revision %s." % (b.repository.base,
252
raise errors.BzrCommandError(msg)
253
elif revision is not None:
256
raise errors.BzrCommandError('You cannot specify a NULL'
258
rev_id = rev.as_revision_id(b)
259
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
262
class cmd_dump_btree(Command):
263
"""Dump the contents of a btree index file to stdout.
265
PATH is a btree index file, it can be any URL. This includes things like
266
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
268
By default, the tuples stored in the index file will be displayed. With
269
--raw, we will uncompress the pages, but otherwise display the raw bytes
273
# TODO: Do we want to dump the internal nodes as well?
274
# TODO: It would be nice to be able to dump the un-parsed information,
275
# rather than only going through iter_all_entries. However, this is
276
# good enough for a start
278
encoding_type = 'exact'
279
takes_args = ['path']
280
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
281
' rather than the parsed tuples.'),
284
def run(self, path, raw=False):
285
dirname, basename = osutils.split(path)
286
t = transport.get_transport(dirname)
288
self._dump_raw_bytes(t, basename)
290
self._dump_entries(t, basename)
292
def _get_index_and_bytes(self, trans, basename):
293
"""Create a BTreeGraphIndex and raw bytes."""
294
bt = btree_index.BTreeGraphIndex(trans, basename, None)
295
bytes = trans.get_bytes(basename)
296
bt._file = cStringIO.StringIO(bytes)
297
bt._size = len(bytes)
300
def _dump_raw_bytes(self, trans, basename):
303
# We need to parse at least the root node.
304
# This is because the first page of every row starts with an
305
# uncompressed header.
306
bt, bytes = self._get_index_and_bytes(trans, basename)
307
for page_idx, page_start in enumerate(xrange(0, len(bytes),
308
btree_index._PAGE_SIZE)):
309
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
310
page_bytes = bytes[page_start:page_end]
312
self.outf.write('Root node:\n')
313
header_end, data = bt._parse_header_from_bytes(page_bytes)
314
self.outf.write(page_bytes[:header_end])
316
self.outf.write('\nPage %d\n' % (page_idx,))
317
decomp_bytes = zlib.decompress(page_bytes)
318
self.outf.write(decomp_bytes)
319
self.outf.write('\n')
321
def _dump_entries(self, trans, basename):
323
st = trans.stat(basename)
324
except errors.TransportNotPossible:
325
# We can't stat, so we'll fake it because we have to do the 'get()'
327
bt, _ = self._get_index_and_bytes(trans, basename)
329
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
330
for node in bt.iter_all_entries():
331
# Node is made up of:
332
# (index, key, value, [references])
333
self.outf.write('%s\n' % (node[1:],))
336
class cmd_remove_tree(Command):
337
"""Remove the working tree from a given branch/checkout.
339
Since a lightweight checkout is little more than a working tree
340
this will refuse to run against one.
342
To re-create the working tree, use "bzr checkout".
344
_see_also = ['checkout', 'working-trees']
345
takes_args = ['location?']
348
help='Remove the working tree even if it has '
349
'uncommitted changes.'),
352
def run(self, location='.', force=False):
353
d = bzrdir.BzrDir.open(location)
356
working = d.open_workingtree()
357
except errors.NoWorkingTree:
358
raise errors.BzrCommandError("No working tree to remove")
359
except errors.NotLocalUrl:
360
raise errors.BzrCommandError("You cannot remove the working tree of a "
363
changes = working.changes_from(working.basis_tree())
364
if changes.has_changed():
365
raise errors.UncommittedChanges(working)
367
working_path = working.bzrdir.root_transport.base
368
branch_path = working.branch.bzrdir.root_transport.base
369
if working_path != branch_path:
370
raise errors.BzrCommandError("You cannot remove the working tree from "
371
"a lightweight checkout")
373
d.destroy_workingtree()
376
class cmd_revno(Command):
377
"""Show current revision number.
379
This is equal to the number of revisions on this branch.
383
takes_args = ['location?']
386
def run(self, location=u'.'):
387
self.outf.write(str(Branch.open_containing(location)[0].revno()))
388
self.outf.write('\n')
391
class cmd_revision_info(Command):
392
"""Show revision number and revision id for a given revision identifier.
395
takes_args = ['revision_info*']
399
help='Branch to examine, '
400
'rather than the one containing the working directory.',
407
def run(self, revision=None, directory=u'.', revision_info_list=[]):
410
if revision is not None:
411
revs.extend(revision)
412
if revision_info_list is not None:
413
for rev in revision_info_list:
414
revs.append(RevisionSpec.from_string(rev))
416
b = Branch.open_containing(directory)[0]
419
revs.append(RevisionSpec.from_string('-1'))
422
revision_id = rev.as_revision_id(b)
424
revno = '%4d' % (b.revision_id_to_revno(revision_id))
425
except errors.NoSuchRevision:
426
dotted_map = b.get_revision_id_to_revno_map()
427
revno = '.'.join(str(i) for i in dotted_map[revision_id])
428
print '%s %s' % (revno, revision_id)
431
class cmd_add(Command):
432
"""Add specified files or directories.
434
In non-recursive mode, all the named items are added, regardless
435
of whether they were previously ignored. A warning is given if
436
any of the named files are already versioned.
438
In recursive mode (the default), files are treated the same way
439
but the behaviour for directories is different. Directories that
440
are already versioned do not give a warning. All directories,
441
whether already versioned or not, are searched for files or
442
subdirectories that are neither versioned or ignored, and these
443
are added. This search proceeds recursively into versioned
444
directories. If no names are given '.' is assumed.
446
Therefore simply saying 'bzr add' will version all files that
447
are currently unknown.
449
Adding a file whose parent directory is not versioned will
450
implicitly add the parent, and so on up to the root. This means
451
you should never need to explicitly add a directory, they'll just
452
get added when you add a file in the directory.
454
--dry-run will show which files would be added, but not actually
457
--file-ids-from will try to use the file ids from the supplied path.
458
It looks up ids trying to find a matching parent directory with the
459
same filename, and then by pure path. This option is rarely needed
460
but can be useful when adding the same logical file into two
461
branches that will be merged later (without showing the two different
462
adds as a conflict). It is also useful when merging another project
463
into a subdirectory of this one.
465
takes_args = ['file*']
468
help="Don't recursively add the contents of directories."),
470
help="Show what would be done, but don't actually do anything."),
472
Option('file-ids-from',
474
help='Lookup file ids from this tree.'),
476
encoding_type = 'replace'
477
_see_also = ['remove']
479
def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
484
if file_ids_from is not None:
486
base_tree, base_path = WorkingTree.open_containing(
488
except errors.NoWorkingTree:
489
base_branch, base_path = Branch.open_containing(
491
base_tree = base_branch.basis_tree()
493
action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
494
to_file=self.outf, should_print=(not is_quiet()))
496
action = bzrlib.add.AddAction(to_file=self.outf,
497
should_print=(not is_quiet()))
500
base_tree.lock_read()
502
file_list = self._maybe_expand_globs(file_list)
504
tree = WorkingTree.open_containing(file_list[0])[0]
506
tree = WorkingTree.open_containing(u'.')[0]
507
added, ignored = tree.smart_add(file_list, not
508
no_recurse, action=action, save=not dry_run)
510
if base_tree is not None:
514
for glob in sorted(ignored.keys()):
515
for path in ignored[glob]:
516
self.outf.write("ignored %s matching \"%s\"\n"
520
for glob, paths in ignored.items():
521
match_len += len(paths)
522
self.outf.write("ignored %d file(s).\n" % match_len)
523
self.outf.write("If you wish to add some of these files,"
524
" please add them by name.\n")
527
class cmd_mkdir(Command):
528
"""Create a new versioned directory.
530
This is equivalent to creating the directory and then adding it.
533
takes_args = ['dir+']
534
encoding_type = 'replace'
536
def run(self, dir_list):
539
wt, dd = WorkingTree.open_containing(d)
541
self.outf.write('added %s\n' % d)
544
class cmd_relpath(Command):
545
"""Show path of a file relative to root"""
547
takes_args = ['filename']
551
def run(self, filename):
552
# TODO: jam 20050106 Can relpath return a munged path if
553
# sys.stdout encoding cannot represent it?
554
tree, relpath = WorkingTree.open_containing(filename)
555
self.outf.write(relpath)
556
self.outf.write('\n')
559
class cmd_inventory(Command):
560
"""Show inventory of the current working copy or a revision.
562
It is possible to limit the output to a particular entry
563
type using the --kind option. For example: --kind file.
565
It is also possible to restrict the list of files to a specific
566
set. For example: bzr inventory --show-ids this/file
575
help='List entries of a particular kind: file, directory, symlink.',
578
takes_args = ['file*']
581
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
582
if kind and kind not in ['file', 'directory', 'symlink']:
583
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
585
work_tree, file_list = tree_files(file_list)
586
work_tree.lock_read()
588
if revision is not None:
589
if len(revision) > 1:
590
raise errors.BzrCommandError(
591
'bzr inventory --revision takes exactly one revision'
593
tree = revision[0].as_tree(work_tree.branch)
595
extra_trees = [work_tree]
601
if file_list is not None:
602
file_ids = tree.paths2ids(file_list, trees=extra_trees,
603
require_versioned=True)
604
# find_ids_across_trees may include some paths that don't
606
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
607
for file_id in file_ids if file_id in tree)
609
entries = tree.inventory.entries()
612
if tree is not work_tree:
615
for path, entry in entries:
616
if kind and kind != entry.kind:
619
self.outf.write('%-50s %s\n' % (path, entry.file_id))
621
self.outf.write(path)
622
self.outf.write('\n')
625
class cmd_mv(Command):
626
"""Move or rename a file.
629
bzr mv OLDNAME NEWNAME
631
bzr mv SOURCE... DESTINATION
633
If the last argument is a versioned directory, all the other names
634
are moved into it. Otherwise, there must be exactly two arguments
635
and the file is changed to a new name.
637
If OLDNAME does not exist on the filesystem but is versioned and
638
NEWNAME does exist on the filesystem but is not versioned, mv
639
assumes that the file has been manually moved and only updates
640
its internal inventory to reflect that change.
641
The same is valid when moving many SOURCE files to a DESTINATION.
643
Files cannot be moved between branches.
646
takes_args = ['names*']
647
takes_options = [Option("after", help="Move only the bzr identifier"
648
" of the file, because the file has already been moved."),
650
aliases = ['move', 'rename']
651
encoding_type = 'replace'
653
def run(self, names_list, after=False):
654
if names_list is None:
657
if len(names_list) < 2:
658
raise errors.BzrCommandError("missing file argument")
659
tree, rel_names = tree_files(names_list)
662
self._run(tree, names_list, rel_names, after)
666
def _run(self, tree, names_list, rel_names, after):
667
into_existing = osutils.isdir(names_list[-1])
668
if into_existing and len(names_list) == 2:
670
# a. case-insensitive filesystem and change case of dir
671
# b. move directory after the fact (if the source used to be
672
# a directory, but now doesn't exist in the working tree
673
# and the target is an existing directory, just rename it)
674
if (not tree.case_sensitive
675
and rel_names[0].lower() == rel_names[1].lower()):
676
into_existing = False
679
from_id = tree.path2id(rel_names[0])
680
if (not osutils.lexists(names_list[0]) and
681
from_id and inv.get_file_kind(from_id) == "directory"):
682
into_existing = False
685
# move into existing directory
686
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
687
self.outf.write("%s => %s\n" % pair)
689
if len(names_list) != 2:
690
raise errors.BzrCommandError('to mv multiple files the'
691
' destination must be a versioned'
693
tree.rename_one(rel_names[0], rel_names[1], after=after)
694
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
697
class cmd_pull(Command):
698
"""Turn this branch into a mirror of another branch.
700
This command only works on branches that have not diverged. Branches are
701
considered diverged if the destination branch's most recent commit is one
702
that has not been merged (directly or indirectly) into the parent.
704
If branches have diverged, you can use 'bzr merge' to integrate the changes
705
from one into the other. Once one branch has merged, the other should
706
be able to pull it again.
708
If you want to forget your local changes and just update your branch to
709
match the remote one, use pull --overwrite.
711
If there is no default location set, the first pull will set it. After
712
that, you can omit the location to use the default. To change the
713
default, use --remember. The value will only be saved if the remote
714
location can be accessed.
716
Note: The location can be specified either in the form of a branch,
717
or in the form of a path to a file containing a merge directive generated
721
_see_also = ['push', 'update', 'status-flags']
722
takes_options = ['remember', 'overwrite', 'revision',
723
custom_help('verbose',
724
help='Show logs of pulled revisions.'),
726
help='Branch to pull into, '
727
'rather than the one containing the working directory.',
732
takes_args = ['location?']
733
encoding_type = 'replace'
735
def run(self, location=None, remember=False, overwrite=False,
736
revision=None, verbose=False,
738
# FIXME: too much stuff is in the command class
741
if directory is None:
744
tree_to = WorkingTree.open_containing(directory)[0]
745
branch_to = tree_to.branch
746
except errors.NoWorkingTree:
748
branch_to = Branch.open_containing(directory)[0]
750
possible_transports = []
751
if location is not None:
753
mergeable = bundle.read_mergeable_from_url(location,
754
possible_transports=possible_transports)
755
except errors.NotABundle:
758
stored_loc = branch_to.get_parent()
760
if stored_loc is None:
761
raise errors.BzrCommandError("No pull location known or"
764
display_url = urlutils.unescape_for_display(stored_loc,
767
self.outf.write("Using saved parent location: %s\n" % display_url)
768
location = stored_loc
770
if mergeable is not None:
771
if revision is not None:
772
raise errors.BzrCommandError(
773
'Cannot use -r with merge directives or bundles')
774
mergeable.install_revisions(branch_to.repository)
775
base_revision_id, revision_id, verified = \
776
mergeable.get_merge_request(branch_to.repository)
777
branch_from = branch_to
779
branch_from = Branch.open(location,
780
possible_transports=possible_transports)
782
if branch_to.get_parent() is None or remember:
783
branch_to.set_parent(branch_from.base)
785
if revision is not None:
786
if len(revision) == 1:
787
revision_id = revision[0].as_revision_id(branch_from)
789
raise errors.BzrCommandError(
790
'bzr pull --revision takes one value.')
792
branch_to.lock_write()
794
if tree_to is not None:
795
change_reporter = delta._ChangeReporter(
796
unversioned_filter=tree_to.is_ignored)
797
result = tree_to.pull(branch_from, overwrite, revision_id,
799
possible_transports=possible_transports)
801
result = branch_to.pull(branch_from, overwrite, revision_id)
803
result.report(self.outf)
804
if verbose and result.old_revid != result.new_revid:
806
branch_to.repository.iter_reverse_revision_history(
809
new_rh = branch_to.revision_history()
810
log_format = branch_to.get_config().log_format()
811
log.show_changed_revisions(branch_to, old_rh, new_rh,
813
log_format=log_format)
818
class cmd_push(Command):
819
"""Update a mirror of this branch.
821
The target branch will not have its working tree populated because this
822
is both expensive, and is not supported on remote file systems.
824
Some smart servers or protocols *may* put the working tree in place in
827
This command only works on branches that have not diverged. Branches are
828
considered diverged if the destination branch's most recent commit is one
829
that has not been merged (directly or indirectly) by the source branch.
831
If branches have diverged, you can use 'bzr push --overwrite' to replace
832
the other branch completely, discarding its unmerged changes.
834
If you want to ensure you have the different changes in the other branch,
835
do a merge (see bzr help merge) from the other branch, and commit that.
836
After that you will be able to do a push without '--overwrite'.
838
If there is no default push location set, the first push will set it.
839
After that, you can omit the location to use the default. To change the
840
default, use --remember. The value will only be saved if the remote
841
location can be accessed.
844
_see_also = ['pull', 'update', 'working-trees']
845
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
846
Option('create-prefix',
847
help='Create the path leading up to the branch '
848
'if it does not already exist.'),
850
help='Branch to push from, '
851
'rather than the one containing the working directory.',
855
Option('use-existing-dir',
856
help='By default push will fail if the target'
857
' directory exists, but does not already'
858
' have a control directory. This flag will'
859
' allow push to proceed.'),
861
help='Create a stacked branch that references the public location '
862
'of the parent branch.'),
864
help='Create a stacked branch that refers to another branch '
865
'for the commit history. Only the work not present in the '
866
'referenced branch is included in the branch created.',
869
takes_args = ['location?']
870
encoding_type = 'replace'
872
def run(self, location=None, remember=False, overwrite=False,
873
create_prefix=False, verbose=False, revision=None,
874
use_existing_dir=False, directory=None, stacked_on=None,
876
from bzrlib.push import _show_push_branch
878
# Get the source branch and revision_id
879
if directory is None:
881
br_from = Branch.open_containing(directory)[0]
882
if revision is not None:
883
if len(revision) == 1:
884
revision_id = revision[0].in_history(br_from).rev_id
886
raise errors.BzrCommandError(
887
'bzr push --revision takes one value.')
889
revision_id = br_from.last_revision()
891
# Get the stacked_on branch, if any
892
if stacked_on is not None:
893
stacked_on = urlutils.normalize_url(stacked_on)
895
parent_url = br_from.get_parent()
897
parent = Branch.open(parent_url)
898
stacked_on = parent.get_public_branch()
900
# I considered excluding non-http url's here, thus forcing
901
# 'public' branches only, but that only works for some
902
# users, so it's best to just depend on the user spotting an
903
# error by the feedback given to them. RBC 20080227.
904
stacked_on = parent_url
906
raise errors.BzrCommandError(
907
"Could not determine branch to refer to.")
909
# Get the destination location
911
stored_loc = br_from.get_push_location()
912
if stored_loc is None:
913
raise errors.BzrCommandError(
914
"No push location known or specified.")
916
display_url = urlutils.unescape_for_display(stored_loc,
918
self.outf.write("Using saved push location: %s\n" % display_url)
919
location = stored_loc
921
_show_push_branch(br_from, revision_id, location, self.outf,
922
verbose=verbose, overwrite=overwrite, remember=remember,
923
stacked_on=stacked_on, create_prefix=create_prefix,
924
use_existing_dir=use_existing_dir)
927
class cmd_branch(Command):
928
"""Create a new copy of a branch.
930
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
931
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
932
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
933
is derived from the FROM_LOCATION by stripping a leading scheme or drive
934
identifier, if any. For example, "branch lp:foo-bar" will attempt to
937
To retrieve the branch as of a particular revision, supply the --revision
938
parameter, as in "branch foo/bar -r 5".
941
_see_also = ['checkout']
942
takes_args = ['from_location', 'to_location?']
943
takes_options = ['revision', Option('hardlink',
944
help='Hard-link working tree files where possible.'),
946
help='Create a stacked branch referring to the source branch. '
947
'The new branch will depend on the availability of the source '
948
'branch for all operations.'),
950
help='Do not use a shared repository, even if available.'),
952
aliases = ['get', 'clone']
954
def run(self, from_location, to_location=None, revision=None,
955
hardlink=False, stacked=False, standalone=False):
956
from bzrlib.tag import _merge_tags_if_possible
959
elif len(revision) > 1:
960
raise errors.BzrCommandError(
961
'bzr branch --revision takes exactly 1 revision value')
963
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
967
if len(revision) == 1 and revision[0] is not None:
968
revision_id = revision[0].as_revision_id(br_from)
970
# FIXME - wt.last_revision, fallback to branch, fall back to
971
# None or perhaps NULL_REVISION to mean copy nothing
973
revision_id = br_from.last_revision()
974
if to_location is None:
975
to_location = urlutils.derive_to_location(from_location)
976
to_transport = transport.get_transport(to_location)
978
to_transport.mkdir('.')
979
except errors.FileExists:
980
raise errors.BzrCommandError('Target directory "%s" already'
981
' exists.' % to_location)
982
except errors.NoSuchFile:
983
raise errors.BzrCommandError('Parent of "%s" does not exist.'
986
# preserve whatever source format we have.
987
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
988
possible_transports=[to_transport],
989
accelerator_tree=accelerator_tree,
990
hardlink=hardlink, stacked=stacked,
991
force_new_repo=standalone,
992
source_branch=br_from)
993
branch = dir.open_branch()
994
except errors.NoSuchRevision:
995
to_transport.delete_tree('.')
996
msg = "The branch %s has no revision %s." % (from_location,
998
raise errors.BzrCommandError(msg)
999
_merge_tags_if_possible(br_from, branch)
1000
# If the source branch is stacked, the new branch may
1001
# be stacked whether we asked for that explicitly or not.
1002
# We therefore need a try/except here and not just 'if stacked:'
1004
note('Created new stacked branch referring to %s.' %
1005
branch.get_stacked_on_url())
1006
except (errors.NotStacked, errors.UnstackableBranchFormat,
1007
errors.UnstackableRepositoryFormat), e:
1008
note('Branched %d revision(s).' % branch.revno())
1013
class cmd_checkout(Command):
1014
"""Create a new checkout of an existing branch.
1016
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1017
the branch found in '.'. This is useful if you have removed the working tree
1018
or if it was never created - i.e. if you pushed the branch to its current
1019
location using SFTP.
1021
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1022
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1023
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1024
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1025
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1028
To retrieve the branch as of a particular revision, supply the --revision
1029
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1030
out of date [so you cannot commit] but it may be useful (i.e. to examine old
1034
_see_also = ['checkouts', 'branch']
1035
takes_args = ['branch_location?', 'to_location?']
1036
takes_options = ['revision',
1037
Option('lightweight',
1038
help="Perform a lightweight checkout. Lightweight "
1039
"checkouts depend on access to the branch for "
1040
"every operation. Normal checkouts can perform "
1041
"common operations like diff and status without "
1042
"such access, and also support local commits."
1044
Option('files-from', type=str,
1045
help="Get file contents from this tree."),
1047
help='Hard-link working tree files where possible.'
1052
def run(self, branch_location=None, to_location=None, revision=None,
1053
lightweight=False, files_from=None, hardlink=False):
1054
if revision is None:
1056
elif len(revision) > 1:
1057
raise errors.BzrCommandError(
1058
'bzr checkout --revision takes exactly 1 revision value')
1059
if branch_location is None:
1060
branch_location = osutils.getcwd()
1061
to_location = branch_location
1062
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1064
if files_from is not None:
1065
accelerator_tree = WorkingTree.open(files_from)
1066
if len(revision) == 1 and revision[0] is not None:
1067
revision_id = revision[0].as_revision_id(source)
1070
if to_location is None:
1071
to_location = urlutils.derive_to_location(branch_location)
1072
# if the source and to_location are the same,
1073
# and there is no working tree,
1074
# then reconstitute a branch
1075
if (osutils.abspath(to_location) ==
1076
osutils.abspath(branch_location)):
1078
source.bzrdir.open_workingtree()
1079
except errors.NoWorkingTree:
1080
source.bzrdir.create_workingtree(revision_id)
1082
source.create_checkout(to_location, revision_id, lightweight,
1083
accelerator_tree, hardlink)
1086
class cmd_renames(Command):
1087
"""Show list of renamed files.
1089
# TODO: Option to show renames between two historical versions.
1091
# TODO: Only show renames under dir, rather than in the whole branch.
1092
_see_also = ['status']
1093
takes_args = ['dir?']
1096
def run(self, dir=u'.'):
1097
tree = WorkingTree.open_containing(dir)[0]
1100
new_inv = tree.inventory
1101
old_tree = tree.basis_tree()
1102
old_tree.lock_read()
1104
old_inv = old_tree.inventory
1106
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1107
for f, paths, c, v, p, n, k, e in iterator:
1108
if paths[0] == paths[1]:
1112
renames.append(paths)
1114
for old_name, new_name in renames:
1115
self.outf.write("%s => %s\n" % (old_name, new_name))
1122
class cmd_update(Command):
1123
"""Update a tree to have the latest code committed to its branch.
1125
This will perform a merge into the working tree, and may generate
1126
conflicts. If you have any local changes, you will still
1127
need to commit them after the update for the update to be complete.
1129
If you want to discard your local changes, you can just do a
1130
'bzr revert' instead of 'bzr commit' after the update.
1133
_see_also = ['pull', 'working-trees', 'status-flags']
1134
takes_args = ['dir?']
1137
def run(self, dir='.'):
1138
tree = WorkingTree.open_containing(dir)[0]
1139
possible_transports = []
1140
master = tree.branch.get_master_branch(
1141
possible_transports=possible_transports)
1142
if master is not None:
1145
tree.lock_tree_write()
1147
existing_pending_merges = tree.get_parent_ids()[1:]
1148
last_rev = _mod_revision.ensure_null(tree.last_revision())
1149
if last_rev == _mod_revision.ensure_null(
1150
tree.branch.last_revision()):
1151
# may be up to date, check master too.
1152
if master is None or last_rev == _mod_revision.ensure_null(
1153
master.last_revision()):
1154
revno = tree.branch.revision_id_to_revno(last_rev)
1155
note("Tree is up to date at revision %d." % (revno,))
1157
conflicts = tree.update(
1158
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1159
possible_transports=possible_transports)
1160
revno = tree.branch.revision_id_to_revno(
1161
_mod_revision.ensure_null(tree.last_revision()))
1162
note('Updated to revision %d.' % (revno,))
1163
if tree.get_parent_ids()[1:] != existing_pending_merges:
1164
note('Your local commits will now show as pending merges with '
1165
"'bzr status', and can be committed with 'bzr commit'.")
1174
class cmd_info(Command):
1175
"""Show information about a working tree, branch or repository.
1177
This command will show all known locations and formats associated to the
1178
tree, branch or repository. Statistical information is included with
1181
Branches and working trees will also report any missing revisions.
1183
_see_also = ['revno', 'working-trees', 'repositories']
1184
takes_args = ['location?']
1185
takes_options = ['verbose']
1186
encoding_type = 'replace'
1189
def run(self, location=None, verbose=False):
1194
from bzrlib.info import show_bzrdir_info
1195
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1196
verbose=noise_level, outfile=self.outf)
1199
class cmd_remove(Command):
1200
"""Remove files or directories.
1202
This makes bzr stop tracking changes to the specified files. bzr will delete
1203
them if they can easily be recovered using revert. If no options or
1204
parameters are given bzr will scan for files that are being tracked by bzr
1205
but missing in your tree and stop tracking them for you.
1207
takes_args = ['file*']
1208
takes_options = ['verbose',
1209
Option('new', help='Only remove files that have never been committed.'),
1210
RegistryOption.from_kwargs('file-deletion-strategy',
1211
'The file deletion mode to be used.',
1212
title='Deletion Strategy', value_switches=True, enum_switch=False,
1213
safe='Only delete files if they can be'
1214
' safely recovered (default).',
1215
keep="Don't delete any files.",
1216
force='Delete all the specified files, even if they can not be '
1217
'recovered and even if they are non-empty directories.')]
1218
aliases = ['rm', 'del']
1219
encoding_type = 'replace'
1221
def run(self, file_list, verbose=False, new=False,
1222
file_deletion_strategy='safe'):
1223
tree, file_list = tree_files(file_list)
1225
if file_list is not None:
1226
file_list = [f for f in file_list]
1230
# Heuristics should probably all move into tree.remove_smart or
1233
added = tree.changes_from(tree.basis_tree(),
1234
specific_files=file_list).added
1235
file_list = sorted([f[0] for f in added], reverse=True)
1236
if len(file_list) == 0:
1237
raise errors.BzrCommandError('No matching files.')
1238
elif file_list is None:
1239
# missing files show up in iter_changes(basis) as
1240
# versioned-with-no-kind.
1242
for change in tree.iter_changes(tree.basis_tree()):
1243
# Find paths in the working tree that have no kind:
1244
if change[1][1] is not None and change[6][1] is None:
1245
missing.append(change[1][1])
1246
file_list = sorted(missing, reverse=True)
1247
file_deletion_strategy = 'keep'
1248
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1249
keep_files=file_deletion_strategy=='keep',
1250
force=file_deletion_strategy=='force')
1255
class cmd_file_id(Command):
1256
"""Print file_id of a particular file or directory.
1258
The file_id is assigned when the file is first added and remains the
1259
same through all revisions where the file exists, even when it is
1264
_see_also = ['inventory', 'ls']
1265
takes_args = ['filename']
1268
def run(self, filename):
1269
tree, relpath = WorkingTree.open_containing(filename)
1270
i = tree.path2id(relpath)
1272
raise errors.NotVersionedError(filename)
1274
self.outf.write(i + '\n')
1277
class cmd_file_path(Command):
1278
"""Print path of file_ids to a file or directory.
1280
This prints one line for each directory down to the target,
1281
starting at the branch root.
1285
takes_args = ['filename']
1288
def run(self, filename):
1289
tree, relpath = WorkingTree.open_containing(filename)
1290
fid = tree.path2id(relpath)
1292
raise errors.NotVersionedError(filename)
1293
segments = osutils.splitpath(relpath)
1294
for pos in range(1, len(segments) + 1):
1295
path = osutils.joinpath(segments[:pos])
1296
self.outf.write("%s\n" % tree.path2id(path))
1299
class cmd_reconcile(Command):
1300
"""Reconcile bzr metadata in a branch.
1302
This can correct data mismatches that may have been caused by
1303
previous ghost operations or bzr upgrades. You should only
1304
need to run this command if 'bzr check' or a bzr developer
1305
advises you to run it.
1307
If a second branch is provided, cross-branch reconciliation is
1308
also attempted, which will check that data like the tree root
1309
id which was not present in very early bzr versions is represented
1310
correctly in both branches.
1312
At the same time it is run it may recompress data resulting in
1313
a potential saving in disk space or performance gain.
1315
The branch *MUST* be on a listable system such as local disk or sftp.
1318
_see_also = ['check']
1319
takes_args = ['branch?']
1321
def run(self, branch="."):
1322
from bzrlib.reconcile import reconcile
1323
dir = bzrdir.BzrDir.open(branch)
1327
class cmd_revision_history(Command):
1328
"""Display the list of revision ids on a branch."""
1331
takes_args = ['location?']
1336
def run(self, location="."):
1337
branch = Branch.open_containing(location)[0]
1338
for revid in branch.revision_history():
1339
self.outf.write(revid)
1340
self.outf.write('\n')
1343
class cmd_ancestry(Command):
1344
"""List all revisions merged into this branch."""
1346
_see_also = ['log', 'revision-history']
1347
takes_args = ['location?']
1352
def run(self, location="."):
1354
wt = WorkingTree.open_containing(location)[0]
1355
except errors.NoWorkingTree:
1356
b = Branch.open(location)
1357
last_revision = b.last_revision()
1360
last_revision = wt.last_revision()
1362
revision_ids = b.repository.get_ancestry(last_revision)
1364
for revision_id in revision_ids:
1365
self.outf.write(revision_id + '\n')
1368
class cmd_init(Command):
1369
"""Make a directory into a versioned branch.
1371
Use this to create an empty branch, or before importing an
1374
If there is a repository in a parent directory of the location, then
1375
the history of the branch will be stored in the repository. Otherwise
1376
init creates a standalone branch which carries its own history
1377
in the .bzr directory.
1379
If there is already a branch at the location but it has no working tree,
1380
the tree can be populated with 'bzr checkout'.
1382
Recipe for importing a tree of files::
1388
bzr commit -m "imported project"
1391
_see_also = ['init-repository', 'branch', 'checkout']
1392
takes_args = ['location?']
1394
Option('create-prefix',
1395
help='Create the path leading up to the branch '
1396
'if it does not already exist.'),
1397
RegistryOption('format',
1398
help='Specify a format for this branch. '
1399
'See "help formats".',
1400
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1401
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1402
value_switches=True,
1403
title="Branch Format",
1405
Option('append-revisions-only',
1406
help='Never change revnos or the existing log.'
1407
' Append revisions to it only.')
1409
def run(self, location=None, format=None, append_revisions_only=False,
1410
create_prefix=False):
1412
format = bzrdir.format_registry.make_bzrdir('default')
1413
if location is None:
1416
to_transport = transport.get_transport(location)
1418
# The path has to exist to initialize a
1419
# branch inside of it.
1420
# Just using os.mkdir, since I don't
1421
# believe that we want to create a bunch of
1422
# locations if the user supplies an extended path
1424
to_transport.ensure_base()
1425
except errors.NoSuchFile:
1426
if not create_prefix:
1427
raise errors.BzrCommandError("Parent directory of %s"
1429
"\nYou may supply --create-prefix to create all"
1430
" leading parent directories."
1432
_create_prefix(to_transport)
1435
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1436
except errors.NotBranchError:
1437
# really a NotBzrDir error...
1438
create_branch = bzrdir.BzrDir.create_branch_convenience
1439
branch = create_branch(to_transport.base, format=format,
1440
possible_transports=[to_transport])
1441
a_bzrdir = branch.bzrdir
1443
from bzrlib.transport.local import LocalTransport
1444
if a_bzrdir.has_branch():
1445
if (isinstance(to_transport, LocalTransport)
1446
and not a_bzrdir.has_workingtree()):
1447
raise errors.BranchExistsWithoutWorkingTree(location)
1448
raise errors.AlreadyBranchError(location)
1449
branch = a_bzrdir.create_branch()
1450
a_bzrdir.create_workingtree()
1451
if append_revisions_only:
1453
branch.set_append_revisions_only(True)
1454
except errors.UpgradeRequired:
1455
raise errors.BzrCommandError('This branch format cannot be set'
1456
' to append-revisions-only. Try --experimental-branch6')
1458
from bzrlib.info import show_bzrdir_info
1459
show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1462
class cmd_init_repository(Command):
1463
"""Create a shared repository to hold branches.
1465
New branches created under the repository directory will store their
1466
revisions in the repository, not in the branch directory.
1468
If the --no-trees option is used then the branches in the repository
1469
will not have working trees by default.
1472
Create a shared repositories holding just branches::
1474
bzr init-repo --no-trees repo
1477
Make a lightweight checkout elsewhere::
1479
bzr checkout --lightweight repo/trunk trunk-checkout
1484
_see_also = ['init', 'branch', 'checkout', 'repositories']
1485
takes_args = ["location"]
1486
takes_options = [RegistryOption('format',
1487
help='Specify a format for this repository. See'
1488
' "bzr help formats" for details.',
1489
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1490
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1491
value_switches=True, title='Repository format'),
1493
help='Branches in the repository will default to'
1494
' not having a working tree.'),
1496
aliases = ["init-repo"]
1498
def run(self, location, format=None, no_trees=False):
1500
format = bzrdir.format_registry.make_bzrdir('default')
1502
if location is None:
1505
to_transport = transport.get_transport(location)
1506
to_transport.ensure_base()
1508
newdir = format.initialize_on_transport(to_transport)
1509
repo = newdir.create_repository(shared=True)
1510
repo.set_make_working_trees(not no_trees)
1512
from bzrlib.info import show_bzrdir_info
1513
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1516
class cmd_diff(Command):
1517
"""Show differences in the working tree, between revisions or branches.
1519
If no arguments are given, all changes for the current tree are listed.
1520
If files are given, only the changes in those files are listed.
1521
Remote and multiple branches can be compared by using the --old and
1522
--new options. If not provided, the default for both is derived from
1523
the first argument, if any, or the current tree if no arguments are
1526
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1527
produces patches suitable for "patch -p1".
1531
2 - unrepresentable changes
1536
Shows the difference in the working tree versus the last commit::
1540
Difference between the working tree and revision 1::
1544
Difference between revision 2 and revision 1::
1548
Difference between revision 2 and revision 1 for branch xxx::
1552
Show just the differences for file NEWS::
1556
Show the differences in working tree xxx for file NEWS::
1560
Show the differences from branch xxx to this working tree:
1564
Show the differences between two branches for file NEWS::
1566
bzr diff --old xxx --new yyy NEWS
1568
Same as 'bzr diff' but prefix paths with old/ and new/::
1570
bzr diff --prefix old/:new/
1572
_see_also = ['status']
1573
takes_args = ['file*']
1575
Option('diff-options', type=str,
1576
help='Pass these options to the external diff program.'),
1577
Option('prefix', type=str,
1579
help='Set prefixes added to old and new filenames, as '
1580
'two values separated by a colon. (eg "old/:new/").'),
1582
help='Branch/tree to compare from.',
1586
help='Branch/tree to compare to.',
1592
help='Use this command to compare files.',
1596
aliases = ['di', 'dif']
1597
encoding_type = 'exact'
1600
def run(self, revision=None, file_list=None, diff_options=None,
1601
prefix=None, old=None, new=None, using=None):
1602
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1604
if (prefix is None) or (prefix == '0'):
1612
old_label, new_label = prefix.split(":")
1614
raise errors.BzrCommandError(
1615
'--prefix expects two values separated by a colon'
1616
' (eg "old/:new/")')
1618
if revision and len(revision) > 2:
1619
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1620
' one or two revision specifiers')
1622
old_tree, new_tree, specific_files, extra_trees = \
1623
_get_trees_to_diff(file_list, revision, old, new)
1624
return show_diff_trees(old_tree, new_tree, sys.stdout,
1625
specific_files=specific_files,
1626
external_diff_options=diff_options,
1627
old_label=old_label, new_label=new_label,
1628
extra_trees=extra_trees, using=using)
1631
class cmd_deleted(Command):
1632
"""List files deleted in the working tree.
1634
# TODO: Show files deleted since a previous revision, or
1635
# between two revisions.
1636
# TODO: Much more efficient way to do this: read in new
1637
# directories with readdir, rather than stating each one. Same
1638
# level of effort but possibly much less IO. (Or possibly not,
1639
# if the directories are very large...)
1640
_see_also = ['status', 'ls']
1641
takes_options = ['show-ids']
1644
def run(self, show_ids=False):
1645
tree = WorkingTree.open_containing(u'.')[0]
1648
old = tree.basis_tree()
1651
for path, ie in old.inventory.iter_entries():
1652
if not tree.has_id(ie.file_id):
1653
self.outf.write(path)
1655
self.outf.write(' ')
1656
self.outf.write(ie.file_id)
1657
self.outf.write('\n')
1664
class cmd_modified(Command):
1665
"""List files modified in working tree.
1669
_see_also = ['status', 'ls']
1672
help='Write an ascii NUL (\\0) separator '
1673
'between files rather than a newline.')
1677
def run(self, null=False):
1678
tree = WorkingTree.open_containing(u'.')[0]
1679
td = tree.changes_from(tree.basis_tree())
1680
for path, id, kind, text_modified, meta_modified in td.modified:
1682
self.outf.write(path + '\0')
1684
self.outf.write(osutils.quotefn(path) + '\n')
1687
class cmd_added(Command):
1688
"""List files added in working tree.
1692
_see_also = ['status', 'ls']
1695
help='Write an ascii NUL (\\0) separator '
1696
'between files rather than a newline.')
1700
def run(self, null=False):
1701
wt = WorkingTree.open_containing(u'.')[0]
1704
basis = wt.basis_tree()
1707
basis_inv = basis.inventory
1710
if file_id in basis_inv:
1712
if inv.is_root(file_id) and len(basis_inv) == 0:
1714
path = inv.id2path(file_id)
1715
if not os.access(osutils.abspath(path), os.F_OK):
1718
self.outf.write(path + '\0')
1720
self.outf.write(osutils.quotefn(path) + '\n')
1727
class cmd_root(Command):
1728
"""Show the tree root directory.
1730
The root is the nearest enclosing directory with a .bzr control
1733
takes_args = ['filename?']
1735
def run(self, filename=None):
1736
"""Print the branch root."""
1737
tree = WorkingTree.open_containing(filename)[0]
1738
self.outf.write(tree.basedir + '\n')
1741
def _parse_limit(limitstring):
1743
return int(limitstring)
1745
msg = "The limit argument must be an integer."
1746
raise errors.BzrCommandError(msg)
1749
class cmd_log(Command):
1750
"""Show log of a branch, file, or directory.
1752
By default show the log of the branch containing the working directory.
1754
To request a range of logs, you can use the command -r begin..end
1755
-r revision requests a specific revision, -r ..end or -r begin.. are
1759
Log the current branch::
1767
Log the last 10 revisions of a branch::
1769
bzr log -r -10.. http://server/branch
1772
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1774
takes_args = ['location?']
1777
help='Show from oldest to newest.'),
1779
custom_help('verbose',
1780
help='Show files changed in each revision.'),
1784
type=bzrlib.option._parse_revision_str,
1786
help='Show just the specified revision.'
1787
' See also "help revisionspec".'),
1791
help='Show revisions whose message matches this '
1792
'regular expression.',
1796
help='Limit the output to the first N revisions.',
1800
encoding_type = 'replace'
1803
def run(self, location=None, timezone='original',
1812
from bzrlib.log import show_log
1813
direction = (forward and 'forward') or 'reverse'
1815
if change is not None:
1817
raise errors.RangeInChangeOption()
1818
if revision is not None:
1819
raise errors.BzrCommandError(
1820
'--revision and --change are mutually exclusive')
1827
# find the file id to log:
1829
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1833
tree = b.basis_tree()
1834
file_id = tree.path2id(fp)
1836
raise errors.BzrCommandError(
1837
"Path does not have any revision history: %s" %
1841
# FIXME ? log the current subdir only RBC 20060203
1842
if revision is not None \
1843
and len(revision) > 0 and revision[0].get_branch():
1844
location = revision[0].get_branch()
1847
dir, relpath = bzrdir.BzrDir.open_containing(location)
1848
b = dir.open_branch()
1852
rev1, rev2 = _get_revision_range(revision, b, self.name())
1853
if log_format is None:
1854
log_format = log.log_formatter_registry.get_default(b)
1856
lf = log_format(show_ids=show_ids, to_file=self.outf,
1857
show_timezone=timezone,
1858
delta_format=get_verbosity_level())
1864
direction=direction,
1865
start_revision=rev1,
1872
def _get_revision_range(revisionspec_list, branch, command_name):
1873
"""Take the input of a revision option and turn it into a revision range.
1875
It returns RevisionInfo objects which can be used to obtain the rev_id's
1876
of the desired revisons. It does some user input validations.
1878
if revisionspec_list is None:
1881
elif len(revisionspec_list) == 1:
1882
rev1 = rev2 = revisionspec_list[0].in_history(branch)
1883
elif len(revisionspec_list) == 2:
1884
if revisionspec_list[1].get_branch() != revisionspec_list[0
1886
# b is taken from revision[0].get_branch(), and
1887
# show_log will use its revision_history. Having
1888
# different branches will lead to weird behaviors.
1889
raise errors.BzrCommandError(
1890
"bzr %s doesn't accept two revisions in different"
1891
" branches." % command_name)
1892
rev1 = revisionspec_list[0].in_history(branch)
1893
rev2 = revisionspec_list[1].in_history(branch)
1895
raise errors.BzrCommandError(
1896
'bzr %s --revision takes one or two values.' % command_name)
1900
def _revision_range_to_revid_range(revision_range):
1903
if revision_range[0] is not None:
1904
rev_id1 = revision_range[0].rev_id
1905
if revision_range[1] is not None:
1906
rev_id2 = revision_range[1].rev_id
1907
return rev_id1, rev_id2
1909
def get_log_format(long=False, short=False, line=False, default='long'):
1910
log_format = default
1914
log_format = 'short'
1920
class cmd_touching_revisions(Command):
1921
"""Return revision-ids which affected a particular file.
1923
A more user-friendly interface is "bzr log FILE".
1927
takes_args = ["filename"]
1930
def run(self, filename):
1931
tree, relpath = WorkingTree.open_containing(filename)
1933
file_id = tree.path2id(relpath)
1934
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1935
self.outf.write("%6d %s\n" % (revno, what))
1938
class cmd_ls(Command):
1939
"""List files in a tree.
1942
_see_also = ['status', 'cat']
1943
takes_args = ['path?']
1944
# TODO: Take a revision or remote path and list that tree instead.
1948
Option('non-recursive',
1949
help='Don\'t recurse into subdirectories.'),
1951
help='Print paths relative to the root of the branch.'),
1952
Option('unknown', help='Print unknown files.'),
1953
Option('versioned', help='Print versioned files.',
1955
Option('ignored', help='Print ignored files.'),
1957
help='Write an ascii NUL (\\0) separator '
1958
'between files rather than a newline.'),
1960
help='List entries of a particular kind: file, directory, symlink.',
1965
def run(self, revision=None, verbose=False,
1966
non_recursive=False, from_root=False,
1967
unknown=False, versioned=False, ignored=False,
1968
null=False, kind=None, show_ids=False, path=None):
1970
if kind and kind not in ('file', 'directory', 'symlink'):
1971
raise errors.BzrCommandError('invalid kind specified')
1973
if verbose and null:
1974
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1975
all = not (unknown or versioned or ignored)
1977
selection = {'I':ignored, '?':unknown, 'V':versioned}
1984
raise errors.BzrCommandError('cannot specify both --from-root'
1988
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1994
if revision is not None or tree is None:
1995
tree = _get_one_revision_tree('ls', revision, branch=branch)
1999
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2000
if fp.startswith(relpath):
2001
fp = osutils.pathjoin(prefix, fp[len(relpath):])
2002
if non_recursive and '/' in fp:
2004
if not all and not selection[fc]:
2006
if kind is not None and fkind != kind:
2008
kindch = entry.kind_character()
2009
outstring = fp + kindch
2011
outstring = '%-8s %s' % (fc, outstring)
2012
if show_ids and fid is not None:
2013
outstring = "%-50s %s" % (outstring, fid)
2014
self.outf.write(outstring + '\n')
2016
self.outf.write(fp + '\0')
2019
self.outf.write(fid)
2020
self.outf.write('\0')
2028
self.outf.write('%-50s %s\n' % (outstring, my_id))
2030
self.outf.write(outstring + '\n')
2035
class cmd_unknowns(Command):
2036
"""List unknown files.
2044
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2045
self.outf.write(osutils.quotefn(f) + '\n')
2048
class cmd_ignore(Command):
2049
"""Ignore specified files or patterns.
2051
See ``bzr help patterns`` for details on the syntax of patterns.
2053
To remove patterns from the ignore list, edit the .bzrignore file.
2054
After adding, editing or deleting that file either indirectly by
2055
using this command or directly by using an editor, be sure to commit
2058
Note: ignore patterns containing shell wildcards must be quoted from
2062
Ignore the top level Makefile::
2064
bzr ignore ./Makefile
2066
Ignore class files in all directories::
2068
bzr ignore "*.class"
2070
Ignore .o files under the lib directory::
2072
bzr ignore "lib/**/*.o"
2074
Ignore .o files under the lib directory::
2076
bzr ignore "RE:lib/.*\.o"
2078
Ignore everything but the "debian" toplevel directory::
2080
bzr ignore "RE:(?!debian/).*"
2083
_see_also = ['status', 'ignored', 'patterns']
2084
takes_args = ['name_pattern*']
2086
Option('old-default-rules',
2087
help='Write out the ignore rules bzr < 0.9 always used.')
2090
def run(self, name_pattern_list=None, old_default_rules=None):
2091
from bzrlib import ignores
2092
if old_default_rules is not None:
2093
# dump the rules and exit
2094
for pattern in ignores.OLD_DEFAULTS:
2097
if not name_pattern_list:
2098
raise errors.BzrCommandError("ignore requires at least one "
2099
"NAME_PATTERN or --old-default-rules")
2100
name_pattern_list = [globbing.normalize_pattern(p)
2101
for p in name_pattern_list]
2102
for name_pattern in name_pattern_list:
2103
if (name_pattern[0] == '/' or
2104
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2105
raise errors.BzrCommandError(
2106
"NAME_PATTERN should not be an absolute path")
2107
tree, relpath = WorkingTree.open_containing(u'.')
2108
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2109
ignored = globbing.Globster(name_pattern_list)
2112
for entry in tree.list_files():
2116
if ignored.match(filename):
2117
matches.append(filename.encode('utf-8'))
2119
if len(matches) > 0:
2120
print "Warning: the following files are version controlled and" \
2121
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2124
class cmd_ignored(Command):
2125
"""List ignored files and the patterns that matched them.
2127
List all the ignored files and the ignore pattern that caused the file to
2130
Alternatively, to list just the files::
2135
encoding_type = 'replace'
2136
_see_also = ['ignore', 'ls']
2140
tree = WorkingTree.open_containing(u'.')[0]
2143
for path, file_class, kind, file_id, entry in tree.list_files():
2144
if file_class != 'I':
2146
## XXX: Slightly inefficient since this was already calculated
2147
pat = tree.is_ignored(path)
2148
self.outf.write('%-50s %s\n' % (path, pat))
2153
class cmd_lookup_revision(Command):
2154
"""Lookup the revision-id from a revision-number
2157
bzr lookup-revision 33
2160
takes_args = ['revno']
2163
def run(self, revno):
2167
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2169
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2172
class cmd_export(Command):
2173
"""Export current or past revision to a destination directory or archive.
2175
If no revision is specified this exports the last committed revision.
2177
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
2178
given, try to find the format with the extension. If no extension
2179
is found exports to a directory (equivalent to --format=dir).
2181
If root is supplied, it will be used as the root directory inside
2182
container formats (tar, zip, etc). If it is not supplied it will default
2183
to the exported filename. The root option has no effect for 'dir' format.
2185
If branch is omitted then the branch containing the current working
2186
directory will be used.
2188
Note: Export of tree with non-ASCII filenames to zip is not supported.
2190
================= =========================
2191
Supported formats Autodetected by extension
2192
================= =========================
2195
tbz2 .tar.bz2, .tbz2
2198
================= =========================
2200
takes_args = ['dest', 'branch_or_subdir?']
2203
help="Type of file to export to.",
2208
help="Name of the root directory inside the exported file."),
2210
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2212
from bzrlib.export import export
2214
if branch_or_subdir is None:
2215
tree = WorkingTree.open_containing(u'.')[0]
2219
b, subdir = Branch.open_containing(branch_or_subdir)
2222
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2224
export(rev_tree, dest, format, root, subdir)
2225
except errors.NoSuchExportFormat, e:
2226
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2229
class cmd_cat(Command):
2230
"""Write the contents of a file as of a given revision to standard output.
2232
If no revision is nominated, the last revision is used.
2234
Note: Take care to redirect standard output when using this command on a
2240
Option('name-from-revision', help='The path name in the old tree.'),
2243
takes_args = ['filename']
2244
encoding_type = 'exact'
2247
def run(self, filename, revision=None, name_from_revision=False):
2248
if revision is not None and len(revision) != 1:
2249
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2250
" one revision specifier")
2251
tree, branch, relpath = \
2252
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2255
return self._run(tree, branch, relpath, filename, revision,
2260
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2262
tree = b.basis_tree()
2263
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2265
cur_file_id = tree.path2id(relpath)
2266
old_file_id = rev_tree.path2id(relpath)
2268
if name_from_revision:
2269
if old_file_id is None:
2270
raise errors.BzrCommandError(
2271
"%r is not present in revision %s" % (
2272
filename, rev_tree.get_revision_id()))
2274
content = rev_tree.get_file_text(old_file_id)
2275
elif cur_file_id is not None:
2276
content = rev_tree.get_file_text(cur_file_id)
2277
elif old_file_id is not None:
2278
content = rev_tree.get_file_text(old_file_id)
2280
raise errors.BzrCommandError(
2281
"%r is not present in revision %s" % (
2282
filename, rev_tree.get_revision_id()))
2283
self.outf.write(content)
2286
class cmd_local_time_offset(Command):
2287
"""Show the offset in seconds from GMT to local time."""
2291
print osutils.local_time_offset()
2295
class cmd_commit(Command):
2296
"""Commit changes into a new revision.
2298
If no arguments are given, the entire tree is committed.
2300
If selected files are specified, only changes to those files are
2301
committed. If a directory is specified then the directory and everything
2302
within it is committed.
2304
When excludes are given, they take precedence over selected files.
2305
For example, too commit only changes within foo, but not changes within
2308
bzr commit foo -x foo/bar
2310
If author of the change is not the same person as the committer, you can
2311
specify the author's name using the --author option. The name should be
2312
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2314
A selected-file commit may fail in some cases where the committed
2315
tree would be invalid. Consider::
2320
bzr commit foo -m "committing foo"
2321
bzr mv foo/bar foo/baz
2324
bzr commit foo/bar -m "committing bar but not baz"
2326
In the example above, the last commit will fail by design. This gives
2327
the user the opportunity to decide whether they want to commit the
2328
rename at the same time, separately first, or not at all. (As a general
2329
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2331
Note: A selected-file commit after a merge is not yet supported.
2333
# TODO: Run hooks on tree to-be-committed, and after commit.
2335
# TODO: Strict commit that fails if there are deleted files.
2336
# (what does "deleted files" mean ??)
2338
# TODO: Give better message for -s, --summary, used by tla people
2340
# XXX: verbose currently does nothing
2342
_see_also = ['bugs', 'uncommit']
2343
takes_args = ['selected*']
2345
ListOption('exclude', type=str, short_name='x',
2346
help="Do not consider changes made to a given path."),
2347
Option('message', type=unicode,
2349
help="Description of the new revision."),
2352
help='Commit even if nothing has changed.'),
2353
Option('file', type=str,
2356
help='Take commit message from this file.'),
2358
help="Refuse to commit if there are unknown "
2359
"files in the working tree."),
2360
ListOption('fixes', type=str,
2361
help="Mark a bug as being fixed by this revision."),
2362
Option('author', type=unicode,
2363
help="Set the author's name, if it's different "
2364
"from the committer."),
2366
help="Perform a local commit in a bound "
2367
"branch. Local commits are not pushed to "
2368
"the master branch until a normal commit "
2372
help='When no message is supplied, show the diff along'
2373
' with the status summary in the message editor.'),
2375
aliases = ['ci', 'checkin']
2377
def _get_bug_fix_properties(self, fixes, branch):
2379
# Configure the properties for bug fixing attributes.
2380
for fixed_bug in fixes:
2381
tokens = fixed_bug.split(':')
2382
if len(tokens) != 2:
2383
raise errors.BzrCommandError(
2384
"Invalid bug %s. Must be in the form of 'tag:id'. "
2385
"Commit refused." % fixed_bug)
2386
tag, bug_id = tokens
2388
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2389
except errors.UnknownBugTrackerAbbreviation:
2390
raise errors.BzrCommandError(
2391
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2392
except errors.MalformedBugIdentifier:
2393
raise errors.BzrCommandError(
2394
"Invalid bug identifier for %s. Commit refused."
2396
properties.append('%s fixed' % bug_url)
2397
return '\n'.join(properties)
2399
def run(self, message=None, file=None, verbose=False, selected_list=None,
2400
unchanged=False, strict=False, local=False, fixes=None,
2401
author=None, show_diff=False, exclude=None):
2402
from bzrlib.errors import (
2407
from bzrlib.msgeditor import (
2408
edit_commit_message_encoded,
2409
generate_commit_message_template,
2410
make_commit_message_template_encoded
2413
# TODO: Need a blackbox test for invoking the external editor; may be
2414
# slightly problematic to run this cross-platform.
2416
# TODO: do more checks that the commit will succeed before
2417
# spending the user's valuable time typing a commit message.
2421
tree, selected_list = tree_files(selected_list)
2422
if selected_list == ['']:
2423
# workaround - commit of root of tree should be exactly the same
2424
# as just default commit in that tree, and succeed even though
2425
# selected-file merge commit is not done yet
2430
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2432
properties['bugs'] = bug_property
2434
if local and not tree.branch.get_bound_location():
2435
raise errors.LocalRequiresBoundBranch()
2437
def get_message(commit_obj):
2438
"""Callback to get commit message"""
2439
my_message = message
2440
if my_message is None and not file:
2441
t = make_commit_message_template_encoded(tree,
2442
selected_list, diff=show_diff,
2443
output_encoding=osutils.get_user_encoding())
2444
start_message = generate_commit_message_template(commit_obj)
2445
my_message = edit_commit_message_encoded(t,
2446
start_message=start_message)
2447
if my_message is None:
2448
raise errors.BzrCommandError("please specify a commit"
2449
" message with either --message or --file")
2450
elif my_message and file:
2451
raise errors.BzrCommandError(
2452
"please specify either --message or --file")
2454
my_message = codecs.open(file, 'rt',
2455
osutils.get_user_encoding()).read()
2456
if my_message == "":
2457
raise errors.BzrCommandError("empty commit message specified")
2461
tree.commit(message_callback=get_message,
2462
specific_files=selected_list,
2463
allow_pointless=unchanged, strict=strict, local=local,
2464
reporter=None, verbose=verbose, revprops=properties,
2466
exclude=safe_relpath_files(tree, exclude))
2467
except PointlessCommit:
2468
# FIXME: This should really happen before the file is read in;
2469
# perhaps prepare the commit; get the message; then actually commit
2470
raise errors.BzrCommandError("no changes to commit."
2471
" use --unchanged to commit anyhow")
2472
except ConflictsInTree:
2473
raise errors.BzrCommandError('Conflicts detected in working '
2474
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2476
except StrictCommitFailed:
2477
raise errors.BzrCommandError("Commit refused because there are"
2478
" unknown files in the working tree.")
2479
except errors.BoundBranchOutOfDate, e:
2480
raise errors.BzrCommandError(str(e) + "\n"
2481
'To commit to master branch, run update and then commit.\n'
2482
'You can also pass --local to commit to continue working '
2486
class cmd_check(Command):
2487
"""Validate working tree structure, branch consistency and repository history.
2489
This command checks various invariants about branch and repository storage
2490
to detect data corruption or bzr bugs.
2492
The working tree and branch checks will only give output if a problem is
2493
detected. The output fields of the repository check are:
2495
revisions: This is just the number of revisions checked. It doesn't
2497
versionedfiles: This is just the number of versionedfiles checked. It
2498
doesn't indicate a problem.
2499
unreferenced ancestors: Texts that are ancestors of other texts, but
2500
are not properly referenced by the revision ancestry. This is a
2501
subtle problem that Bazaar can work around.
2502
unique file texts: This is the total number of unique file contents
2503
seen in the checked revisions. It does not indicate a problem.
2504
repeated file texts: This is the total number of repeated texts seen
2505
in the checked revisions. Texts can be repeated when their file
2506
entries are modified, but the file contents are not. It does not
2509
If no restrictions are specified, all Bazaar data that is found at the given
2510
location will be checked.
2514
Check the tree and branch at 'foo'::
2516
bzr check --tree --branch foo
2518
Check only the repository at 'bar'::
2520
bzr check --repo bar
2522
Check everything at 'baz'::
2527
_see_also = ['reconcile']
2528
takes_args = ['path?']
2529
takes_options = ['verbose',
2530
Option('branch', help="Check the branch related to the"
2531
" current directory."),
2532
Option('repo', help="Check the repository related to the"
2533
" current directory."),
2534
Option('tree', help="Check the working tree related to"
2535
" the current directory.")]
2537
def run(self, path=None, verbose=False, branch=False, repo=False,
2539
from bzrlib.check import check_dwim
2542
if not branch and not repo and not tree:
2543
branch = repo = tree = True
2544
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2547
class cmd_upgrade(Command):
2548
"""Upgrade branch storage to current format.
2550
The check command or bzr developers may sometimes advise you to run
2551
this command. When the default format has changed you may also be warned
2552
during other operations to upgrade.
2555
_see_also = ['check']
2556
takes_args = ['url?']
2558
RegistryOption('format',
2559
help='Upgrade to a specific format. See "bzr help'
2560
' formats" for details.',
2561
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2562
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2563
value_switches=True, title='Branch format'),
2566
def run(self, url='.', format=None):
2567
from bzrlib.upgrade import upgrade
2569
format = bzrdir.format_registry.make_bzrdir('default')
2570
upgrade(url, format)
2573
class cmd_whoami(Command):
2574
"""Show or set bzr user id.
2577
Show the email of the current user::
2581
Set the current user::
2583
bzr whoami "Frank Chu <fchu@example.com>"
2585
takes_options = [ Option('email',
2586
help='Display email address only.'),
2588
help='Set identity for the current branch instead of '
2591
takes_args = ['name?']
2592
encoding_type = 'replace'
2595
def run(self, email=False, branch=False, name=None):
2597
# use branch if we're inside one; otherwise global config
2599
c = Branch.open_containing('.')[0].get_config()
2600
except errors.NotBranchError:
2601
c = config.GlobalConfig()
2603
self.outf.write(c.user_email() + '\n')
2605
self.outf.write(c.username() + '\n')
2608
# display a warning if an email address isn't included in the given name.
2610
config.extract_email_address(name)
2611
except errors.NoEmailInUsername, e:
2612
warning('"%s" does not seem to contain an email address. '
2613
'This is allowed, but not recommended.', name)
2615
# use global config unless --branch given
2617
c = Branch.open_containing('.')[0].get_config()
2619
c = config.GlobalConfig()
2620
c.set_user_option('email', name)
2623
class cmd_nick(Command):
2624
"""Print or set the branch nickname.
2626
If unset, the tree root directory name is used as the nickname.
2627
To print the current nickname, execute with no argument.
2629
Bound branches use the nickname of its master branch unless it is set
2633
_see_also = ['info']
2634
takes_args = ['nickname?']
2635
def run(self, nickname=None):
2636
branch = Branch.open_containing(u'.')[0]
2637
if nickname is None:
2638
self.printme(branch)
2640
branch.nick = nickname
2643
def printme(self, branch):
2647
class cmd_alias(Command):
2648
"""Set/unset and display aliases.
2651
Show the current aliases::
2655
Show the alias specified for 'll'::
2659
Set an alias for 'll'::
2661
bzr alias ll="log --line -r-10..-1"
2663
To remove an alias for 'll'::
2665
bzr alias --remove ll
2668
takes_args = ['name?']
2670
Option('remove', help='Remove the alias.'),
2673
def run(self, name=None, remove=False):
2675
self.remove_alias(name)
2677
self.print_aliases()
2679
equal_pos = name.find('=')
2681
self.print_alias(name)
2683
self.set_alias(name[:equal_pos], name[equal_pos+1:])
2685
def remove_alias(self, alias_name):
2686
if alias_name is None:
2687
raise errors.BzrCommandError(
2688
'bzr alias --remove expects an alias to remove.')
2689
# If alias is not found, print something like:
2690
# unalias: foo: not found
2691
c = config.GlobalConfig()
2692
c.unset_alias(alias_name)
2695
def print_aliases(self):
2696
"""Print out the defined aliases in a similar format to bash."""
2697
aliases = config.GlobalConfig().get_aliases()
2698
for key, value in sorted(aliases.iteritems()):
2699
self.outf.write('bzr alias %s="%s"\n' % (key, value))
2702
def print_alias(self, alias_name):
2703
from bzrlib.commands import get_alias
2704
alias = get_alias(alias_name)
2706
self.outf.write("bzr alias: %s: not found\n" % alias_name)
2709
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2711
def set_alias(self, alias_name, alias_command):
2712
"""Save the alias in the global config."""
2713
c = config.GlobalConfig()
2714
c.set_alias(alias_name, alias_command)
2717
class cmd_selftest(Command):
2718
"""Run internal test suite.
2720
If arguments are given, they are regular expressions that say which tests
2721
should run. Tests matching any expression are run, and other tests are
2724
Alternatively if --first is given, matching tests are run first and then
2725
all other tests are run. This is useful if you have been working in a
2726
particular area, but want to make sure nothing else was broken.
2728
If --exclude is given, tests that match that regular expression are
2729
excluded, regardless of whether they match --first or not.
2731
To help catch accidential dependencies between tests, the --randomize
2732
option is useful. In most cases, the argument used is the word 'now'.
2733
Note that the seed used for the random number generator is displayed
2734
when this option is used. The seed can be explicitly passed as the
2735
argument to this option if required. This enables reproduction of the
2736
actual ordering used if and when an order sensitive problem is encountered.
2738
If --list-only is given, the tests that would be run are listed. This is
2739
useful when combined with --first, --exclude and/or --randomize to
2740
understand their impact. The test harness reports "Listed nn tests in ..."
2741
instead of "Ran nn tests in ..." when list mode is enabled.
2743
If the global option '--no-plugins' is given, plugins are not loaded
2744
before running the selftests. This has two effects: features provided or
2745
modified by plugins will not be tested, and tests provided by plugins will
2748
Tests that need working space on disk use a common temporary directory,
2749
typically inside $TMPDIR or /tmp.
2752
Run only tests relating to 'ignore'::
2756
Disable plugins and list tests as they're run::
2758
bzr --no-plugins selftest -v
2760
# NB: this is used from the class without creating an instance, which is
2761
# why it does not have a self parameter.
2762
def get_transport_type(typestring):
2763
"""Parse and return a transport specifier."""
2764
if typestring == "sftp":
2765
from bzrlib.transport.sftp import SFTPAbsoluteServer
2766
return SFTPAbsoluteServer
2767
if typestring == "memory":
2768
from bzrlib.transport.memory import MemoryServer
2770
if typestring == "fakenfs":
2771
from bzrlib.transport.fakenfs import FakeNFSServer
2772
return FakeNFSServer
2773
msg = "No known transport type %s. Supported types are: sftp\n" %\
2775
raise errors.BzrCommandError(msg)
2778
takes_args = ['testspecs*']
2779
takes_options = ['verbose',
2781
help='Stop when one test fails.',
2785
help='Use a different transport by default '
2786
'throughout the test suite.',
2787
type=get_transport_type),
2789
help='Run the benchmarks rather than selftests.'),
2790
Option('lsprof-timed',
2791
help='Generate lsprof output for benchmarked'
2792
' sections of code.'),
2793
Option('cache-dir', type=str,
2794
help='Cache intermediate benchmark output in this '
2797
help='Run all tests, but run specified tests first.',
2801
help='List the tests instead of running them.'),
2802
Option('randomize', type=str, argname="SEED",
2803
help='Randomize the order of tests using the given'
2804
' seed or "now" for the current time.'),
2805
Option('exclude', type=str, argname="PATTERN",
2807
help='Exclude tests that match this regular'
2809
Option('strict', help='Fail on missing dependencies or '
2811
Option('load-list', type=str, argname='TESTLISTFILE',
2812
help='Load a test id list from a text file.'),
2813
ListOption('debugflag', type=str, short_name='E',
2814
help='Turn on a selftest debug flag.'),
2815
ListOption('starting-with', type=str, argname='TESTID',
2816
param_name='starting_with', short_name='s',
2818
'Load only the tests starting with TESTID.'),
2820
encoding_type = 'replace'
2822
def run(self, testspecs_list=None, verbose=False, one=False,
2823
transport=None, benchmark=None,
2824
lsprof_timed=None, cache_dir=None,
2825
first=False, list_only=False,
2826
randomize=None, exclude=None, strict=False,
2827
load_list=None, debugflag=None, starting_with=None):
2828
from bzrlib.tests import selftest
2829
import bzrlib.benchmarks as benchmarks
2830
from bzrlib.benchmarks import tree_creator
2832
# Make deprecation warnings visible, unless -Werror is set
2833
symbol_versioning.activate_deprecation_warnings(override=False)
2835
if cache_dir is not None:
2836
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2838
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2839
print ' %s (%s python%s)' % (
2841
bzrlib.version_string,
2842
bzrlib._format_version_tuple(sys.version_info),
2845
if testspecs_list is not None:
2846
pattern = '|'.join(testspecs_list)
2850
test_suite_factory = benchmarks.test_suite
2851
# Unless user explicitly asks for quiet, be verbose in benchmarks
2852
verbose = not is_quiet()
2853
# TODO: should possibly lock the history file...
2854
benchfile = open(".perf_history", "at", buffering=1)
2856
test_suite_factory = None
2859
result = selftest(verbose=verbose,
2861
stop_on_failure=one,
2862
transport=transport,
2863
test_suite_factory=test_suite_factory,
2864
lsprof_timed=lsprof_timed,
2865
bench_history=benchfile,
2866
matching_tests_first=first,
2867
list_only=list_only,
2868
random_seed=randomize,
2869
exclude_pattern=exclude,
2871
load_list=load_list,
2872
debug_flags=debugflag,
2873
starting_with=starting_with,
2876
if benchfile is not None:
2879
note('tests passed')
2881
note('tests failed')
2882
return int(not result)
2885
class cmd_version(Command):
2886
"""Show version of bzr."""
2888
encoding_type = 'replace'
2890
Option("short", help="Print just the version number."),
2894
def run(self, short=False):
2895
from bzrlib.version import show_version
2897
self.outf.write(bzrlib.version_string + '\n')
2899
show_version(to_file=self.outf)
2902
class cmd_rocks(Command):
2903
"""Statement of optimism."""
2909
print "It sure does!"
2912
class cmd_find_merge_base(Command):
2913
"""Find and print a base revision for merging two branches."""
2914
# TODO: Options to specify revisions on either side, as if
2915
# merging only part of the history.
2916
takes_args = ['branch', 'other']
2920
def run(self, branch, other):
2921
from bzrlib.revision import ensure_null
2923
branch1 = Branch.open_containing(branch)[0]
2924
branch2 = Branch.open_containing(other)[0]
2929
last1 = ensure_null(branch1.last_revision())
2930
last2 = ensure_null(branch2.last_revision())
2932
graph = branch1.repository.get_graph(branch2.repository)
2933
base_rev_id = graph.find_unique_lca(last1, last2)
2935
print 'merge base is revision %s' % base_rev_id
2942
class cmd_merge(Command):
2943
"""Perform a three-way merge.
2945
The source of the merge can be specified either in the form of a branch,
2946
or in the form of a path to a file containing a merge directive generated
2947
with bzr send. If neither is specified, the default is the upstream branch
2948
or the branch most recently merged using --remember.
2950
When merging a branch, by default the tip will be merged. To pick a different
2951
revision, pass --revision. If you specify two values, the first will be used as
2952
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2953
available revisions, like this is commonly referred to as "cherrypicking".
2955
Revision numbers are always relative to the branch being merged.
2957
By default, bzr will try to merge in all new work from the other
2958
branch, automatically determining an appropriate base. If this
2959
fails, you may need to give an explicit base.
2961
Merge will do its best to combine the changes in two branches, but there
2962
are some kinds of problems only a human can fix. When it encounters those,
2963
it will mark a conflict. A conflict means that you need to fix something,
2964
before you should commit.
2966
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2968
If there is no default branch set, the first merge will set it. After
2969
that, you can omit the branch to use the default. To change the
2970
default, use --remember. The value will only be saved if the remote
2971
location can be accessed.
2973
The results of the merge are placed into the destination working
2974
directory, where they can be reviewed (with bzr diff), tested, and then
2975
committed to record the result of the merge.
2977
merge refuses to run if there are any uncommitted changes, unless
2981
To merge the latest revision from bzr.dev::
2983
bzr merge ../bzr.dev
2985
To merge changes up to and including revision 82 from bzr.dev::
2987
bzr merge -r 82 ../bzr.dev
2989
To merge the changes introduced by 82, without previous changes::
2991
bzr merge -r 81..82 ../bzr.dev
2993
To apply a merge directive contained in in /tmp/merge:
2995
bzr merge /tmp/merge
2998
encoding_type = 'exact'
2999
_see_also = ['update', 'remerge', 'status-flags']
3000
takes_args = ['location?']
3005
help='Merge even if the destination tree has uncommitted changes.'),
3009
Option('show-base', help="Show base revision text in "
3011
Option('uncommitted', help='Apply uncommitted changes'
3012
' from a working copy, instead of branch changes.'),
3013
Option('pull', help='If the destination is already'
3014
' completely merged into the source, pull from the'
3015
' source rather than merging. When this happens,'
3016
' you do not need to commit the result.'),
3018
help='Branch to merge into, '
3019
'rather than the one containing the working directory.',
3023
Option('preview', help='Instead of merging, show a diff of the merge.')
3026
def run(self, location=None, revision=None, force=False,
3027
merge_type=None, show_base=False, reprocess=None, remember=False,
3028
uncommitted=False, pull=False,
3032
if merge_type is None:
3033
merge_type = _mod_merge.Merge3Merger
3035
if directory is None: directory = u'.'
3036
possible_transports = []
3038
allow_pending = True
3039
verified = 'inapplicable'
3040
tree = WorkingTree.open_containing(directory)[0]
3041
change_reporter = delta._ChangeReporter(
3042
unversioned_filter=tree.is_ignored)
3045
pb = ui.ui_factory.nested_progress_bar()
3046
cleanups.append(pb.finished)
3048
cleanups.append(tree.unlock)
3049
if location is not None:
3051
mergeable = bundle.read_mergeable_from_url(location,
3052
possible_transports=possible_transports)
3053
except errors.NotABundle:
3057
raise errors.BzrCommandError('Cannot use --uncommitted'
3058
' with bundles or merge directives.')
3060
if revision is not None:
3061
raise errors.BzrCommandError(
3062
'Cannot use -r with merge directives or bundles')
3063
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3066
if merger is None and uncommitted:
3067
if revision is not None and len(revision) > 0:
3068
raise errors.BzrCommandError('Cannot use --uncommitted and'
3069
' --revision at the same time.')
3070
location = self._select_branch_location(tree, location)[0]
3071
other_tree, other_path = WorkingTree.open_containing(location)
3072
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3074
allow_pending = False
3075
if other_path != '':
3076
merger.interesting_files = [other_path]
3079
merger, allow_pending = self._get_merger_from_branch(tree,
3080
location, revision, remember, possible_transports, pb)
3082
merger.merge_type = merge_type
3083
merger.reprocess = reprocess
3084
merger.show_base = show_base
3085
self.sanity_check_merger(merger)
3086
if (merger.base_rev_id == merger.other_rev_id and
3087
merger.other_rev_id is not None):
3088
note('Nothing to do.')
3091
if merger.interesting_files is not None:
3092
raise errors.BzrCommandError('Cannot pull individual files')
3093
if (merger.base_rev_id == tree.last_revision()):
3094
result = tree.pull(merger.other_branch, False,
3095
merger.other_rev_id)
3096
result.report(self.outf)
3098
merger.check_basis(not force)
3100
return self._do_preview(merger)
3102
return self._do_merge(merger, change_reporter, allow_pending,
3105
for cleanup in reversed(cleanups):
3108
def _do_preview(self, merger):
3109
from bzrlib.diff import show_diff_trees
3110
tree_merger = merger.make_merger()
3111
tt = tree_merger.make_preview_transform()
3113
result_tree = tt.get_preview_tree()
3114
show_diff_trees(merger.this_tree, result_tree, self.outf,
3115
old_label='', new_label='')
3119
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3120
merger.change_reporter = change_reporter
3121
conflict_count = merger.do_merge()
3123
merger.set_pending()
3124
if verified == 'failed':
3125
warning('Preview patch does not match changes')
3126
if conflict_count != 0:
3131
def sanity_check_merger(self, merger):
3132
if (merger.show_base and
3133
not merger.merge_type is _mod_merge.Merge3Merger):
3134
raise errors.BzrCommandError("Show-base is not supported for this"
3135
" merge type. %s" % merger.merge_type)
3136
if merger.reprocess is None:
3137
if merger.show_base:
3138
merger.reprocess = False
3140
# Use reprocess if the merger supports it
3141
merger.reprocess = merger.merge_type.supports_reprocess
3142
if merger.reprocess and not merger.merge_type.supports_reprocess:
3143
raise errors.BzrCommandError("Conflict reduction is not supported"
3144
" for merge type %s." %
3146
if merger.reprocess and merger.show_base:
3147
raise errors.BzrCommandError("Cannot do conflict reduction and"
3150
def _get_merger_from_branch(self, tree, location, revision, remember,
3151
possible_transports, pb):
3152
"""Produce a merger from a location, assuming it refers to a branch."""
3153
from bzrlib.tag import _merge_tags_if_possible
3154
# find the branch locations
3155
other_loc, user_location = self._select_branch_location(tree, location,
3157
if revision is not None and len(revision) == 2:
3158
base_loc, _unused = self._select_branch_location(tree,
3159
location, revision, 0)
3161
base_loc = other_loc
3163
other_branch, other_path = Branch.open_containing(other_loc,
3164
possible_transports)
3165
if base_loc == other_loc:
3166
base_branch = other_branch
3168
base_branch, base_path = Branch.open_containing(base_loc,
3169
possible_transports)
3170
# Find the revision ids
3171
if revision is None or len(revision) < 1 or revision[-1] is None:
3172
other_revision_id = _mod_revision.ensure_null(
3173
other_branch.last_revision())
3175
other_revision_id = revision[-1].as_revision_id(other_branch)
3176
if (revision is not None and len(revision) == 2
3177
and revision[0] is not None):
3178
base_revision_id = revision[0].as_revision_id(base_branch)
3180
base_revision_id = None
3181
# Remember where we merge from
3182
if ((remember or tree.branch.get_submit_branch() is None) and
3183
user_location is not None):
3184
tree.branch.set_submit_branch(other_branch.base)
3185
_merge_tags_if_possible(other_branch, tree.branch)
3186
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3187
other_revision_id, base_revision_id, other_branch, base_branch)
3188
if other_path != '':
3189
allow_pending = False
3190
merger.interesting_files = [other_path]
3192
allow_pending = True
3193
return merger, allow_pending
3195
def _select_branch_location(self, tree, user_location, revision=None,
3197
"""Select a branch location, according to possible inputs.
3199
If provided, branches from ``revision`` are preferred. (Both
3200
``revision`` and ``index`` must be supplied.)
3202
Otherwise, the ``location`` parameter is used. If it is None, then the
3203
``submit`` or ``parent`` location is used, and a note is printed.
3205
:param tree: The working tree to select a branch for merging into
3206
:param location: The location entered by the user
3207
:param revision: The revision parameter to the command
3208
:param index: The index to use for the revision parameter. Negative
3209
indices are permitted.
3210
:return: (selected_location, user_location). The default location
3211
will be the user-entered location.
3213
if (revision is not None and index is not None
3214
and revision[index] is not None):
3215
branch = revision[index].get_branch()
3216
if branch is not None:
3217
return branch, branch
3218
if user_location is None:
3219
location = self._get_remembered(tree, 'Merging from')
3221
location = user_location
3222
return location, user_location
3224
def _get_remembered(self, tree, verb_string):
3225
"""Use tree.branch's parent if none was supplied.
3227
Report if the remembered location was used.
3229
stored_location = tree.branch.get_submit_branch()
3230
stored_location_type = "submit"
3231
if stored_location is None:
3232
stored_location = tree.branch.get_parent()
3233
stored_location_type = "parent"
3234
mutter("%s", stored_location)
3235
if stored_location is None:
3236
raise errors.BzrCommandError("No location specified or remembered")
3237
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3238
note(u"%s remembered %s location %s", verb_string,
3239
stored_location_type, display_url)
3240
return stored_location
3243
class cmd_remerge(Command):
3246
Use this if you want to try a different merge technique while resolving
3247
conflicts. Some merge techniques are better than others, and remerge
3248
lets you try different ones on different files.
3250
The options for remerge have the same meaning and defaults as the ones for
3251
merge. The difference is that remerge can (only) be run when there is a
3252
pending merge, and it lets you specify particular files.
3255
Re-do the merge of all conflicted files, and show the base text in
3256
conflict regions, in addition to the usual THIS and OTHER texts::
3258
bzr remerge --show-base
3260
Re-do the merge of "foobar", using the weave merge algorithm, with
3261
additional processing to reduce the size of conflict regions::
3263
bzr remerge --merge-type weave --reprocess foobar
3265
takes_args = ['file*']
3270
help="Show base revision text in conflicts."),
3273
def run(self, file_list=None, merge_type=None, show_base=False,
3275
if merge_type is None:
3276
merge_type = _mod_merge.Merge3Merger
3277
tree, file_list = tree_files(file_list)
3280
parents = tree.get_parent_ids()
3281
if len(parents) != 2:
3282
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3283
" merges. Not cherrypicking or"
3285
repository = tree.branch.repository
3286
interesting_ids = None
3288
conflicts = tree.conflicts()
3289
if file_list is not None:
3290
interesting_ids = set()
3291
for filename in file_list:
3292
file_id = tree.path2id(filename)
3294
raise errors.NotVersionedError(filename)
3295
interesting_ids.add(file_id)
3296
if tree.kind(file_id) != "directory":
3299
for name, ie in tree.inventory.iter_entries(file_id):
3300
interesting_ids.add(ie.file_id)
3301
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3303
# Remerge only supports resolving contents conflicts
3304
allowed_conflicts = ('text conflict', 'contents conflict')
3305
restore_files = [c.path for c in conflicts
3306
if c.typestring in allowed_conflicts]
3307
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3308
tree.set_conflicts(ConflictList(new_conflicts))
3309
if file_list is not None:
3310
restore_files = file_list
3311
for filename in restore_files:
3313
restore(tree.abspath(filename))
3314
except errors.NotConflicted:
3316
# Disable pending merges, because the file texts we are remerging
3317
# have not had those merges performed. If we use the wrong parents
3318
# list, we imply that the working tree text has seen and rejected
3319
# all the changes from the other tree, when in fact those changes
3320
# have not yet been seen.
3321
pb = ui.ui_factory.nested_progress_bar()
3322
tree.set_parent_ids(parents[:1])
3324
merger = _mod_merge.Merger.from_revision_ids(pb,
3326
merger.interesting_ids = interesting_ids
3327
merger.merge_type = merge_type
3328
merger.show_base = show_base
3329
merger.reprocess = reprocess
3330
conflicts = merger.do_merge()
3332
tree.set_parent_ids(parents)
3342
class cmd_revert(Command):
3343
"""Revert files to a previous revision.
3345
Giving a list of files will revert only those files. Otherwise, all files
3346
will be reverted. If the revision is not specified with '--revision', the
3347
last committed revision is used.
3349
To remove only some changes, without reverting to a prior version, use
3350
merge instead. For example, "merge . --revision -2..-3" will remove the
3351
changes introduced by -2, without affecting the changes introduced by -1.
3352
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3354
By default, any files that have been manually changed will be backed up
3355
first. (Files changed only by merge are not backed up.) Backup files have
3356
'.~#~' appended to their name, where # is a number.
3358
When you provide files, you can use their current pathname or the pathname
3359
from the target revision. So you can use revert to "undelete" a file by
3360
name. If you name a directory, all the contents of that directory will be
3363
Any files that have been newly added since that revision will be deleted,
3364
with a backup kept if appropriate. Directories containing unknown files
3365
will not be deleted.
3367
The working tree contains a list of pending merged revisions, which will
3368
be included as parents in the next commit. Normally, revert clears that
3369
list as well as reverting the files. If any files are specified, revert
3370
leaves the pending merge list alone and reverts only the files. Use "bzr
3371
revert ." in the tree root to revert all files but keep the merge record,
3372
and "bzr revert --forget-merges" to clear the pending merge list without
3373
reverting any files.
3376
_see_also = ['cat', 'export']
3379
Option('no-backup', "Do not save backups of reverted files."),
3380
Option('forget-merges',
3381
'Remove pending merge marker, without changing any files.'),
3383
takes_args = ['file*']
3385
def run(self, revision=None, no_backup=False, file_list=None,
3386
forget_merges=None):
3387
tree, file_list = tree_files(file_list)
3391
tree.set_parent_ids(tree.get_parent_ids()[:1])
3393
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3398
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3399
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3400
pb = ui.ui_factory.nested_progress_bar()
3402
tree.revert(file_list, rev_tree, not no_backup, pb,
3403
report_changes=True)
3408
class cmd_assert_fail(Command):
3409
"""Test reporting of assertion failures"""
3410
# intended just for use in testing
3415
raise AssertionError("always fails")
3418
class cmd_help(Command):
3419
"""Show help on a command or other topic.
3422
_see_also = ['topics']
3424
Option('long', 'Show help on all commands.'),
3426
takes_args = ['topic?']
3427
aliases = ['?', '--help', '-?', '-h']
3430
def run(self, topic=None, long=False):
3432
if topic is None and long:
3434
bzrlib.help.help(topic)
3437
class cmd_shell_complete(Command):
3438
"""Show appropriate completions for context.
3440
For a list of all available commands, say 'bzr shell-complete'.
3442
takes_args = ['context?']
3447
def run(self, context=None):
3448
import shellcomplete
3449
shellcomplete.shellcomplete(context)
3452
class cmd_missing(Command):
3453
"""Show unmerged/unpulled revisions between two branches.
3455
OTHER_BRANCH may be local or remote.
3458
_see_also = ['merge', 'pull']
3459
takes_args = ['other_branch?']
3461
Option('reverse', 'Reverse the order of revisions.'),
3463
'Display changes in the local branch only.'),
3464
Option('this' , 'Same as --mine-only.'),
3465
Option('theirs-only',
3466
'Display changes in the remote branch only.'),
3467
Option('other', 'Same as --theirs-only.'),
3471
custom_help('revision',
3472
help='Filter on local branch revisions. '
3473
'See "help revisionspec" for details.'),
3474
Option('other-revision',
3475
type=_parse_revision_str,
3477
help='Filter on other branch revisions. '
3478
'See "help revisionspec" for details.'),
3479
Option('include-merges', 'Show merged revisions.'),
3481
encoding_type = 'replace'
3484
def run(self, other_branch=None, reverse=False, mine_only=False,
3486
log_format=None, long=False, short=False, line=False,
3487
show_ids=False, verbose=False, this=False, other=False,
3488
include_merges=False, revision=None, other_revision=None):
3489
from bzrlib.missing import find_unmerged, iter_log_revisions
3498
# TODO: We should probably check that we don't have mine-only and
3499
# theirs-only set, but it gets complicated because we also have
3500
# this and other which could be used.
3507
local_branch = Branch.open_containing(u".")[0]
3508
parent = local_branch.get_parent()
3509
if other_branch is None:
3510
other_branch = parent
3511
if other_branch is None:
3512
raise errors.BzrCommandError("No peer location known"
3514
display_url = urlutils.unescape_for_display(parent,
3516
message("Using saved parent location: "
3517
+ display_url + "\n")
3519
remote_branch = Branch.open(other_branch)
3520
if remote_branch.base == local_branch.base:
3521
remote_branch = local_branch
3523
local_revid_range = _revision_range_to_revid_range(
3524
_get_revision_range(revision, local_branch,
3525
self.name()))#Todo singlerev_mode='right'
3527
remote_revid_range = _revision_range_to_revid_range(
3528
_get_revision_range(other_revision,
3529
remote_branch, self.name()))#Todo singlerev_mode='right'
3531
local_branch.lock_read()
3533
remote_branch.lock_read()
3535
local_extra, remote_extra = find_unmerged(
3536
local_branch, remote_branch, restrict,
3537
backward=not reverse,
3538
include_merges=include_merges,
3539
local_revid_range=local_revid_range,
3540
remote_revid_range= remote_revid_range)
3542
if log_format is None:
3543
registry = log.log_formatter_registry
3544
log_format = registry.get_default(local_branch)
3545
lf = log_format(to_file=self.outf,
3547
show_timezone='original')
3550
if local_extra and not theirs_only:
3551
message("You have %d extra revision(s):\n" %
3553
for revision in iter_log_revisions(local_extra,
3554
local_branch.repository,
3556
lf.log_revision(revision)
3557
printed_local = True
3560
printed_local = False
3562
if remote_extra and not mine_only:
3563
if printed_local is True:
3565
message("You are missing %d revision(s):\n" %
3567
for revision in iter_log_revisions(remote_extra,
3568
remote_branch.repository,
3570
lf.log_revision(revision)
3573
if mine_only and not local_extra:
3574
# We checked local, and found nothing extra
3575
message('This branch is up to date.\n')
3576
elif theirs_only and not remote_extra:
3577
# We checked remote, and found nothing extra
3578
message('Other branch is up to date.\n')
3579
elif not (mine_only or theirs_only or local_extra or
3581
# We checked both branches, and neither one had extra
3583
message("Branches are up to date.\n")
3585
remote_branch.unlock()
3587
local_branch.unlock()
3588
if not status_code and parent is None and other_branch is not None:
3589
local_branch.lock_write()
3591
# handle race conditions - a parent might be set while we run.
3592
if local_branch.get_parent() is None:
3593
local_branch.set_parent(remote_branch.base)
3595
local_branch.unlock()
3599
class cmd_pack(Command):
3600
"""Compress the data within a repository."""
3602
_see_also = ['repositories']
3603
takes_args = ['branch_or_repo?']
3605
def run(self, branch_or_repo='.'):
3606
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3608
branch = dir.open_branch()
3609
repository = branch.repository
3610
except errors.NotBranchError:
3611
repository = dir.open_repository()
3615
class cmd_plugins(Command):
3616
"""List the installed plugins.
3618
This command displays the list of installed plugins including
3619
version of plugin and a short description of each.
3621
--verbose shows the path where each plugin is located.
3623
A plugin is an external component for Bazaar that extends the
3624
revision control system, by adding or replacing code in Bazaar.
3625
Plugins can do a variety of things, including overriding commands,
3626
adding new commands, providing additional network transports and
3627
customizing log output.
3629
See the Bazaar web site, http://bazaar-vcs.org, for further
3630
information on plugins including where to find them and how to
3631
install them. Instructions are also provided there on how to
3632
write new plugins using the Python programming language.
3634
takes_options = ['verbose']
3637
def run(self, verbose=False):
3638
import bzrlib.plugin
3639
from inspect import getdoc
3641
for name, plugin in bzrlib.plugin.plugins().items():
3642
version = plugin.__version__
3643
if version == 'unknown':
3645
name_ver = '%s %s' % (name, version)
3646
d = getdoc(plugin.module)
3648
doc = d.split('\n')[0]
3650
doc = '(no description)'
3651
result.append((name_ver, doc, plugin.path()))
3652
for name_ver, doc, path in sorted(result):
3660
class cmd_testament(Command):
3661
"""Show testament (signing-form) of a revision."""
3664
Option('long', help='Produce long-format testament.'),
3666
help='Produce a strict-format testament.')]
3667
takes_args = ['branch?']
3669
def run(self, branch=u'.', revision=None, long=False, strict=False):
3670
from bzrlib.testament import Testament, StrictTestament
3672
testament_class = StrictTestament
3674
testament_class = Testament
3676
b = Branch.open_containing(branch)[0]
3678
b = Branch.open(branch)
3681
if revision is None:
3682
rev_id = b.last_revision()
3684
rev_id = revision[0].as_revision_id(b)
3685
t = testament_class.from_revision(b.repository, rev_id)
3687
sys.stdout.writelines(t.as_text_lines())
3689
sys.stdout.write(t.as_short_text())
3694
class cmd_annotate(Command):
3695
"""Show the origin of each line in a file.
3697
This prints out the given file with an annotation on the left side
3698
indicating which revision, author and date introduced the change.
3700
If the origin is the same for a run of consecutive lines, it is
3701
shown only at the top, unless the --all option is given.
3703
# TODO: annotate directories; showing when each file was last changed
3704
# TODO: if the working copy is modified, show annotations on that
3705
# with new uncommitted lines marked
3706
aliases = ['ann', 'blame', 'praise']
3707
takes_args = ['filename']
3708
takes_options = [Option('all', help='Show annotations on all lines.'),
3709
Option('long', help='Show commit date in annotations.'),
3713
encoding_type = 'exact'
3716
def run(self, filename, all=False, long=False, revision=None,
3718
from bzrlib.annotate import annotate_file, annotate_file_tree
3719
wt, branch, relpath = \
3720
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3726
tree = _get_one_revision_tree('annotate', revision, branch=branch)
3728
file_id = wt.path2id(relpath)
3730
file_id = tree.path2id(relpath)
3732
raise errors.NotVersionedError(filename)
3733
file_version = tree.inventory[file_id].revision
3734
if wt is not None and revision is None:
3735
# If there is a tree and we're not annotating historical
3736
# versions, annotate the working tree's content.
3737
annotate_file_tree(wt, file_id, self.outf, long, all,
3740
annotate_file(branch, file_version, file_id, long, all, self.outf,
3749
class cmd_re_sign(Command):
3750
"""Create a digital signature for an existing revision."""
3751
# TODO be able to replace existing ones.
3753
hidden = True # is this right ?
3754
takes_args = ['revision_id*']
3755
takes_options = ['revision']
3757
def run(self, revision_id_list=None, revision=None):
3758
if revision_id_list is not None and revision is not None:
3759
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3760
if revision_id_list is None and revision is None:
3761
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3762
b = WorkingTree.open_containing(u'.')[0].branch
3765
return self._run(b, revision_id_list, revision)
3769
def _run(self, b, revision_id_list, revision):
3770
import bzrlib.gpg as gpg
3771
gpg_strategy = gpg.GPGStrategy(b.get_config())
3772
if revision_id_list is not None:
3773
b.repository.start_write_group()
3775
for revision_id in revision_id_list:
3776
b.repository.sign_revision(revision_id, gpg_strategy)
3778
b.repository.abort_write_group()
3781
b.repository.commit_write_group()
3782
elif revision is not None:
3783
if len(revision) == 1:
3784
revno, rev_id = revision[0].in_history(b)
3785
b.repository.start_write_group()
3787
b.repository.sign_revision(rev_id, gpg_strategy)
3789
b.repository.abort_write_group()
3792
b.repository.commit_write_group()
3793
elif len(revision) == 2:
3794
# are they both on rh- if so we can walk between them
3795
# might be nice to have a range helper for arbitrary
3796
# revision paths. hmm.
3797
from_revno, from_revid = revision[0].in_history(b)
3798
to_revno, to_revid = revision[1].in_history(b)
3799
if to_revid is None:
3800
to_revno = b.revno()
3801
if from_revno is None or to_revno is None:
3802
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3803
b.repository.start_write_group()
3805
for revno in range(from_revno, to_revno + 1):
3806
b.repository.sign_revision(b.get_rev_id(revno),
3809
b.repository.abort_write_group()
3812
b.repository.commit_write_group()
3814
raise errors.BzrCommandError('Please supply either one revision, or a range.')
3817
class cmd_bind(Command):
3818
"""Convert the current branch into a checkout of the supplied branch.
3820
Once converted into a checkout, commits must succeed on the master branch
3821
before they will be applied to the local branch.
3823
Bound branches use the nickname of its master branch unless it is set
3824
locally, in which case binding will update the the local nickname to be
3828
_see_also = ['checkouts', 'unbind']
3829
takes_args = ['location?']
3832
def run(self, location=None):
3833
b, relpath = Branch.open_containing(u'.')
3834
if location is None:
3836
location = b.get_old_bound_location()
3837
except errors.UpgradeRequired:
3838
raise errors.BzrCommandError('No location supplied. '
3839
'This format does not remember old locations.')
3841
if location is None:
3842
raise errors.BzrCommandError('No location supplied and no '
3843
'previous location known')
3844
b_other = Branch.open(location)
3847
except errors.DivergedBranches:
3848
raise errors.BzrCommandError('These branches have diverged.'
3849
' Try merging, and then bind again.')
3850
if b.get_config().has_explicit_nickname():
3851
b.nick = b_other.nick
3854
class cmd_unbind(Command):
3855
"""Convert the current checkout into a regular branch.
3857
After unbinding, the local branch is considered independent and subsequent
3858
commits will be local only.
3861
_see_also = ['checkouts', 'bind']
3866
b, relpath = Branch.open_containing(u'.')
3868
raise errors.BzrCommandError('Local branch is not bound')
3871
class cmd_uncommit(Command):
3872
"""Remove the last committed revision.
3874
--verbose will print out what is being removed.
3875
--dry-run will go through all the motions, but not actually
3878
If --revision is specified, uncommit revisions to leave the branch at the
3879
specified revision. For example, "bzr uncommit -r 15" will leave the
3880
branch at revision 15.
3882
Uncommit leaves the working tree ready for a new commit. The only change
3883
it may make is to restore any pending merges that were present before
3887
# TODO: jam 20060108 Add an option to allow uncommit to remove
3888
# unreferenced information in 'branch-as-repository' branches.
3889
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3890
# information in shared branches as well.
3891
_see_also = ['commit']
3892
takes_options = ['verbose', 'revision',
3893
Option('dry-run', help='Don\'t actually make changes.'),
3894
Option('force', help='Say yes to all questions.'),
3896
help="Only remove the commits from the local branch"
3897
" when in a checkout."
3900
takes_args = ['location?']
3902
encoding_type = 'replace'
3904
def run(self, location=None,
3905
dry_run=False, verbose=False,
3906
revision=None, force=False, local=False):
3907
if location is None:
3909
control, relpath = bzrdir.BzrDir.open_containing(location)
3911
tree = control.open_workingtree()
3913
except (errors.NoWorkingTree, errors.NotLocalUrl):
3915
b = control.open_branch()
3917
if tree is not None:
3922
return self._run(b, tree, dry_run, verbose, revision, force,
3925
if tree is not None:
3930
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3931
from bzrlib.log import log_formatter, show_log
3932
from bzrlib.uncommit import uncommit
3934
last_revno, last_rev_id = b.last_revision_info()
3937
if revision is None:
3939
rev_id = last_rev_id
3941
# 'bzr uncommit -r 10' actually means uncommit
3942
# so that the final tree is at revno 10.
3943
# but bzrlib.uncommit.uncommit() actually uncommits
3944
# the revisions that are supplied.
3945
# So we need to offset it by one
3946
revno = revision[0].in_history(b).revno + 1
3947
if revno <= last_revno:
3948
rev_id = b.get_rev_id(revno)
3950
if rev_id is None or _mod_revision.is_null(rev_id):
3951
self.outf.write('No revisions to uncommit.\n')
3954
lf = log_formatter('short',
3956
show_timezone='original')
3961
direction='forward',
3962
start_revision=revno,
3963
end_revision=last_revno)
3966
print 'Dry-run, pretending to remove the above revisions.'
3968
val = raw_input('Press <enter> to continue')
3970
print 'The above revision(s) will be removed.'
3972
val = raw_input('Are you sure [y/N]? ')
3973
if val.lower() not in ('y', 'yes'):
3977
mutter('Uncommitting from {%s} to {%s}',
3978
last_rev_id, rev_id)
3979
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3980
revno=revno, local=local)
3981
note('You can restore the old tip by running:\n'
3982
' bzr pull . -r revid:%s', last_rev_id)
3985
class cmd_break_lock(Command):
3986
"""Break a dead lock on a repository, branch or working directory.
3988
CAUTION: Locks should only be broken when you are sure that the process
3989
holding the lock has been stopped.
3991
You can get information on what locks are open via the 'bzr info' command.
3996
takes_args = ['location?']
3998
def run(self, location=None, show=False):
3999
if location is None:
4001
control, relpath = bzrdir.BzrDir.open_containing(location)
4003
control.break_lock()
4004
except NotImplementedError:
4008
class cmd_wait_until_signalled(Command):
4009
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4011
This just prints a line to signal when it is ready, then blocks on stdin.
4017
sys.stdout.write("running\n")
4019
sys.stdin.readline()
4022
class cmd_serve(Command):
4023
"""Run the bzr server."""
4025
aliases = ['server']
4029
help='Serve on stdin/out for use from inetd or sshd.'),
4031
help='Listen for connections on nominated port of the form '
4032
'[hostname:]portnumber. Passing 0 as the port number will '
4033
'result in a dynamically allocated port. The default port is '
4037
help='Serve contents of this directory.',
4039
Option('allow-writes',
4040
help='By default the server is a readonly server. Supplying '
4041
'--allow-writes enables write access to the contents of '
4042
'the served directory and below.'
4046
def run(self, port=None, inet=False, directory=None, allow_writes=False):
4047
from bzrlib import lockdir
4048
from bzrlib.smart import medium, server
4049
from bzrlib.transport import get_transport
4050
from bzrlib.transport.chroot import ChrootServer
4051
if directory is None:
4052
directory = os.getcwd()
4053
url = urlutils.local_path_to_url(directory)
4054
if not allow_writes:
4055
url = 'readonly+' + url
4056
chroot_server = ChrootServer(get_transport(url))
4057
chroot_server.setUp()
4058
t = get_transport(chroot_server.get_url())
4060
smart_server = medium.SmartServerPipeStreamMedium(
4061
sys.stdin, sys.stdout, t)
4063
host = medium.BZR_DEFAULT_INTERFACE
4065
port = medium.BZR_DEFAULT_PORT
4068
host, port = port.split(':')
4070
smart_server = server.SmartTCPServer(t, host=host, port=port)
4071
print 'listening on port: ', smart_server.port
4073
# for the duration of this server, no UI output is permitted.
4074
# note that this may cause problems with blackbox tests. This should
4075
# be changed with care though, as we dont want to use bandwidth sending
4076
# progress over stderr to smart server clients!
4077
old_factory = ui.ui_factory
4078
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4080
ui.ui_factory = ui.SilentUIFactory()
4081
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4082
smart_server.serve()
4084
ui.ui_factory = old_factory
4085
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4088
class cmd_join(Command):
4089
"""Combine a subtree into its containing tree.
4091
This command is for experimental use only. It requires the target tree
4092
to be in dirstate-with-subtree format, which cannot be converted into
4095
The TREE argument should be an independent tree, inside another tree, but
4096
not part of it. (Such trees can be produced by "bzr split", but also by
4097
running "bzr branch" with the target inside a tree.)
4099
The result is a combined tree, with the subtree no longer an independant
4100
part. This is marked as a merge of the subtree into the containing tree,
4101
and all history is preserved.
4103
If --reference is specified, the subtree retains its independence. It can
4104
be branched by itself, and can be part of multiple projects at the same
4105
time. But operations performed in the containing tree, such as commit
4106
and merge, will recurse into the subtree.
4109
_see_also = ['split']
4110
takes_args = ['tree']
4112
Option('reference', help='Join by reference.'),
4116
def run(self, tree, reference=False):
4117
sub_tree = WorkingTree.open(tree)
4118
parent_dir = osutils.dirname(sub_tree.basedir)
4119
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4120
repo = containing_tree.branch.repository
4121
if not repo.supports_rich_root():
4122
raise errors.BzrCommandError(
4123
"Can't join trees because %s doesn't support rich root data.\n"
4124
"You can use bzr upgrade on the repository."
4128
containing_tree.add_reference(sub_tree)
4129
except errors.BadReferenceTarget, e:
4130
# XXX: Would be better to just raise a nicely printable
4131
# exception from the real origin. Also below. mbp 20070306
4132
raise errors.BzrCommandError("Cannot join %s. %s" %
4136
containing_tree.subsume(sub_tree)
4137
except errors.BadSubsumeSource, e:
4138
raise errors.BzrCommandError("Cannot join %s. %s" %
4142
class cmd_split(Command):
4143
"""Split a subdirectory of a tree into a separate tree.
4145
This command will produce a target tree in a format that supports
4146
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4147
converted into earlier formats like 'dirstate-tags'.
4149
The TREE argument should be a subdirectory of a working tree. That
4150
subdirectory will be converted into an independent tree, with its own
4151
branch. Commits in the top-level tree will not apply to the new subtree.
4154
# join is not un-hidden yet
4155
#_see_also = ['join']
4156
takes_args = ['tree']
4158
def run(self, tree):
4159
containing_tree, subdir = WorkingTree.open_containing(tree)
4160
sub_id = containing_tree.path2id(subdir)
4162
raise errors.NotVersionedError(subdir)
4164
containing_tree.extract(sub_id)
4165
except errors.RootNotRich:
4166
raise errors.UpgradeRequired(containing_tree.branch.base)
4169
class cmd_merge_directive(Command):
4170
"""Generate a merge directive for auto-merge tools.
4172
A directive requests a merge to be performed, and also provides all the
4173
information necessary to do so. This means it must either include a
4174
revision bundle, or the location of a branch containing the desired
4177
A submit branch (the location to merge into) must be supplied the first
4178
time the command is issued. After it has been supplied once, it will
4179
be remembered as the default.
4181
A public branch is optional if a revision bundle is supplied, but required
4182
if --diff or --plain is specified. It will be remembered as the default
4183
after the first use.
4186
takes_args = ['submit_branch?', 'public_branch?']
4190
_see_also = ['send']
4193
RegistryOption.from_kwargs('patch-type',
4194
'The type of patch to include in the directive.',
4196
value_switches=True,
4198
bundle='Bazaar revision bundle (default).',
4199
diff='Normal unified diff.',
4200
plain='No patch, just directive.'),
4201
Option('sign', help='GPG-sign the directive.'), 'revision',
4202
Option('mail-to', type=str,
4203
help='Instead of printing the directive, email to this address.'),
4204
Option('message', type=str, short_name='m',
4205
help='Message to use when committing this merge.')
4208
encoding_type = 'exact'
4210
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4211
sign=False, revision=None, mail_to=None, message=None):
4212
from bzrlib.revision import ensure_null, NULL_REVISION
4213
include_patch, include_bundle = {
4214
'plain': (False, False),
4215
'diff': (True, False),
4216
'bundle': (True, True),
4218
branch = Branch.open('.')
4219
stored_submit_branch = branch.get_submit_branch()
4220
if submit_branch is None:
4221
submit_branch = stored_submit_branch
4223
if stored_submit_branch is None:
4224
branch.set_submit_branch(submit_branch)
4225
if submit_branch is None:
4226
submit_branch = branch.get_parent()
4227
if submit_branch is None:
4228
raise errors.BzrCommandError('No submit branch specified or known')
4230
stored_public_branch = branch.get_public_branch()
4231
if public_branch is None:
4232
public_branch = stored_public_branch
4233
elif stored_public_branch is None:
4234
branch.set_public_branch(public_branch)
4235
if not include_bundle and public_branch is None:
4236
raise errors.BzrCommandError('No public branch specified or'
4238
base_revision_id = None
4239
if revision is not None:
4240
if len(revision) > 2:
4241
raise errors.BzrCommandError('bzr merge-directive takes '
4242
'at most two one revision identifiers')
4243
revision_id = revision[-1].as_revision_id(branch)
4244
if len(revision) == 2:
4245
base_revision_id = revision[0].as_revision_id(branch)
4247
revision_id = branch.last_revision()
4248
revision_id = ensure_null(revision_id)
4249
if revision_id == NULL_REVISION:
4250
raise errors.BzrCommandError('No revisions to bundle.')
4251
directive = merge_directive.MergeDirective2.from_objects(
4252
branch.repository, revision_id, time.time(),
4253
osutils.local_time_offset(), submit_branch,
4254
public_branch=public_branch, include_patch=include_patch,
4255
include_bundle=include_bundle, message=message,
4256
base_revision_id=base_revision_id)
4259
self.outf.write(directive.to_signed(branch))
4261
self.outf.writelines(directive.to_lines())
4263
message = directive.to_email(mail_to, branch, sign)
4264
s = SMTPConnection(branch.get_config())
4265
s.send_email(message)
4268
class cmd_send(Command):
4269
"""Mail or create a merge-directive for submitting changes.
4271
A merge directive provides many things needed for requesting merges:
4273
* A machine-readable description of the merge to perform
4275
* An optional patch that is a preview of the changes requested
4277
* An optional bundle of revision data, so that the changes can be applied
4278
directly from the merge directive, without retrieving data from a
4281
If --no-bundle is specified, then public_branch is needed (and must be
4282
up-to-date), so that the receiver can perform the merge using the
4283
public_branch. The public_branch is always included if known, so that
4284
people can check it later.
4286
The submit branch defaults to the parent, but can be overridden. Both
4287
submit branch and public branch will be remembered if supplied.
4289
If a public_branch is known for the submit_branch, that public submit
4290
branch is used in the merge instructions. This means that a local mirror
4291
can be used as your actual submit branch, once you have set public_branch
4294
Mail is sent using your preferred mail program. This should be transparent
4295
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4296
If the preferred client can't be found (or used), your editor will be used.
4298
To use a specific mail program, set the mail_client configuration option.
4299
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4300
specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4301
generic options are "default", "editor", "emacsclient", "mapi", and
4302
"xdg-email". Plugins may also add supported clients.
4304
If mail is being sent, a to address is required. This can be supplied
4305
either on the commandline, by setting the submit_to configuration
4306
option in the branch itself or the child_submit_to configuration option
4307
in the submit branch.
4309
Two formats are currently supported: "4" uses revision bundle format 4 and
4310
merge directive format 2. It is significantly faster and smaller than
4311
older formats. It is compatible with Bazaar 0.19 and later. It is the
4312
default. "0.9" uses revision bundle format 0.9 and merge directive
4313
format 1. It is compatible with Bazaar 0.12 - 0.18.
4315
Merge directives are applied using the merge command or the pull command.
4318
encoding_type = 'exact'
4320
_see_also = ['merge', 'pull']
4322
takes_args = ['submit_branch?', 'public_branch?']
4326
help='Do not include a bundle in the merge directive.'),
4327
Option('no-patch', help='Do not include a preview patch in the merge'
4330
help='Remember submit and public branch.'),
4332
help='Branch to generate the submission from, '
4333
'rather than the one containing the working directory.',
4336
Option('output', short_name='o',
4337
help='Write merge directive to this file; '
4338
'use - for stdout.',
4340
Option('mail-to', help='Mail the request to this address.',
4344
RegistryOption.from_kwargs('format',
4345
'Use the specified output format.',
4346
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4347
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4350
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4351
no_patch=False, revision=None, remember=False, output=None,
4352
format='4', mail_to=None, message=None, **kwargs):
4353
return self._run(submit_branch, revision, public_branch, remember,
4354
format, no_bundle, no_patch, output,
4355
kwargs.get('from', '.'), mail_to, message)
4357
def _run(self, submit_branch, revision, public_branch, remember, format,
4358
no_bundle, no_patch, output, from_, mail_to, message):
4359
from bzrlib.revision import NULL_REVISION
4360
branch = Branch.open_containing(from_)[0]
4362
outfile = cStringIO.StringIO()
4366
outfile = open(output, 'wb')
4367
# we may need to write data into branch's repository to calculate
4372
config = branch.get_config()
4374
mail_to = config.get_user_option('submit_to')
4375
mail_client = config.get_mail_client()
4376
if remember and submit_branch is None:
4377
raise errors.BzrCommandError(
4378
'--remember requires a branch to be specified.')
4379
stored_submit_branch = branch.get_submit_branch()
4380
remembered_submit_branch = None
4381
if submit_branch is None:
4382
submit_branch = stored_submit_branch
4383
remembered_submit_branch = "submit"
4385
if stored_submit_branch is None or remember:
4386
branch.set_submit_branch(submit_branch)
4387
if submit_branch is None:
4388
submit_branch = branch.get_parent()
4389
remembered_submit_branch = "parent"
4390
if submit_branch is None:
4391
raise errors.BzrCommandError('No submit branch known or'
4393
if remembered_submit_branch is not None:
4394
note('Using saved %s location "%s" to determine what '
4395
'changes to submit.', remembered_submit_branch,
4399
submit_config = Branch.open(submit_branch).get_config()
4400
mail_to = submit_config.get_user_option("child_submit_to")
4402
stored_public_branch = branch.get_public_branch()
4403
if public_branch is None:
4404
public_branch = stored_public_branch
4405
elif stored_public_branch is None or remember:
4406
branch.set_public_branch(public_branch)
4407
if no_bundle and public_branch is None:
4408
raise errors.BzrCommandError('No public branch specified or'
4410
base_revision_id = None
4412
if revision is not None:
4413
if len(revision) > 2:
4414
raise errors.BzrCommandError('bzr send takes '
4415
'at most two one revision identifiers')
4416
revision_id = revision[-1].as_revision_id(branch)
4417
if len(revision) == 2:
4418
base_revision_id = revision[0].as_revision_id(branch)
4419
if revision_id is None:
4420
revision_id = branch.last_revision()
4421
if revision_id == NULL_REVISION:
4422
raise errors.BzrCommandError('No revisions to submit.')
4424
directive = merge_directive.MergeDirective2.from_objects(
4425
branch.repository, revision_id, time.time(),
4426
osutils.local_time_offset(), submit_branch,
4427
public_branch=public_branch, include_patch=not no_patch,
4428
include_bundle=not no_bundle, message=message,
4429
base_revision_id=base_revision_id)
4430
elif format == '0.9':
4433
patch_type = 'bundle'
4435
raise errors.BzrCommandError('Format 0.9 does not'
4436
' permit bundle with no patch')
4442
directive = merge_directive.MergeDirective.from_objects(
4443
branch.repository, revision_id, time.time(),
4444
osutils.local_time_offset(), submit_branch,
4445
public_branch=public_branch, patch_type=patch_type,
4448
outfile.writelines(directive.to_lines())
4450
subject = '[MERGE] '
4451
if message is not None:
4454
revision = branch.repository.get_revision(revision_id)
4455
subject += revision.get_summary()
4456
basename = directive.get_disk_name(branch)
4457
mail_client.compose_merge_request(mail_to, subject,
4458
outfile.getvalue(), basename)
4465
class cmd_bundle_revisions(cmd_send):
4467
"""Create a merge-directive for submitting changes.
4469
A merge directive provides many things needed for requesting merges:
4471
* A machine-readable description of the merge to perform
4473
* An optional patch that is a preview of the changes requested
4475
* An optional bundle of revision data, so that the changes can be applied
4476
directly from the merge directive, without retrieving data from a
4479
If --no-bundle is specified, then public_branch is needed (and must be
4480
up-to-date), so that the receiver can perform the merge using the
4481
public_branch. The public_branch is always included if known, so that
4482
people can check it later.
4484
The submit branch defaults to the parent, but can be overridden. Both
4485
submit branch and public branch will be remembered if supplied.
4487
If a public_branch is known for the submit_branch, that public submit
4488
branch is used in the merge instructions. This means that a local mirror
4489
can be used as your actual submit branch, once you have set public_branch
4492
Two formats are currently supported: "4" uses revision bundle format 4 and
4493
merge directive format 2. It is significantly faster and smaller than
4494
older formats. It is compatible with Bazaar 0.19 and later. It is the
4495
default. "0.9" uses revision bundle format 0.9 and merge directive
4496
format 1. It is compatible with Bazaar 0.12 - 0.18.
4501
help='Do not include a bundle in the merge directive.'),
4502
Option('no-patch', help='Do not include a preview patch in the merge'
4505
help='Remember submit and public branch.'),
4507
help='Branch to generate the submission from, '
4508
'rather than the one containing the working directory.',
4511
Option('output', short_name='o', help='Write directive to this file.',
4514
RegistryOption.from_kwargs('format',
4515
'Use the specified output format.',
4516
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4517
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4519
aliases = ['bundle']
4521
_see_also = ['send', 'merge']
4525
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4526
no_patch=False, revision=None, remember=False, output=None,
4527
format='4', **kwargs):
4530
return self._run(submit_branch, revision, public_branch, remember,
4531
format, no_bundle, no_patch, output,
4532
kwargs.get('from', '.'), None, None)
4535
class cmd_tag(Command):
4536
"""Create, remove or modify a tag naming a revision.
4538
Tags give human-meaningful names to revisions. Commands that take a -r
4539
(--revision) option can be given -rtag:X, where X is any previously
4542
Tags are stored in the branch. Tags are copied from one branch to another
4543
along when you branch, push, pull or merge.
4545
It is an error to give a tag name that already exists unless you pass
4546
--force, in which case the tag is moved to point to the new revision.
4548
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4549
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4552
_see_also = ['commit', 'tags']
4553
takes_args = ['tag_name']
4556
help='Delete this tag rather than placing it.',
4559
help='Branch in which to place the tag.',
4564
help='Replace existing tags.',
4569
def run(self, tag_name,
4575
branch, relpath = Branch.open_containing(directory)
4579
branch.tags.delete_tag(tag_name)
4580
self.outf.write('Deleted tag %s.\n' % tag_name)
4583
if len(revision) != 1:
4584
raise errors.BzrCommandError(
4585
"Tags can only be placed on a single revision, "
4587
revision_id = revision[0].as_revision_id(branch)
4589
revision_id = branch.last_revision()
4590
if (not force) and branch.tags.has_tag(tag_name):
4591
raise errors.TagAlreadyExists(tag_name)
4592
branch.tags.set_tag(tag_name, revision_id)
4593
self.outf.write('Created tag %s.\n' % tag_name)
4598
class cmd_tags(Command):
4601
This command shows a table of tag names and the revisions they reference.
4607
help='Branch whose tags should be displayed.',
4611
RegistryOption.from_kwargs('sort',
4612
'Sort tags by different criteria.', title='Sorting',
4613
alpha='Sort tags lexicographically (default).',
4614
time='Sort tags chronologically.',
4627
branch, relpath = Branch.open_containing(directory)
4629
tags = branch.tags.get_tag_dict().items()
4636
graph = branch.repository.get_graph()
4637
rev1, rev2 = _get_revision_range(revision, branch, self.name())
4638
revid1, revid2 = rev1.rev_id, rev2.rev_id
4639
# only show revisions between revid1 and revid2 (inclusive)
4640
tags = [(tag, revid) for tag, revid in tags if
4641
graph.is_between(revid, revid1, revid2)]
4646
elif sort == 'time':
4648
for tag, revid in tags:
4650
revobj = branch.repository.get_revision(revid)
4651
except errors.NoSuchRevision:
4652
timestamp = sys.maxint # place them at the end
4654
timestamp = revobj.timestamp
4655
timestamps[revid] = timestamp
4656
tags.sort(key=lambda x: timestamps[x[1]])
4658
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4659
revno_map = branch.get_revision_id_to_revno_map()
4660
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4661
for tag, revid in tags ]
4662
for tag, revspec in tags:
4663
self.outf.write('%-20s %s\n' % (tag, revspec))
4666
class cmd_reconfigure(Command):
4667
"""Reconfigure the type of a bzr directory.
4669
A target configuration must be specified.
4671
For checkouts, the bind-to location will be auto-detected if not specified.
4672
The order of preference is
4673
1. For a lightweight checkout, the current bound location.
4674
2. For branches that used to be checkouts, the previously-bound location.
4675
3. The push location.
4676
4. The parent location.
4677
If none of these is available, --bind-to must be specified.
4680
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4681
takes_args = ['location?']
4682
takes_options = [RegistryOption.from_kwargs('target_type',
4683
title='Target type',
4684
help='The type to reconfigure the directory to.',
4685
value_switches=True, enum_switch=False,
4686
branch='Reconfigure to be an unbound branch '
4687
'with no working tree.',
4688
tree='Reconfigure to be an unbound branch '
4689
'with a working tree.',
4690
checkout='Reconfigure to be a bound branch '
4691
'with a working tree.',
4692
lightweight_checkout='Reconfigure to be a lightweight'
4693
' checkout (with no local history).',
4694
standalone='Reconfigure to be a standalone branch '
4695
'(i.e. stop using shared repository).',
4696
use_shared='Reconfigure to use a shared repository.'),
4697
Option('bind-to', help='Branch to bind checkout to.',
4700
help='Perform reconfiguration even if local changes'
4704
def run(self, location=None, target_type=None, bind_to=None, force=False):
4705
directory = bzrdir.BzrDir.open(location)
4706
if target_type is None:
4707
raise errors.BzrCommandError('No target configuration specified')
4708
elif target_type == 'branch':
4709
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4710
elif target_type == 'tree':
4711
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4712
elif target_type == 'checkout':
4713
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4715
elif target_type == 'lightweight-checkout':
4716
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4718
elif target_type == 'use-shared':
4719
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4720
elif target_type == 'standalone':
4721
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4722
reconfiguration.apply(force)
4725
class cmd_switch(Command):
4726
"""Set the branch of a checkout and update.
4728
For lightweight checkouts, this changes the branch being referenced.
4729
For heavyweight checkouts, this checks that there are no local commits
4730
versus the current bound branch, then it makes the local branch a mirror
4731
of the new location and binds to it.
4733
In both cases, the working tree is updated and uncommitted changes
4734
are merged. The user can commit or revert these as they desire.
4736
Pending merges need to be committed or reverted before using switch.
4738
The path to the branch to switch to can be specified relative to the parent
4739
directory of the current branch. For example, if you are currently in a
4740
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4743
Bound branches use the nickname of its master branch unless it is set
4744
locally, in which case switching will update the the local nickname to be
4748
takes_args = ['to_location']
4749
takes_options = [Option('force',
4750
help='Switch even if local commits will be lost.')
4753
def run(self, to_location, force=False):
4754
from bzrlib import switch
4756
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4757
branch = control_dir.open_branch()
4759
to_branch = Branch.open(to_location)
4760
except errors.NotBranchError:
4761
this_branch = control_dir.open_branch()
4762
# This may be a heavy checkout, where we want the master branch
4763
this_url = this_branch.get_bound_location()
4764
# If not, use a local sibling
4765
if this_url is None:
4766
this_url = this_branch.base
4767
to_branch = Branch.open(
4768
urlutils.join(this_url, '..', to_location))
4769
switch.switch(control_dir, to_branch, force)
4770
if branch.get_config().has_explicit_nickname():
4771
branch = control_dir.open_branch() #get the new branch!
4772
branch.nick = to_branch.nick
4773
note('Switched to branch: %s',
4774
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4777
class cmd_hooks(Command):
4778
"""Show a branch's currently registered hooks.
4782
takes_args = ['path?']
4784
def run(self, path=None):
4787
branch_hooks = Branch.open(path).hooks
4788
for hook_type in branch_hooks:
4789
hooks = branch_hooks[hook_type]
4790
self.outf.write("%s:\n" % (hook_type,))
4793
self.outf.write(" %s\n" %
4794
(branch_hooks.get_hook_name(hook),))
4796
self.outf.write(" <no hooks installed>\n")
4799
class cmd_shelve(Command):
4800
"""Temporarily set aside some changes from the current tree.
4802
Shelve allows you to temporarily put changes you've made "on the shelf",
4803
ie. out of the way, until a later time when you can bring them back from
4804
the shelf with the 'unshelve' command.
4806
If shelve --list is specified, previously-shelved changes are listed.
4808
Shelve is intended to help separate several sets of changes that have
4809
been inappropriately mingled. If you just want to get rid of all changes
4810
and you don't need to restore them later, use revert. If you want to
4811
shelve all text changes at once, use shelve --all.
4813
If filenames are specified, only the changes to those files will be
4814
shelved. Other files will be left untouched.
4816
If a revision is specified, changes since that revision will be shelved.
4818
You can put multiple items on the shelf, and by default, 'unshelve' will
4819
restore the most recently shelved changes.
4822
takes_args = ['file*']
4826
Option('all', help='Shelve all changes.'),
4828
RegistryOption('writer', 'Method to use for writing diffs.',
4829
bzrlib.option.diff_writer_registry,
4830
value_switches=True, enum_switch=False),
4832
Option('list', help='List shelved changes.'),
4834
_see_also = ['unshelve']
4836
def run(self, revision=None, all=False, file_list=None, message=None,
4837
writer=None, list=False):
4839
return self.run_for_list()
4840
from bzrlib.shelf_ui import Shelver
4842
writer = bzrlib.option.diff_writer_registry.get()
4844
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
4846
except errors.UserAbort:
4849
def run_for_list(self):
4850
tree = WorkingTree.open_containing('.')[0]
4853
manager = tree.get_shelf_manager()
4854
shelves = manager.active_shelves()
4855
if len(shelves) == 0:
4856
note('No shelved changes.')
4858
for shelf_id in reversed(shelves):
4859
message = manager.get_metadata(shelf_id).get('message')
4861
message = '<no message>'
4862
self.outf.write('%3d: %s\n' % (shelf_id, message))
4868
class cmd_unshelve(Command):
4869
"""Restore shelved changes.
4871
By default, the most recently shelved changes are restored. However if you
4872
specify a patch by name those changes will be restored instead. This
4873
works best when the changes don't depend on each other.
4876
takes_args = ['shelf_id?']
4878
RegistryOption.from_kwargs(
4879
'action', help="The action to perform.",
4880
enum_switch=False, value_switches=True,
4881
apply="Apply changes and remove from the shelf.",
4882
dry_run="Show changes, but do not apply or remove them.",
4883
delete_only="Delete changes without applying them."
4886
_see_also = ['shelve']
4888
def run(self, shelf_id=None, action='apply'):
4889
from bzrlib.shelf_ui import Unshelver
4890
Unshelver.from_args(shelf_id, action).run()
4893
def _create_prefix(cur_transport):
4894
needed = [cur_transport]
4895
# Recurse upwards until we can create a directory successfully
4897
new_transport = cur_transport.clone('..')
4898
if new_transport.base == cur_transport.base:
4899
raise errors.BzrCommandError(
4900
"Failed to create path prefix for %s."
4901
% cur_transport.base)
4903
new_transport.mkdir('.')
4904
except errors.NoSuchFile:
4905
needed.append(new_transport)
4906
cur_transport = new_transport
4909
# Now we only need to create child directories
4911
cur_transport = needed.pop()
4912
cur_transport.ensure_base()
4915
# these get imported and then picked up by the scan for cmd_*
4916
# TODO: Some more consistent way to split command definitions across files;
4917
# we do need to load at least some information about them to know of
4918
# aliases. ideally we would avoid loading the implementation until the
4919
# details were needed.
4920
from bzrlib.cmd_version_info import cmd_version_info
4921
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4922
from bzrlib.bundle.commands import (
4925
from bzrlib.sign_my_commits import cmd_sign_my_commits
4926
from bzrlib.weave_commands import cmd_versionedfile_list, \
4927
cmd_weave_plan_merge, cmd_weave_merge_text