13
13
# You should have received a copy of the GNU General Public License
14
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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
"""builtin bzr commands"""
20
from StringIO import StringIO
22
21
from bzrlib.lazy_import import lazy_import
23
22
lazy_import(globals(), """
31
28
from bzrlib import (
35
config as _mod_config,
42
40
merge as _mod_merge,
47
45
revision as _mod_revision,
55
54
from bzrlib.branch import Branch
56
55
from bzrlib.conflicts import ConflictList
57
from bzrlib.revisionspec import RevisionSpec
56
from bzrlib.transport import memory
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
58
58
from bzrlib.smtp_connection import SMTPConnection
59
59
from bzrlib.workingtree import WorkingTree
62
from bzrlib.commands import Command, display_command
63
from bzrlib.option import ListOption, Option, RegistryOption
64
from bzrlib.progress import DummyProgress, ProgressPhase
65
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
68
def tree_files(file_list, default_branch=u'.'):
70
return internal_tree_files(file_list, default_branch)
71
except errors.FileInWrongBranch, e:
72
raise errors.BzrCommandError("%s is not in the same branch as %s" %
73
(e.path, file_list[0]))
62
from bzrlib.commands import (
64
builtin_command_registry,
67
from bzrlib.option import (
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
77
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
80
return internal_tree_files(file_list, default_branch, canonicalize,
84
def tree_files_for_add(file_list):
86
Return a tree and list of absolute paths from a file list.
88
Similar to tree_files, but add handles files a bit differently, so it a
89
custom implementation. In particular, MutableTreeTree.smart_add expects
90
absolute paths, which it immediately converts to relative paths.
92
# FIXME Would be nice to just return the relative paths like
93
# internal_tree_files does, but there are a large number of unit tests
94
# that assume the current interface to mutabletree.smart_add
96
tree, relpath = WorkingTree.open_containing(file_list[0])
97
if tree.supports_views():
98
view_files = tree.views.lookup_view()
100
for filename in file_list:
101
if not osutils.is_inside_any(view_files, filename):
102
raise errors.FileOutsideView(filename, view_files)
103
file_list = file_list[:]
104
file_list[0] = tree.abspath(relpath)
106
tree = WorkingTree.open_containing(u'.')[0]
107
if tree.supports_views():
108
view_files = tree.views.lookup_view()
110
file_list = view_files
111
view_str = views.view_display_str(view_files)
112
note("Ignoring files outside view. View is %s" % view_str)
113
return tree, file_list
116
def _get_one_revision(command_name, revisions):
117
if revisions is None:
119
if len(revisions) != 1:
120
raise errors.BzrCommandError(
121
'bzr %s --revision takes exactly one revision identifier' % (
126
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
127
"""Get a revision tree. Not suitable for commands that change the tree.
129
Specifically, the basis tree in dirstate trees is coupled to the dirstate
130
and doing a commit/uncommit/pull will at best fail due to changing the
133
If tree is passed in, it should be already locked, for lifetime management
134
of the trees internal cached state.
138
if revisions is None:
140
rev_tree = tree.basis_tree()
142
rev_tree = branch.basis_tree()
144
revision = _get_one_revision(command_name, revisions)
145
rev_tree = revision.as_tree(branch)
76
149
# XXX: Bad function name; should possibly also be a class method of
77
150
# WorkingTree rather than a function.
78
def internal_tree_files(file_list, default_branch=u'.'):
151
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
152
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
79
154
"""Convert command-line paths to a WorkingTree and relative paths.
156
Deprecated: use WorkingTree.open_containing_paths instead.
81
158
This is typically used for command-line processors that take one or
82
159
more filenames, and infer the workingtree that contains them.
84
161
The filenames given are not required to exist.
86
:param file_list: Filenames to convert.
163
:param file_list: Filenames to convert.
88
165
:param default_branch: Fallback tree path to use if file_list is empty or
168
:param apply_view: if True and a view is set, apply it or check that
169
specified files are within it
91
171
:return: workingtree, [relative_paths]
93
if file_list is None or len(file_list) == 0:
94
return WorkingTree.open_containing(default_branch)[0], file_list
95
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
97
for filename in file_list:
99
new_list.append(tree.relpath(osutils.dereference_path(filename)))
100
except errors.PathNotChild:
101
raise errors.FileInWrongBranch(tree.branch, filename)
102
return tree, new_list
105
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
106
def get_format_type(typestring):
107
"""Parse and return a format specifier."""
108
# Have to use BzrDirMetaFormat1 directly, so that
109
# RepositoryFormat.set_default_format works
110
if typestring == "default":
111
return bzrdir.BzrDirMetaFormat1()
173
return WorkingTree.open_containing_paths(
174
file_list, default_directory='.',
179
def _get_view_info_for_change_reporter(tree):
180
"""Get the view information from a tree for change reporting."""
113
return bzrdir.format_registry.make_bzrdir(typestring)
115
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
116
raise errors.BzrCommandError(msg)
183
current_view = tree.views.get_view_info()[0]
184
if current_view is not None:
185
view_info = (current_view, tree.views.lookup_view())
186
except errors.ViewsNotSupported:
191
def _open_directory_or_containing_tree_or_branch(filename, directory):
192
"""Open the tree or branch containing the specified file, unless
193
the --directory option is used to specify a different branch."""
194
if directory is not None:
195
return (None, Branch.open(directory), filename)
196
return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
119
199
# TODO: Make sure no commands unconditionally use the working directory as a
150
230
Not versioned and not matching an ignore pattern.
232
Additionally for directories, symlinks and files with an executable
233
bit, Bazaar indicates their type using a trailing character: '/', '@'
152
236
To see ignored files use 'bzr ignored'. For details on the
153
237
changes to file texts, use 'bzr diff'.
155
--short gives a status flags for each item, similar to the SVN's status
239
Note that --short or -S gives status flags for each item, similar
240
to Subversion's status command. To get output similar to svn -q,
158
243
If no arguments are specified, the status of the entire working
159
244
directory is shown. Otherwise, only the status of the specified
160
245
files or directories is reported. If a directory is given, status
161
246
is reported for everything inside that directory.
248
Before merges are committed, the pending merge tip revisions are
249
shown. To see all pending merge revisions, use the -v option.
250
To skip the display of pending merge information altogether, use
251
the no-pending option or specify a file/directory.
163
253
If a revision argument is given, the status is calculated against
164
254
that revision, or between two revisions if two are provided.
167
257
# TODO: --no-recurse, --recurse options
169
259
takes_args = ['file*']
170
takes_options = ['show-ids', 'revision', 'change',
171
Option('short', help='Give short SVN-style status lines.'),
172
Option('versioned', help='Only show versioned files.')]
260
takes_options = ['show-ids', 'revision', 'change', 'verbose',
261
Option('short', help='Use short status indicators.',
263
Option('versioned', help='Only show versioned files.',
265
Option('no-pending', help='Don\'t show pending merges.',
173
268
aliases = ['st', 'stat']
175
270
encoding_type = 'replace'
176
271
_see_also = ['diff', 'revert', 'status-flags']
179
274
def run(self, show_ids=False, file_list=None, revision=None, short=False,
275
versioned=False, no_pending=False, verbose=False):
181
276
from bzrlib.status import show_tree_status
183
278
if revision and len(revision) > 2:
184
279
raise errors.BzrCommandError('bzr status --revision takes exactly'
185
280
' one or two revision specifiers')
187
tree, file_list = tree_files(file_list)
282
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
283
# Avoid asking for specific files when that is not needed.
284
if relfile_list == ['']:
286
# Don't disable pending merges for full trees other than '.'.
287
if file_list == ['.']:
289
# A specific path within a tree was given.
290
elif relfile_list is not None:
189
292
show_tree_status(tree, show_ids=show_ids,
190
specific_files=file_list, revision=revision,
191
to_file=self.outf, short=short, versioned=versioned)
293
specific_files=relfile_list, revision=revision,
294
to_file=self.outf, short=short, versioned=versioned,
295
show_pending=(not no_pending), verbose=verbose)
194
298
class cmd_cat_revision(Command):
195
"""Write out metadata for a revision.
299
__doc__ = """Write out metadata for a revision.
197
301
The revision to print can either be specified by a specific
198
302
revision identifier, or you can use --revision.
202
306
takes_args = ['revision_id?']
203
takes_options = ['revision']
307
takes_options = ['directory', 'revision']
204
308
# cat-revision is more for frontends so should be exact
205
309
encoding = 'strict'
311
def print_revision(self, revisions, revid):
312
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
313
record = stream.next()
314
if record.storage_kind == 'absent':
315
raise errors.NoSuchRevision(revisions, revid)
316
revtext = record.get_bytes_as('fulltext')
317
self.outf.write(revtext.decode('utf-8'))
208
def run(self, revision_id=None, revision=None):
210
revision_id = osutils.safe_revision_id(revision_id, warn=False)
320
def run(self, revision_id=None, revision=None, directory=u'.'):
211
321
if revision_id is not None and revision is not None:
212
322
raise errors.BzrCommandError('You can only supply one of'
213
323
' revision_id or --revision')
214
324
if revision_id is None and revision is None:
215
325
raise errors.BzrCommandError('You must supply either'
216
326
' --revision or a revision_id')
217
b = WorkingTree.open_containing(u'.')[0].branch
219
# TODO: jam 20060112 should cat-revision always output utf-8?
220
if revision_id is not None:
221
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
222
elif revision is not None:
225
raise errors.BzrCommandError('You cannot specify a NULL'
227
revno, rev_id = rev.in_history(b)
228
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
327
b = WorkingTree.open_containing(directory)[0].branch
329
revisions = b.repository.revisions
330
if revisions is None:
331
raise errors.BzrCommandError('Repository %r does not support '
332
'access to raw revision texts')
334
b.repository.lock_read()
336
# TODO: jam 20060112 should cat-revision always output utf-8?
337
if revision_id is not None:
338
revision_id = osutils.safe_revision_id(revision_id, warn=False)
340
self.print_revision(revisions, revision_id)
341
except errors.NoSuchRevision:
342
msg = "The repository %s contains no revision %s." % (
343
b.repository.base, revision_id)
344
raise errors.BzrCommandError(msg)
345
elif revision is not None:
348
raise errors.BzrCommandError(
349
'You cannot specify a NULL revision.')
350
rev_id = rev.as_revision_id(b)
351
self.print_revision(revisions, rev_id)
353
b.repository.unlock()
356
class cmd_dump_btree(Command):
357
__doc__ = """Dump the contents of a btree index file to stdout.
359
PATH is a btree index file, it can be any URL. This includes things like
360
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
362
By default, the tuples stored in the index file will be displayed. With
363
--raw, we will uncompress the pages, but otherwise display the raw bytes
367
# TODO: Do we want to dump the internal nodes as well?
368
# TODO: It would be nice to be able to dump the un-parsed information,
369
# rather than only going through iter_all_entries. However, this is
370
# good enough for a start
372
encoding_type = 'exact'
373
takes_args = ['path']
374
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
375
' rather than the parsed tuples.'),
378
def run(self, path, raw=False):
379
dirname, basename = osutils.split(path)
380
t = transport.get_transport(dirname)
382
self._dump_raw_bytes(t, basename)
384
self._dump_entries(t, basename)
386
def _get_index_and_bytes(self, trans, basename):
387
"""Create a BTreeGraphIndex and raw bytes."""
388
bt = btree_index.BTreeGraphIndex(trans, basename, None)
389
bytes = trans.get_bytes(basename)
390
bt._file = cStringIO.StringIO(bytes)
391
bt._size = len(bytes)
394
def _dump_raw_bytes(self, trans, basename):
397
# We need to parse at least the root node.
398
# This is because the first page of every row starts with an
399
# uncompressed header.
400
bt, bytes = self._get_index_and_bytes(trans, basename)
401
for page_idx, page_start in enumerate(xrange(0, len(bytes),
402
btree_index._PAGE_SIZE)):
403
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
404
page_bytes = bytes[page_start:page_end]
406
self.outf.write('Root node:\n')
407
header_end, data = bt._parse_header_from_bytes(page_bytes)
408
self.outf.write(page_bytes[:header_end])
410
self.outf.write('\nPage %d\n' % (page_idx,))
411
decomp_bytes = zlib.decompress(page_bytes)
412
self.outf.write(decomp_bytes)
413
self.outf.write('\n')
415
def _dump_entries(self, trans, basename):
417
st = trans.stat(basename)
418
except errors.TransportNotPossible:
419
# We can't stat, so we'll fake it because we have to do the 'get()'
421
bt, _ = self._get_index_and_bytes(trans, basename)
423
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
424
for node in bt.iter_all_entries():
425
# Node is made up of:
426
# (index, key, value, [references])
430
refs_as_tuples = None
432
refs_as_tuples = static_tuple.as_tuples(refs)
433
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
434
self.outf.write('%s\n' % (as_tuple,))
231
437
class cmd_remove_tree(Command):
232
"""Remove the working tree from a given branch/checkout.
438
__doc__ = """Remove the working tree from a given branch/checkout.
234
440
Since a lightweight checkout is little more than a working tree
235
441
this will refuse to run against one.
237
443
To re-create the working tree, use "bzr checkout".
239
445
_see_also = ['checkout', 'working-trees']
241
takes_args = ['location?']
243
def run(self, location='.'):
244
d = bzrdir.BzrDir.open(location)
247
working = d.open_workingtree()
248
except errors.NoWorkingTree:
249
raise errors.BzrCommandError("No working tree to remove")
250
except errors.NotLocalUrl:
251
raise errors.BzrCommandError("You cannot remove the working tree of a "
254
working_path = working.bzrdir.root_transport.base
255
branch_path = working.branch.bzrdir.root_transport.base
256
if working_path != branch_path:
257
raise errors.BzrCommandError("You cannot remove the working tree from "
258
"a lightweight checkout")
260
d.destroy_workingtree()
446
takes_args = ['location*']
449
help='Remove the working tree even if it has '
450
'uncommitted or shelved changes.'),
453
def run(self, location_list, force=False):
454
if not location_list:
457
for location in location_list:
458
d = bzrdir.BzrDir.open(location)
461
working = d.open_workingtree()
462
except errors.NoWorkingTree:
463
raise errors.BzrCommandError("No working tree to remove")
464
except errors.NotLocalUrl:
465
raise errors.BzrCommandError("You cannot remove the working tree"
468
if (working.has_changes()):
469
raise errors.UncommittedChanges(working)
470
if working.get_shelf_manager().last_shelf() is not None:
471
raise errors.ShelvedChanges(working)
473
if working.user_url != working.branch.user_url:
474
raise errors.BzrCommandError("You cannot remove the working tree"
475
" from a lightweight checkout")
477
d.destroy_workingtree()
263
480
class cmd_revno(Command):
264
"""Show current revision number.
481
__doc__ = """Show current revision number.
266
483
This is equal to the number of revisions on this branch.
269
486
_see_also = ['info']
270
487
takes_args = ['location?']
489
Option('tree', help='Show revno of working tree'),
273
def run(self, location=u'.'):
274
self.outf.write(str(Branch.open_containing(location)[0].revno()))
275
self.outf.write('\n')
493
def run(self, tree=False, location=u'.'):
496
wt = WorkingTree.open_containing(location)[0]
497
self.add_cleanup(wt.lock_read().unlock)
498
except (errors.NoWorkingTree, errors.NotLocalUrl):
499
raise errors.NoWorkingTree(location)
500
revid = wt.last_revision()
502
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
503
except errors.NoSuchRevision:
505
revno = ".".join(str(n) for n in revno_t)
507
b = Branch.open_containing(location)[0]
508
self.add_cleanup(b.lock_read().unlock)
511
self.outf.write(str(revno) + '\n')
278
514
class cmd_revision_info(Command):
279
"""Show revision number and revision id for a given revision identifier.
515
__doc__ = """Show revision number and revision id for a given revision identifier.
282
518
takes_args = ['revision_info*']
283
takes_options = ['revision']
521
custom_help('directory',
522
help='Branch to examine, '
523
'rather than the one containing the working directory.'),
524
Option('tree', help='Show revno of working tree'),
286
def run(self, revision=None, revision_info_list=[]):
528
def run(self, revision=None, directory=u'.', tree=False,
529
revision_info_list=[]):
532
wt = WorkingTree.open_containing(directory)[0]
534
self.add_cleanup(wt.lock_read().unlock)
535
except (errors.NoWorkingTree, errors.NotLocalUrl):
537
b = Branch.open_containing(directory)[0]
538
self.add_cleanup(b.lock_read().unlock)
289
540
if revision is not None:
290
revs.extend(revision)
541
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
291
542
if revision_info_list is not None:
292
for rev in revision_info_list:
293
revs.append(RevisionSpec.from_string(rev))
295
b = Branch.open_containing(u'.')[0]
298
revs.append(RevisionSpec.from_string('-1'))
301
revinfo = rev.in_history(b)
302
if revinfo.revno is None:
303
dotted_map = b.get_revision_id_to_revno_map()
304
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
305
print '%s %s' % (revno, revinfo.rev_id)
543
for rev_str in revision_info_list:
544
rev_spec = RevisionSpec.from_string(rev_str)
545
revision_ids.append(rev_spec.as_revision_id(b))
546
# No arguments supplied, default to the last revision
547
if len(revision_ids) == 0:
550
raise errors.NoWorkingTree(directory)
551
revision_ids.append(wt.last_revision())
307
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
553
revision_ids.append(b.last_revision())
557
for revision_id in revision_ids:
559
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
560
revno = '.'.join(str(i) for i in dotted_revno)
561
except errors.NoSuchRevision:
563
maxlen = max(maxlen, len(revno))
564
revinfos.append([revno, revision_id])
568
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
310
571
class cmd_add(Command):
311
"""Add specified files or directories.
572
__doc__ = """Add specified files or directories.
313
574
In non-recursive mode, all the named items are added, regardless
314
575
of whether they were previously ignored. A warning is given if
526
773
takes_args = ['names*']
527
774
takes_options = [Option("after", help="Move only the bzr identifier"
528
775
" of the file, because the file has already been moved."),
776
Option('auto', help='Automatically guess renames.'),
777
Option('dry-run', help='Avoid making changes when guessing renames.'),
530
779
aliases = ['move', 'rename']
531
780
encoding_type = 'replace'
533
def run(self, names_list, after=False):
782
def run(self, names_list, after=False, auto=False, dry_run=False):
784
return self.run_auto(names_list, after, dry_run)
786
raise errors.BzrCommandError('--dry-run requires --auto.')
534
787
if names_list is None:
537
789
if len(names_list) < 2:
538
790
raise errors.BzrCommandError("missing file argument")
539
tree, rel_names = tree_files(names_list)
541
if os.path.isdir(names_list[-1]):
791
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
792
self.add_cleanup(tree.lock_tree_write().unlock)
793
self._run(tree, names_list, rel_names, after)
795
def run_auto(self, names_list, after, dry_run):
796
if names_list is not None and len(names_list) > 1:
797
raise errors.BzrCommandError('Only one path may be specified to'
800
raise errors.BzrCommandError('--after cannot be specified with'
802
work_tree, file_list = WorkingTree.open_containing_paths(
803
names_list, default_directory='.')
804
self.add_cleanup(work_tree.lock_tree_write().unlock)
805
rename_map.RenameMap.guess_renames(work_tree, dry_run)
807
def _run(self, tree, names_list, rel_names, after):
808
into_existing = osutils.isdir(names_list[-1])
809
if into_existing and len(names_list) == 2:
811
# a. case-insensitive filesystem and change case of dir
812
# b. move directory after the fact (if the source used to be
813
# a directory, but now doesn't exist in the working tree
814
# and the target is an existing directory, just rename it)
815
if (not tree.case_sensitive
816
and rel_names[0].lower() == rel_names[1].lower()):
817
into_existing = False
820
# 'fix' the case of a potential 'from'
821
from_id = tree.path2id(
822
tree.get_canonical_inventory_path(rel_names[0]))
823
if (not osutils.lexists(names_list[0]) and
824
from_id and inv.get_file_kind(from_id) == "directory"):
825
into_existing = False
542
828
# move into existing directory
543
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
544
self.outf.write("%s => %s\n" % pair)
829
# All entries reference existing inventory items, so fix them up
830
# for cicp file-systems.
831
rel_names = tree.get_canonical_inventory_paths(rel_names)
832
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
834
self.outf.write("%s => %s\n" % (src, dest))
546
836
if len(names_list) != 2:
547
837
raise errors.BzrCommandError('to mv multiple files the'
548
838
' destination must be a versioned'
550
tree.rename_one(rel_names[0], rel_names[1], after=after)
551
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
841
# for cicp file-systems: the src references an existing inventory
843
src = tree.get_canonical_inventory_path(rel_names[0])
844
# Find the canonical version of the destination: In all cases, the
845
# parent of the target must be in the inventory, so we fetch the
846
# canonical version from there (we do not always *use* the
847
# canonicalized tail portion - we may be attempting to rename the
849
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
850
dest_parent = osutils.dirname(canon_dest)
851
spec_tail = osutils.basename(rel_names[1])
852
# For a CICP file-system, we need to avoid creating 2 inventory
853
# entries that differ only by case. So regardless of the case
854
# we *want* to use (ie, specified by the user or the file-system),
855
# we must always choose to use the case of any existing inventory
856
# items. The only exception to this is when we are attempting a
857
# case-only rename (ie, canonical versions of src and dest are
859
dest_id = tree.path2id(canon_dest)
860
if dest_id is None or tree.path2id(src) == dest_id:
861
# No existing item we care about, so work out what case we
862
# are actually going to use.
864
# If 'after' is specified, the tail must refer to a file on disk.
866
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
868
# pathjoin with an empty tail adds a slash, which breaks
870
dest_parent_fq = tree.basedir
872
dest_tail = osutils.canonical_relpath(
874
osutils.pathjoin(dest_parent_fq, spec_tail))
876
# not 'after', so case as specified is used
877
dest_tail = spec_tail
879
# Use the existing item so 'mv' fails with AlreadyVersioned.
880
dest_tail = os.path.basename(canon_dest)
881
dest = osutils.pathjoin(dest_parent, dest_tail)
882
mutter("attempting to move %s => %s", src, dest)
883
tree.rename_one(src, dest, after=after)
885
self.outf.write("%s => %s\n" % (src, dest))
554
888
class cmd_pull(Command):
555
"""Turn this branch into a mirror of another branch.
889
__doc__ = """Turn this branch into a mirror of another branch.
557
This command only works on branches that have not diverged. Branches are
558
considered diverged if the destination branch's most recent commit is one
559
that has not been merged (directly or indirectly) into the parent.
891
By default, this command only works on branches that have not diverged.
892
Branches are considered diverged if the destination branch's most recent
893
commit is one that has not been merged (directly or indirectly) into the
561
896
If branches have diverged, you can use 'bzr merge' to integrate the changes
562
897
from one into the other. Once one branch has merged, the other should
563
898
be able to pull it again.
565
If you want to forget your local changes and just update your branch to
566
match the remote one, use pull --overwrite.
900
If you want to replace your local changes and just want your branch to
901
match the remote one, use pull --overwrite. This will work even if the two
902
branches have diverged.
568
904
If there is no default location set, the first pull will set it. After
569
905
that, you can omit the location to use the default. To change the
570
906
default, use --remember. The value will only be saved if the remote
571
907
location can be accessed.
909
Note: The location can be specified either in the form of a branch,
910
or in the form of a path to a file containing a merge directive generated
574
_see_also = ['push', 'update', 'status-flags']
914
_see_also = ['push', 'update', 'status-flags', 'send']
575
915
takes_options = ['remember', 'overwrite', 'revision',
576
Option('verbose', short_name='v',
916
custom_help('verbose',
577
917
help='Show logs of pulled revisions.'),
918
custom_help('directory',
579
919
help='Branch to pull into, '
580
'rather than the one containing the working directory.',
920
'rather than the one containing the working directory.'),
922
help="Perform a local pull in a bound "
923
"branch. Local pulls are not applied to "
927
help="Show base revision text in conflicts.")
585
929
takes_args = ['location?']
586
930
encoding_type = 'replace'
588
932
def run(self, location=None, remember=False, overwrite=False,
589
933
revision=None, verbose=False,
934
directory=None, local=False,
591
936
# FIXME: too much stuff is in the command class
592
937
revision_id = None
680
1042
_see_also = ['pull', 'update', 'working-trees']
681
takes_options = ['remember', 'overwrite', 'verbose',
1043
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
682
1044
Option('create-prefix',
683
1045
help='Create the path leading up to the branch '
684
1046
'if it does not already exist.'),
1047
custom_help('directory',
686
1048
help='Branch to push from, '
687
'rather than the one containing the working directory.',
1049
'rather than the one containing the working directory.'),
691
1050
Option('use-existing-dir',
692
1051
help='By default push will fail if the target'
693
1052
' directory exists, but does not already'
694
1053
' have a control directory. This flag will'
695
1054
' allow push to proceed.'),
1056
help='Create a stacked branch that references the public location '
1057
'of the parent branch.'),
1058
Option('stacked-on',
1059
help='Create a stacked branch that refers to another branch '
1060
'for the commit history. Only the work not present in the '
1061
'referenced branch is included in the branch created.',
1064
help='Refuse to push if there are uncommitted changes in'
1065
' the working tree, --no-strict disables the check.'),
697
1067
takes_args = ['location?']
698
1068
encoding_type = 'replace'
700
1070
def run(self, location=None, remember=False, overwrite=False,
701
create_prefix=False, verbose=False,
702
use_existing_dir=False,
704
# FIXME: Way too big! Put this into a function called from the
1071
create_prefix=False, verbose=False, revision=None,
1072
use_existing_dir=False, directory=None, stacked_on=None,
1073
stacked=False, strict=None):
1074
from bzrlib.push import _show_push_branch
706
1076
if directory is None:
708
br_from = Branch.open_containing(directory)[0]
709
stored_loc = br_from.get_push_location()
1078
# Get the source branch
1080
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1081
# Get the tip's revision_id
1082
revision = _get_one_revision('push', revision)
1083
if revision is not None:
1084
revision_id = revision.in_history(br_from).rev_id
1087
if tree is not None and revision_id is None:
1088
tree.check_changed_or_out_of_date(
1089
strict, 'push_strict',
1090
more_error='Use --no-strict to force the push.',
1091
more_warning='Uncommitted changes will not be pushed.')
1092
# Get the stacked_on branch, if any
1093
if stacked_on is not None:
1094
stacked_on = urlutils.normalize_url(stacked_on)
1096
parent_url = br_from.get_parent()
1098
parent = Branch.open(parent_url)
1099
stacked_on = parent.get_public_branch()
1101
# I considered excluding non-http url's here, thus forcing
1102
# 'public' branches only, but that only works for some
1103
# users, so it's best to just depend on the user spotting an
1104
# error by the feedback given to them. RBC 20080227.
1105
stacked_on = parent_url
1107
raise errors.BzrCommandError(
1108
"Could not determine branch to refer to.")
1110
# Get the destination location
710
1111
if location is None:
1112
stored_loc = br_from.get_push_location()
711
1113
if stored_loc is None:
712
raise errors.BzrCommandError("No push location known or specified.")
1114
raise errors.BzrCommandError(
1115
"No push location known or specified.")
714
1117
display_url = urlutils.unescape_for_display(stored_loc,
715
1118
self.outf.encoding)
716
self.outf.write("Using saved location: %s\n" % display_url)
1119
self.outf.write("Using saved push location: %s\n" % display_url)
717
1120
location = stored_loc
719
to_transport = transport.get_transport(location)
721
br_to = repository_to = dir_to = None
723
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
724
except errors.NotBranchError:
725
pass # Didn't find anything
727
# If we can open a branch, use its direct repository, otherwise see
728
# if there is a repository without a branch.
730
br_to = dir_to.open_branch()
731
except errors.NotBranchError:
732
# Didn't find a branch, can we find a repository?
734
repository_to = dir_to.find_repository()
735
except errors.NoRepositoryPresent:
738
# Found a branch, so we must have found a repository
739
repository_to = br_to.repository
744
# The destination doesn't exist; create it.
745
# XXX: Refactor the create_prefix/no_create_prefix code into a
746
# common helper function
748
to_transport.mkdir('.')
749
except errors.FileExists:
750
if not use_existing_dir:
751
raise errors.BzrCommandError("Target directory %s"
752
" already exists, but does not have a valid .bzr"
753
" directory. Supply --use-existing-dir to push"
754
" there anyway." % location)
755
except errors.NoSuchFile:
756
if not create_prefix:
757
raise errors.BzrCommandError("Parent directory of %s"
759
"\nYou may supply --create-prefix to create all"
760
" leading parent directories."
762
_create_prefix(to_transport)
764
# Now the target directory exists, but doesn't have a .bzr
765
# directory. So we need to create it, along with any work to create
766
# all of the dependent branches, etc.
767
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
768
revision_id=br_from.last_revision())
769
br_to = dir_to.open_branch()
770
# TODO: Some more useful message about what was copied
771
note('Created new branch.')
772
# We successfully created the target, remember it
773
if br_from.get_push_location() is None or remember:
774
br_from.set_push_location(br_to.base)
775
elif repository_to is None:
776
# we have a bzrdir but no branch or repository
777
# XXX: Figure out what to do other than complain.
778
raise errors.BzrCommandError("At %s you have a valid .bzr control"
779
" directory, but not a branch or repository. This is an"
780
" unsupported configuration. Please move the target directory"
781
" out of the way and try again."
784
# We have a repository but no branch, copy the revisions, and then
786
last_revision_id = br_from.last_revision()
787
repository_to.fetch(br_from.repository,
788
revision_id=last_revision_id)
789
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
790
note('Created new branch.')
791
if br_from.get_push_location() is None or remember:
792
br_from.set_push_location(br_to.base)
793
else: # We have a valid to branch
794
# We were able to connect to the remote location, so remember it
795
# we don't need to successfully push because of possible divergence.
796
if br_from.get_push_location() is None or remember:
797
br_from.set_push_location(br_to.base)
799
old_rh = br_to.revision_history()
802
tree_to = dir_to.open_workingtree()
803
except errors.NotLocalUrl:
804
warning("This transport does not update the working "
805
"tree of: %s. See 'bzr help working-trees' for "
806
"more information." % br_to.base)
807
push_result = br_from.push(br_to, overwrite)
808
except errors.NoWorkingTree:
809
push_result = br_from.push(br_to, overwrite)
813
push_result = br_from.push(tree_to.branch, overwrite)
817
except errors.DivergedBranches:
818
raise errors.BzrCommandError('These branches have diverged.'
819
' Try using "merge" and then "push".')
820
if push_result is not None:
821
push_result.report(self.outf)
823
new_rh = br_to.revision_history()
826
from bzrlib.log import show_changed_revisions
827
show_changed_revisions(br_to, old_rh, new_rh,
830
# we probably did a clone rather than a push, so a message was
1122
_show_push_branch(br_from, revision_id, location, self.outf,
1123
verbose=verbose, overwrite=overwrite, remember=remember,
1124
stacked_on=stacked_on, create_prefix=create_prefix,
1125
use_existing_dir=use_existing_dir)
835
1128
class cmd_branch(Command):
836
"""Create a new copy of a branch.
1129
__doc__ = """Create a new branch that is a copy of an existing branch.
838
1131
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
839
1132
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
849
1142
_see_also = ['checkout']
850
1143
takes_args = ['from_location', 'to_location?']
851
takes_options = ['revision']
1144
takes_options = ['revision',
1145
Option('hardlink', help='Hard-link working tree files where possible.'),
1146
Option('files-from', type=str,
1147
help="Get file contents from this tree."),
1149
help="Create a branch without a working-tree."),
1151
help="Switch the checkout in the current directory "
1152
"to the new branch."),
1154
help='Create a stacked branch referring to the source branch. '
1155
'The new branch will depend on the availability of the source '
1156
'branch for all operations.'),
1157
Option('standalone',
1158
help='Do not use a shared repository, even if available.'),
1159
Option('use-existing-dir',
1160
help='By default branch will fail if the target'
1161
' directory exists, but does not already'
1162
' have a control directory. This flag will'
1163
' allow branch to proceed.'),
1165
help="Bind new branch to from location."),
852
1167
aliases = ['get', 'clone']
854
def run(self, from_location, to_location=None, revision=None):
1169
def run(self, from_location, to_location=None, revision=None,
1170
hardlink=False, stacked=False, standalone=False, no_tree=False,
1171
use_existing_dir=False, switch=False, bind=False,
1173
from bzrlib import switch as _mod_switch
855
1174
from bzrlib.tag import _merge_tags_if_possible
858
elif len(revision) > 1:
859
raise errors.BzrCommandError(
860
'bzr branch --revision takes exactly 1 revision value')
862
br_from = Branch.open(from_location)
865
if len(revision) == 1 and revision[0] is not None:
866
revision_id = revision[0].in_history(br_from)[1]
868
# FIXME - wt.last_revision, fallback to branch, fall back to
869
# None or perhaps NULL_REVISION to mean copy nothing
871
revision_id = br_from.last_revision()
872
if to_location is None:
873
to_location = urlutils.derive_to_location(from_location)
876
name = os.path.basename(to_location) + '\n'
878
to_transport = transport.get_transport(to_location)
880
to_transport.mkdir('.')
881
except errors.FileExists:
882
raise errors.BzrCommandError('Target directory "%s" already'
883
' exists.' % to_location)
884
except errors.NoSuchFile:
885
raise errors.BzrCommandError('Parent of "%s" does not exist.'
888
# preserve whatever source format we have.
889
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
890
possible_transports=[to_transport])
891
branch = dir.open_branch()
892
except errors.NoSuchRevision:
893
to_transport.delete_tree('.')
894
msg = "The branch %s has no revision %s." % (from_location, revision[0])
895
raise errors.BzrCommandError(msg)
897
branch.control_files.put_utf8('branch-name', name)
898
_merge_tags_if_possible(br_from, branch)
1175
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1177
if not (hardlink or files_from):
1178
# accelerator_tree is usually slower because you have to read N
1179
# files (no readahead, lots of seeks, etc), but allow the user to
1180
# explicitly request it
1181
accelerator_tree = None
1182
if files_from is not None and files_from != from_location:
1183
accelerator_tree = WorkingTree.open(files_from)
1184
revision = _get_one_revision('branch', revision)
1185
self.add_cleanup(br_from.lock_read().unlock)
1186
if revision is not None:
1187
revision_id = revision.as_revision_id(br_from)
1189
# FIXME - wt.last_revision, fallback to branch, fall back to
1190
# None or perhaps NULL_REVISION to mean copy nothing
1192
revision_id = br_from.last_revision()
1193
if to_location is None:
1194
to_location = urlutils.derive_to_location(from_location)
1195
to_transport = transport.get_transport(to_location)
1197
to_transport.mkdir('.')
1198
except errors.FileExists:
1199
if not use_existing_dir:
1200
raise errors.BzrCommandError('Target directory "%s" '
1201
'already exists.' % to_location)
1204
bzrdir.BzrDir.open_from_transport(to_transport)
1205
except errors.NotBranchError:
1208
raise errors.AlreadyBranchError(to_location)
1209
except errors.NoSuchFile:
1210
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1213
# preserve whatever source format we have.
1214
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1215
possible_transports=[to_transport],
1216
accelerator_tree=accelerator_tree,
1217
hardlink=hardlink, stacked=stacked,
1218
force_new_repo=standalone,
1219
create_tree_if_local=not no_tree,
1220
source_branch=br_from)
1221
branch = dir.open_branch()
1222
except errors.NoSuchRevision:
1223
to_transport.delete_tree('.')
1224
msg = "The branch %s has no revision %s." % (from_location,
1226
raise errors.BzrCommandError(msg)
1227
_merge_tags_if_possible(br_from, branch)
1228
# If the source branch is stacked, the new branch may
1229
# be stacked whether we asked for that explicitly or not.
1230
# We therefore need a try/except here and not just 'if stacked:'
1232
note('Created new stacked branch referring to %s.' %
1233
branch.get_stacked_on_url())
1234
except (errors.NotStacked, errors.UnstackableBranchFormat,
1235
errors.UnstackableRepositoryFormat), e:
899
1236
note('Branched %d revision(s).' % branch.revno())
1238
# Bind to the parent
1239
parent_branch = Branch.open(from_location)
1240
branch.bind(parent_branch)
1241
note('New branch bound to %s' % from_location)
1243
# Switch to the new branch
1244
wt, _ = WorkingTree.open_containing('.')
1245
_mod_switch.switch(wt.bzrdir, branch)
1246
note('Switched to branch: %s',
1247
urlutils.unescape_for_display(branch.base, 'utf-8'))
904
1250
class cmd_checkout(Command):
905
"""Create a new checkout of an existing branch.
1251
__doc__ = """Create a new checkout of an existing branch.
907
1253
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
908
1254
the branch found in '.'. This is useful if you have removed the working tree
909
1255
or if it was never created - i.e. if you pushed the branch to its current
910
1256
location using SFTP.
912
1258
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
913
1259
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
914
1260
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
978
1333
@display_command
979
1334
def run(self, dir=u'.'):
980
1335
tree = WorkingTree.open_containing(dir)[0]
983
new_inv = tree.inventory
984
old_tree = tree.basis_tree()
987
old_inv = old_tree.inventory
988
renames = list(_mod_tree.find_renames(old_inv, new_inv))
990
for old_name, new_name in renames:
991
self.outf.write("%s => %s\n" % (old_name, new_name))
1336
self.add_cleanup(tree.lock_read().unlock)
1337
new_inv = tree.inventory
1338
old_tree = tree.basis_tree()
1339
self.add_cleanup(old_tree.lock_read().unlock)
1340
old_inv = old_tree.inventory
1342
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1343
for f, paths, c, v, p, n, k, e in iterator:
1344
if paths[0] == paths[1]:
1348
renames.append(paths)
1350
for old_name, new_name in renames:
1351
self.outf.write("%s => %s\n" % (old_name, new_name))
998
1354
class cmd_update(Command):
999
"""Update a tree to have the latest code committed to its branch.
1355
__doc__ = """Update a tree to have the latest code committed to its branch.
1001
1357
This will perform a merge into the working tree, and may generate
1002
conflicts. If you have any local changes, you will still
1358
conflicts. If you have any local changes, you will still
1003
1359
need to commit them after the update for the update to be complete.
1005
If you want to discard your local changes, you can just do a
1361
If you want to discard your local changes, you can just do a
1006
1362
'bzr revert' instead of 'bzr commit' after the update.
1364
If you want to restore a file that has been removed locally, use
1365
'bzr revert' instead of 'bzr update'.
1367
If the tree's branch is bound to a master branch, it will also update
1368
the branch from the master.
1009
1371
_see_also = ['pull', 'working-trees', 'status-flags']
1010
1372
takes_args = ['dir?']
1373
takes_options = ['revision',
1375
help="Show base revision text in conflicts."),
1011
1377
aliases = ['up']
1013
def run(self, dir='.'):
1379
def run(self, dir='.', revision=None, show_base=None):
1380
if revision is not None and len(revision) != 1:
1381
raise errors.BzrCommandError(
1382
"bzr update --revision takes exactly one revision")
1014
1383
tree = WorkingTree.open_containing(dir)[0]
1015
master = tree.branch.get_master_branch()
1384
branch = tree.branch
1385
possible_transports = []
1386
master = branch.get_master_branch(
1387
possible_transports=possible_transports)
1016
1388
if master is not None:
1389
branch_location = master.base
1017
1390
tree.lock_write()
1392
branch_location = tree.branch.base
1019
1393
tree.lock_tree_write()
1394
self.add_cleanup(tree.unlock)
1395
# get rid of the final '/' and be ready for display
1396
branch_location = urlutils.unescape_for_display(
1397
branch_location.rstrip('/'),
1399
existing_pending_merges = tree.get_parent_ids()[1:]
1403
# may need to fetch data into a heavyweight checkout
1404
# XXX: this may take some time, maybe we should display a
1406
old_tip = branch.update(possible_transports)
1407
if revision is not None:
1408
revision_id = revision[0].as_revision_id(branch)
1410
revision_id = branch.last_revision()
1411
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1412
revno = branch.revision_id_to_dotted_revno(revision_id)
1413
note("Tree is up to date at revision %s of branch %s" %
1414
('.'.join(map(str, revno)), branch_location))
1416
view_info = _get_view_info_for_change_reporter(tree)
1417
change_reporter = delta._ChangeReporter(
1418
unversioned_filter=tree.is_ignored,
1419
view_info=view_info)
1021
existing_pending_merges = tree.get_parent_ids()[1:]
1022
last_rev = _mod_revision.ensure_null(tree.last_revision())
1023
if last_rev == _mod_revision.ensure_null(
1024
tree.branch.last_revision()):
1025
# may be up to date, check master too.
1026
if master is None or last_rev == _mod_revision.ensure_null(
1027
master.last_revision()):
1028
revno = tree.branch.revision_id_to_revno(last_rev)
1029
note("Tree is up to date at revision %d." % (revno,))
1031
conflicts = tree.update(delta._ChangeReporter(
1032
unversioned_filter=tree.is_ignored))
1033
revno = tree.branch.revision_id_to_revno(
1034
_mod_revision.ensure_null(tree.last_revision()))
1035
note('Updated to revision %d.' % (revno,))
1036
if tree.get_parent_ids()[1:] != existing_pending_merges:
1037
note('Your local commits will now show as pending merges with '
1038
"'bzr status', and can be committed with 'bzr commit'.")
1421
conflicts = tree.update(
1423
possible_transports=possible_transports,
1424
revision=revision_id,
1426
show_base=show_base)
1427
except errors.NoSuchRevision, e:
1428
raise errors.BzrCommandError(
1429
"branch has no revision %s\n"
1430
"bzr update --revision only works"
1431
" for a revision in the branch history"
1433
revno = tree.branch.revision_id_to_dotted_revno(
1434
_mod_revision.ensure_null(tree.last_revision()))
1435
note('Updated to revision %s of branch %s' %
1436
('.'.join(map(str, revno)), branch_location))
1437
parent_ids = tree.get_parent_ids()
1438
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1439
note('Your local commits will now show as pending merges with '
1440
"'bzr status', and can be committed with 'bzr commit'.")
1047
1447
class cmd_info(Command):
1048
"""Show information about a working tree, branch or repository.
1448
__doc__ = """Show information about a working tree, branch or repository.
1050
1450
This command will show all known locations and formats associated to the
1051
tree, branch or repository. Statistical information is included with
1451
tree, branch or repository.
1453
In verbose mode, statistical information is included with each report.
1454
To see extended statistic information, use a verbosity level of 2 or
1455
higher by specifying the verbose option multiple times, e.g. -vv.
1054
1457
Branches and working trees will also report any missing revisions.
1461
Display information on the format and related locations:
1465
Display the above together with extended format information and
1466
basic statistics (like the number of files in the working tree and
1467
number of revisions in the branch and repository):
1471
Display the above together with number of committers to the branch:
1056
1475
_see_also = ['revno', 'working-trees', 'repositories']
1057
1476
takes_args = ['location?']
1058
1477
takes_options = ['verbose']
1478
encoding_type = 'replace'
1060
1480
@display_command
1061
def run(self, location=None, verbose=0):
1481
def run(self, location=None, verbose=False):
1483
noise_level = get_verbosity_level()
1062
1486
from bzrlib.info import show_bzrdir_info
1063
1487
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1488
verbose=noise_level, outfile=self.outf)
1067
1491
class cmd_remove(Command):
1068
"""Remove files or directories.
1070
This makes bzr stop tracking changes to the specified files and
1071
delete them if they can easily be recovered using revert.
1073
You can specify one or more files, and/or --new. If you specify --new,
1074
only 'added' files will be removed. If you specify both, then new files
1075
in the specified directories will be removed. If the directories are
1076
also new, they will also be removed.
1492
__doc__ = """Remove files or directories.
1494
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1495
delete them if they can easily be recovered using revert otherwise they
1496
will be backed up (adding an extention of the form .~#~). If no options or
1497
parameters are given Bazaar will scan for files that are being tracked by
1498
Bazaar but missing in your tree and stop tracking them for you.
1078
1500
takes_args = ['file*']
1079
1501
takes_options = ['verbose',
1080
Option('new', help='Remove newly-added files.'),
1502
Option('new', help='Only remove files that have never been committed.'),
1081
1503
RegistryOption.from_kwargs('file-deletion-strategy',
1082
1504
'The file deletion mode to be used.',
1083
1505
title='Deletion Strategy', value_switches=True, enum_switch=False,
1084
safe='Only delete files if they can be'
1085
' safely recovered (default).',
1086
keep="Don't delete any files.",
1506
safe='Backup changed files (default).',
1507
keep='Delete from bzr but leave the working copy.',
1087
1508
force='Delete all the specified files, even if they can not be '
1088
1509
'recovered and even if they are non-empty directories.')]
1510
aliases = ['rm', 'del']
1090
1511
encoding_type = 'replace'
1092
1513
def run(self, file_list, verbose=False, new=False,
1093
1514
file_deletion_strategy='safe'):
1094
tree, file_list = tree_files(file_list)
1515
tree, file_list = WorkingTree.open_containing_paths(file_list)
1096
1517
if file_list is not None:
1097
file_list = [f for f in file_list if f != '']
1099
raise errors.BzrCommandError('Specify one or more files to'
1100
' remove, or use --new.')
1518
file_list = [f for f in file_list]
1520
self.add_cleanup(tree.lock_write().unlock)
1521
# Heuristics should probably all move into tree.remove_smart or
1103
1524
added = tree.changes_from(tree.basis_tree(),
1104
1525
specific_files=file_list).added
1105
1526
file_list = sorted([f[0] for f in added], reverse=True)
1106
1527
if len(file_list) == 0:
1107
1528
raise errors.BzrCommandError('No matching files.')
1529
elif file_list is None:
1530
# missing files show up in iter_changes(basis) as
1531
# versioned-with-no-kind.
1533
for change in tree.iter_changes(tree.basis_tree()):
1534
# Find paths in the working tree that have no kind:
1535
if change[1][1] is not None and change[6][1] is None:
1536
missing.append(change[1][1])
1537
file_list = sorted(missing, reverse=True)
1538
file_deletion_strategy = 'keep'
1108
1539
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1109
1540
keep_files=file_deletion_strategy=='keep',
1110
1541
force=file_deletion_strategy=='force')
1113
1544
class cmd_file_id(Command):
1114
"""Print file_id of a particular file or directory.
1545
__doc__ = """Print file_id of a particular file or directory.
1116
1547
The file_id is assigned when the file is first added and remains the
1117
1548
same through all revisions where the file exists, even when it is
1594
2076
raise errors.BzrCommandError(msg)
2079
def _parse_levels(s):
2083
msg = "The levels argument must be an integer."
2084
raise errors.BzrCommandError(msg)
1597
2087
class cmd_log(Command):
1598
"""Show log of a branch, file, or directory.
1600
By default show the log of the branch containing the working directory.
1602
To request a range of logs, you can use the command -r begin..end
1603
-r revision requests a specific revision, -r ..end or -r begin.. are
1607
Log the current branch::
1615
Log the last 10 revisions of a branch::
1617
bzr log -r -10.. http://server/branch
2088
__doc__ = """Show historical log for a branch or subset of a branch.
2090
log is bzr's default tool for exploring the history of a branch.
2091
The branch to use is taken from the first parameter. If no parameters
2092
are given, the branch containing the working directory is logged.
2093
Here are some simple examples::
2095
bzr log log the current branch
2096
bzr log foo.py log a file in its branch
2097
bzr log http://server/branch log a branch on a server
2099
The filtering, ordering and information shown for each revision can
2100
be controlled as explained below. By default, all revisions are
2101
shown sorted (topologically) so that newer revisions appear before
2102
older ones and descendants always appear before ancestors. If displayed,
2103
merged revisions are shown indented under the revision in which they
2108
The log format controls how information about each revision is
2109
displayed. The standard log formats are called ``long``, ``short``
2110
and ``line``. The default is long. See ``bzr help log-formats``
2111
for more details on log formats.
2113
The following options can be used to control what information is
2116
-l N display a maximum of N revisions
2117
-n N display N levels of revisions (0 for all, 1 for collapsed)
2118
-v display a status summary (delta) for each revision
2119
-p display a diff (patch) for each revision
2120
--show-ids display revision-ids (and file-ids), not just revnos
2122
Note that the default number of levels to display is a function of the
2123
log format. If the -n option is not used, the standard log formats show
2124
just the top level (mainline).
2126
Status summaries are shown using status flags like A, M, etc. To see
2127
the changes explained using words like ``added`` and ``modified``
2128
instead, use the -vv option.
2132
To display revisions from oldest to newest, use the --forward option.
2133
In most cases, using this option will have little impact on the total
2134
time taken to produce a log, though --forward does not incrementally
2135
display revisions like --reverse does when it can.
2137
:Revision filtering:
2139
The -r option can be used to specify what revision or range of revisions
2140
to filter against. The various forms are shown below::
2142
-rX display revision X
2143
-rX.. display revision X and later
2144
-r..Y display up to and including revision Y
2145
-rX..Y display from X to Y inclusive
2147
See ``bzr help revisionspec`` for details on how to specify X and Y.
2148
Some common examples are given below::
2150
-r-1 show just the tip
2151
-r-10.. show the last 10 mainline revisions
2152
-rsubmit:.. show what's new on this branch
2153
-rancestor:path.. show changes since the common ancestor of this
2154
branch and the one at location path
2155
-rdate:yesterday.. show changes since yesterday
2157
When logging a range of revisions using -rX..Y, log starts at
2158
revision Y and searches back in history through the primary
2159
("left-hand") parents until it finds X. When logging just the
2160
top level (using -n1), an error is reported if X is not found
2161
along the way. If multi-level logging is used (-n0), X may be
2162
a nested merge revision and the log will be truncated accordingly.
2166
If parameters are given and the first one is not a branch, the log
2167
will be filtered to show only those revisions that changed the
2168
nominated files or directories.
2170
Filenames are interpreted within their historical context. To log a
2171
deleted file, specify a revision range so that the file existed at
2172
the end or start of the range.
2174
Historical context is also important when interpreting pathnames of
2175
renamed files/directories. Consider the following example:
2177
* revision 1: add tutorial.txt
2178
* revision 2: modify tutorial.txt
2179
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2183
* ``bzr log guide.txt`` will log the file added in revision 1
2185
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2187
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2188
the original file in revision 2.
2190
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2191
was no file called guide.txt in revision 2.
2193
Renames are always followed by log. By design, there is no need to
2194
explicitly ask for this (and no way to stop logging a file back
2195
until it was last renamed).
2199
The --message option can be used for finding revisions that match a
2200
regular expression in a commit message.
2204
GUI tools and IDEs are often better at exploring history than command
2205
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2206
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2207
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2208
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2210
You may find it useful to add the aliases below to ``bazaar.conf``::
2214
top = log -l10 --line
2217
``bzr tip`` will then show the latest revision while ``bzr top``
2218
will show the last 10 mainline revisions. To see the details of a
2219
particular revision X, ``bzr show -rX``.
2221
If you are interested in looking deeper into a particular merge X,
2222
use ``bzr log -n0 -rX``.
2224
``bzr log -v`` on a branch with lots of history is currently
2225
very slow. A fix for this issue is currently under development.
2226
With or without that fix, it is recommended that a revision range
2227
be given when using the -v option.
2229
bzr has a generic full-text matching plugin, bzr-search, that can be
2230
used to find revisions matching user names, commit messages, etc.
2231
Among other features, this plugin can find all revisions containing
2232
a list of words but not others.
2234
When exploring non-mainline history on large projects with deep
2235
history, the performance of log can be greatly improved by installing
2236
the historycache plugin. This plugin buffers historical information
2237
trading disk space for faster speed.
1620
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1622
takes_args = ['location?']
2239
takes_args = ['file*']
2240
_see_also = ['log-formats', 'revisionspec']
1623
2241
takes_options = [
1624
2242
Option('forward',
1625
2243
help='Show from oldest to newest.'),
1628
help='Display timezone as local, original, or utc.'),
2245
custom_help('verbose',
1631
2246
help='Show files changed in each revision.'),
2250
type=bzrlib.option._parse_revision_str,
2252
help='Show just the specified revision.'
2253
' See also "help revisionspec".'),
2255
RegistryOption('authors',
2256
'What names to list as authors - first, all or committer.',
2258
lazy_registry=('bzrlib.log', 'author_list_registry'),
2262
help='Number of levels to display - 0 for all, 1 for flat.',
2264
type=_parse_levels),
1635
2265
Option('message',
1636
2266
short_name='m',
1637
2267
help='Show revisions whose message matches this '
1638
2268
'regular expression.',
1640
2270
Option('limit',
1641
2272
help='Limit the output to the first N revisions.',
1643
2274
type=_parse_limit),
2277
help='Show changes made in each revision as a patch.'),
2278
Option('include-merges',
2279
help='Show merged revisions like --levels 0 does.'),
2280
Option('exclude-common-ancestry',
2281
help='Display only the revisions that are not part'
2282
' of both ancestries (require -rX..Y)'
1645
2285
encoding_type = 'replace'
1647
2287
@display_command
1648
def run(self, location=None, timezone='original',
2288
def run(self, file_list=None, timezone='original',
1650
2290
show_ids=False,
1653
2294
log_format=None,
1656
from bzrlib.log import show_log
1657
assert message is None or isinstance(message, basestring), \
1658
"invalid message argument %r" % message
2299
include_merges=False,
2301
exclude_common_ancestry=False,
2303
from bzrlib.log import (
2305
make_log_request_dict,
2306
_get_info_for_log_files,
1659
2308
direction = (forward and 'forward') or 'reverse'
1664
# find the file id to log:
1666
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1670
tree = b.basis_tree()
1671
file_id = tree.path2id(fp)
2309
if (exclude_common_ancestry
2310
and (revision is None or len(revision) != 2)):
2311
raise errors.BzrCommandError(
2312
'--exclude-common-ancestry requires -r with two revisions')
2317
raise errors.BzrCommandError(
2318
'--levels and --include-merges are mutually exclusive')
2320
if change is not None:
2322
raise errors.RangeInChangeOption()
2323
if revision is not None:
2324
raise errors.BzrCommandError(
2325
'--revision and --change are mutually exclusive')
2330
filter_by_dir = False
2332
# find the file ids to log and check for directory filtering
2333
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2334
revision, file_list, self.add_cleanup)
2335
for relpath, file_id, kind in file_info_list:
1672
2336
if file_id is None:
1673
2337
raise errors.BzrCommandError(
1674
"Path does not have any revision history: %s" %
2338
"Path unknown at end or start of revision range: %s" %
2340
# If the relpath is the top of the tree, we log everything
2345
file_ids.append(file_id)
2346
filter_by_dir = filter_by_dir or (
2347
kind in ['directory', 'tree-reference'])
1678
# FIXME ? log the current subdir only RBC 20060203
2350
# FIXME ? log the current subdir only RBC 20060203
1679
2351
if revision is not None \
1680
2352
and len(revision) > 0 and revision[0].get_branch():
1681
2353
location = revision[0].get_branch()
1796
2536
if path is None:
1801
2540
raise errors.BzrCommandError('cannot specify both --from-root'
1805
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2543
tree, branch, relpath = \
2544
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2546
# Calculate the prefix to use
1811
if revision is not None:
1812
tree = branch.repository.revision_tree(
1813
revision[0].in_history(branch).rev_id)
1815
tree = branch.basis_tree()
1819
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1820
if fp.startswith(relpath):
1821
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1822
if non_recursive and '/' in fp:
1824
if not all and not selection[fc]:
1826
if kind is not None and fkind != kind:
1829
kindch = entry.kind_character()
1830
outstring = '%-8s %s%s' % (fc, fp, kindch)
1831
if show_ids and fid is not None:
1832
outstring = "%-50s %s" % (outstring, fid)
1833
self.outf.write(outstring + '\n')
1835
self.outf.write(fp + '\0')
1838
self.outf.write(fid)
1839
self.outf.write('\0')
1847
self.outf.write('%-50s %s\n' % (fp, my_id))
1849
self.outf.write(fp + '\n')
2550
prefix = relpath + '/'
2551
elif fs_path != '.' and not fs_path.endswith('/'):
2552
prefix = fs_path + '/'
2554
if revision is not None or tree is None:
2555
tree = _get_one_revision_tree('ls', revision, branch=branch)
2558
if isinstance(tree, WorkingTree) and tree.supports_views():
2559
view_files = tree.views.lookup_view()
2562
view_str = views.view_display_str(view_files)
2563
note("Ignoring files outside view. View is %s" % view_str)
2565
self.add_cleanup(tree.lock_read().unlock)
2566
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2567
from_dir=relpath, recursive=recursive):
2568
# Apply additional masking
2569
if not all and not selection[fc]:
2571
if kind is not None and fkind != kind:
2576
fullpath = osutils.pathjoin(relpath, fp)
2579
views.check_path_in_view(tree, fullpath)
2580
except errors.FileOutsideView:
2585
fp = osutils.pathjoin(prefix, fp)
2586
kindch = entry.kind_character()
2587
outstring = fp + kindch
2588
ui.ui_factory.clear_term()
2590
outstring = '%-8s %s' % (fc, outstring)
2591
if show_ids and fid is not None:
2592
outstring = "%-50s %s" % (outstring, fid)
2593
self.outf.write(outstring + '\n')
2595
self.outf.write(fp + '\0')
2598
self.outf.write(fid)
2599
self.outf.write('\0')
2607
self.outf.write('%-50s %s\n' % (outstring, my_id))
2609
self.outf.write(outstring + '\n')
1854
2612
class cmd_unknowns(Command):
1855
"""List unknown files.
2613
__doc__ = """List unknown files.
1859
2617
_see_also = ['ls']
2618
takes_options = ['directory']
1861
2620
@display_command
1863
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2621
def run(self, directory=u'.'):
2622
for f in WorkingTree.open_containing(directory)[0].unknowns():
1864
2623
self.outf.write(osutils.quotefn(f) + '\n')
1867
2626
class cmd_ignore(Command):
1868
"""Ignore specified files or patterns.
2627
__doc__ = """Ignore specified files or patterns.
2629
See ``bzr help patterns`` for details on the syntax of patterns.
2631
If a .bzrignore file does not exist, the ignore command
2632
will create one and add the specified files or patterns to the newly
2633
created file. The ignore command will also automatically add the
2634
.bzrignore file to be versioned. Creating a .bzrignore file without
2635
the use of the ignore command will require an explicit add command.
1870
2637
To remove patterns from the ignore list, edit the .bzrignore file.
1872
Trailing slashes on patterns are ignored.
1873
If the pattern contains a slash or is a regular expression, it is compared
1874
to the whole path from the branch root. Otherwise, it is compared to only
1875
the last component of the path. To match a file only in the root
1876
directory, prepend './'.
1878
Ignore patterns specifying absolute paths are not allowed.
1880
Ignore patterns may include globbing wildcards such as::
1882
? - Matches any single character except '/'
1883
* - Matches 0 or more characters except '/'
1884
/**/ - Matches 0 or more directories in a path
1885
[a-z] - Matches a single character from within a group of characters
1887
Ignore patterns may also be Python regular expressions.
1888
Regular expression ignore patterns are identified by a 'RE:' prefix
1889
followed by the regular expression. Regular expression ignore patterns
1890
may not include named or numbered groups.
1892
Note: ignore patterns containing shell wildcards must be quoted from
2638
After adding, editing or deleting that file either indirectly by
2639
using this command or directly by using an editor, be sure to commit
2642
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2643
the global ignore file can be found in the application data directory as
2644
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2645
Global ignores are not touched by this command. The global ignore file
2646
can be edited directly using an editor.
2648
Patterns prefixed with '!' are exceptions to ignore patterns and take
2649
precedence over regular ignores. Such exceptions are used to specify
2650
files that should be versioned which would otherwise be ignored.
2652
Patterns prefixed with '!!' act as regular ignore patterns, but have
2653
precedence over the '!' exception patterns.
2655
Note: ignore patterns containing shell wildcards must be quoted from
1893
2656
the shell on Unix.
1898
2661
bzr ignore ./Makefile
1900
Ignore class files in all directories::
1902
bzr ignore '*.class'
1904
Ignore .o files under the lib directory::
1906
bzr ignore 'lib/**/*.o'
1908
Ignore .o files under the lib directory::
1910
bzr ignore 'RE:lib/.*\.o'
2663
Ignore .class files in all directories...::
2665
bzr ignore "*.class"
2667
...but do not ignore "special.class"::
2669
bzr ignore "!special.class"
2671
Ignore .o files under the lib directory::
2673
bzr ignore "lib/**/*.o"
2675
Ignore .o files under the lib directory::
2677
bzr ignore "RE:lib/.*\.o"
2679
Ignore everything but the "debian" toplevel directory::
2681
bzr ignore "RE:(?!debian/).*"
2683
Ignore everything except the "local" toplevel directory,
2684
but always ignore "*~" autosave files, even under local/::
2687
bzr ignore "!./local"
1913
_see_also = ['status', 'ignored']
2691
_see_also = ['status', 'ignored', 'patterns']
1914
2692
takes_args = ['name_pattern*']
1916
Option('old-default-rules',
1917
help='Write out the ignore rules bzr < 0.9 always used.')
2693
takes_options = ['directory',
2694
Option('default-rules',
2695
help='Display the default ignore rules that bzr uses.')
1920
def run(self, name_pattern_list=None, old_default_rules=None):
1921
from bzrlib.atomicfile import AtomicFile
1922
if old_default_rules is not None:
1923
# dump the rules and exit
1924
for pattern in ignores.OLD_DEFAULTS:
2698
def run(self, name_pattern_list=None, default_rules=None,
2700
from bzrlib import ignores
2701
if default_rules is not None:
2702
# dump the default rules and exit
2703
for pattern in ignores.USER_DEFAULTS:
2704
self.outf.write("%s\n" % pattern)
1927
2706
if not name_pattern_list:
1928
2707
raise errors.BzrCommandError("ignore requires at least one "
1929
"NAME_PATTERN or --old-default-rules")
1930
name_pattern_list = [globbing.normalize_pattern(p)
2708
"NAME_PATTERN or --default-rules.")
2709
name_pattern_list = [globbing.normalize_pattern(p)
1931
2710
for p in name_pattern_list]
2712
for p in name_pattern_list:
2713
if not globbing.Globster.is_pattern_valid(p):
2714
bad_patterns += ('\n %s' % p)
2716
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2717
ui.ui_factory.show_error(msg)
2718
raise errors.InvalidPattern('')
1932
2719
for name_pattern in name_pattern_list:
1933
if (name_pattern[0] == '/' or
2720
if (name_pattern[0] == '/' or
1934
2721
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1935
2722
raise errors.BzrCommandError(
1936
2723
"NAME_PATTERN should not be an absolute path")
1937
tree, relpath = WorkingTree.open_containing(u'.')
1938
ifn = tree.abspath('.bzrignore')
1939
if os.path.exists(ifn):
1942
igns = f.read().decode('utf-8')
1948
# TODO: If the file already uses crlf-style termination, maybe
1949
# we should use that for the newly added lines?
1951
if igns and igns[-1] != '\n':
1953
for name_pattern in name_pattern_list:
1954
igns += name_pattern + '\n'
1956
f = AtomicFile(ifn, 'wb')
1958
f.write(igns.encode('utf-8'))
1963
if not tree.path2id('.bzrignore'):
1964
tree.add(['.bzrignore'])
2724
tree, relpath = WorkingTree.open_containing(directory)
2725
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2726
ignored = globbing.Globster(name_pattern_list)
2728
self.add_cleanup(tree.lock_read().unlock)
2729
for entry in tree.list_files():
2733
if ignored.match(filename):
2734
matches.append(filename)
2735
if len(matches) > 0:
2736
self.outf.write("Warning: the following files are version controlled and"
2737
" match your ignore pattern:\n%s"
2738
"\nThese files will continue to be version controlled"
2739
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1967
2742
class cmd_ignored(Command):
1968
"""List ignored files and the patterns that matched them.
2743
__doc__ = """List ignored files and the patterns that matched them.
2745
List all the ignored files and the ignore pattern that caused the file to
2748
Alternatively, to list just the files::
1971
_see_also = ['ignore']
2753
encoding_type = 'replace'
2754
_see_also = ['ignore', 'ls']
2755
takes_options = ['directory']
1972
2757
@display_command
1974
tree = WorkingTree.open_containing(u'.')[0]
1977
for path, file_class, kind, file_id, entry in tree.list_files():
1978
if file_class != 'I':
1980
## XXX: Slightly inefficient since this was already calculated
1981
pat = tree.is_ignored(path)
1982
print '%-50s %s' % (path, pat)
2758
def run(self, directory=u'.'):
2759
tree = WorkingTree.open_containing(directory)[0]
2760
self.add_cleanup(tree.lock_read().unlock)
2761
for path, file_class, kind, file_id, entry in tree.list_files():
2762
if file_class != 'I':
2764
## XXX: Slightly inefficient since this was already calculated
2765
pat = tree.is_ignored(path)
2766
self.outf.write('%-50s %s\n' % (path, pat))
1987
2769
class cmd_lookup_revision(Command):
1988
"""Lookup the revision-id from a revision-number
2770
__doc__ = """Lookup the revision-id from a revision-number
1991
2773
bzr lookup-revision 33
1994
2776
takes_args = ['revno']
2777
takes_options = ['directory']
1996
2779
@display_command
1997
def run(self, revno):
2780
def run(self, revno, directory=u'.'):
1999
2782
revno = int(revno)
2000
2783
except ValueError:
2001
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2003
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2784
raise errors.BzrCommandError("not a valid revision-number: %r"
2786
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2787
self.outf.write("%s\n" % revid)
2006
2790
class cmd_export(Command):
2007
"""Export current or past revision to a destination directory or archive.
2791
__doc__ = """Export current or past revision to a destination directory or archive.
2009
2793
If no revision is specified this exports the last committed revision.
2032
2816
================= =========================
2034
takes_args = ['dest', 'branch?']
2818
takes_args = ['dest', 'branch_or_subdir?']
2819
takes_options = ['directory',
2036
2820
Option('format',
2037
2821
help="Type of file to export to.",
2824
Option('filters', help='Apply content filters to export the '
2825
'convenient form.'),
2042
2828
help="Name of the root directory inside the exported file."),
2829
Option('per-file-timestamps',
2830
help='Set modification time of files to that of the last '
2831
'revision in which it was changed.'),
2044
def run(self, dest, branch=None, revision=None, format=None, root=None):
2833
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2834
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2045
2835
from bzrlib.export import export
2048
tree = WorkingTree.open_containing(u'.')[0]
2837
if branch_or_subdir is None:
2838
tree = WorkingTree.open_containing(directory)[0]
2049
2839
b = tree.branch
2051
b = Branch.open(branch)
2053
if revision is None:
2054
# should be tree.last_revision FIXME
2055
rev_id = b.last_revision()
2057
if len(revision) != 1:
2058
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2059
rev_id = revision[0].in_history(b).rev_id
2060
t = b.repository.revision_tree(rev_id)
2842
b, subdir = Branch.open_containing(branch_or_subdir)
2845
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2062
export(t, dest, format, root)
2847
export(rev_tree, dest, format, root, subdir, filtered=filters,
2848
per_file_timestamps=per_file_timestamps)
2063
2849
except errors.NoSuchExportFormat, e:
2064
2850
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2067
2853
class cmd_cat(Command):
2068
"""Write the contents of a file as of a given revision to standard output.
2854
__doc__ = """Write the contents of a file as of a given revision to standard output.
2070
2856
If no revision is nominated, the last revision is used.
2072
2858
Note: Take care to redirect standard output when using this command on a
2076
2862
_see_also = ['ls']
2863
takes_options = ['directory',
2078
2864
Option('name-from-revision', help='The path name in the old tree.'),
2865
Option('filters', help='Apply content filters to display the '
2866
'convenience form.'),
2081
2869
takes_args = ['filename']
2082
2870
encoding_type = 'exact'
2084
2872
@display_command
2085
def run(self, filename, revision=None, name_from_revision=False):
2873
def run(self, filename, revision=None, name_from_revision=False,
2874
filters=False, directory=None):
2086
2875
if revision is not None and len(revision) != 1:
2087
2876
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2092
tree, b, relpath = \
2093
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2094
except errors.NotBranchError:
2097
if revision is not None and revision[0].get_branch() is not None:
2098
b = Branch.open(revision[0].get_branch())
2877
" one revision specifier")
2878
tree, branch, relpath = \
2879
_open_directory_or_containing_tree_or_branch(filename, directory)
2880
self.add_cleanup(branch.lock_read().unlock)
2881
return self._run(tree, branch, relpath, filename, revision,
2882
name_from_revision, filters)
2884
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2099
2886
if tree is None:
2100
2887
tree = b.basis_tree()
2101
if revision is None:
2102
revision_id = b.last_revision()
2104
revision_id = revision[0].in_history(b).rev_id
2888
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2889
self.add_cleanup(rev_tree.lock_read().unlock)
2106
cur_file_id = tree.path2id(relpath)
2107
rev_tree = b.repository.revision_tree(revision_id)
2108
2891
old_file_id = rev_tree.path2id(relpath)
2110
2893
if name_from_revision:
2894
# Try in revision if requested
2111
2895
if old_file_id is None:
2112
raise errors.BzrCommandError("%r is not present in revision %s"
2113
% (filename, revision_id))
2896
raise errors.BzrCommandError(
2897
"%r is not present in revision %s" % (
2898
filename, rev_tree.get_revision_id()))
2115
rev_tree.print_file(old_file_id)
2116
elif cur_file_id is not None:
2117
rev_tree.print_file(cur_file_id)
2118
elif old_file_id is not None:
2119
rev_tree.print_file(old_file_id)
2121
raise errors.BzrCommandError("%r is not present in revision %s" %
2122
(filename, revision_id))
2900
content = rev_tree.get_file_text(old_file_id)
2902
cur_file_id = tree.path2id(relpath)
2904
if cur_file_id is not None:
2905
# Then try with the actual file id
2907
content = rev_tree.get_file_text(cur_file_id)
2909
except errors.NoSuchId:
2910
# The actual file id didn't exist at that time
2912
if not found and old_file_id is not None:
2913
# Finally try with the old file id
2914
content = rev_tree.get_file_text(old_file_id)
2917
# Can't be found anywhere
2918
raise errors.BzrCommandError(
2919
"%r is not present in revision %s" % (
2920
filename, rev_tree.get_revision_id()))
2922
from bzrlib.filters import (
2923
ContentFilterContext,
2924
filtered_output_bytes,
2926
filters = rev_tree._content_filter_stack(relpath)
2927
chunks = content.splitlines(True)
2928
content = filtered_output_bytes(chunks, filters,
2929
ContentFilterContext(relpath, rev_tree))
2931
self.outf.writelines(content)
2934
self.outf.write(content)
2125
2937
class cmd_local_time_offset(Command):
2126
"""Show the offset in seconds from GMT to local time."""
2938
__doc__ = """Show the offset in seconds from GMT to local time."""
2128
2940
@display_command
2130
print osutils.local_time_offset()
2942
self.outf.write("%s\n" % osutils.local_time_offset())
2134
2946
class cmd_commit(Command):
2135
"""Commit changes into a new revision.
2137
If no arguments are given, the entire tree is committed.
2139
If selected files are specified, only changes to those files are
2140
committed. If a directory is specified then the directory and everything
2141
within it is committed.
2143
If author of the change is not the same person as the committer, you can
2144
specify the author's name using the --author option. The name should be
2145
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2147
A selected-file commit may fail in some cases where the committed
2148
tree would be invalid. Consider::
2153
bzr commit foo -m "committing foo"
2154
bzr mv foo/bar foo/baz
2157
bzr commit foo/bar -m "committing bar but not baz"
2159
In the example above, the last commit will fail by design. This gives
2160
the user the opportunity to decide whether they want to commit the
2161
rename at the same time, separately first, or not at all. (As a general
2162
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2164
Note: A selected-file commit after a merge is not yet supported.
2947
__doc__ = """Commit changes into a new revision.
2949
An explanatory message needs to be given for each commit. This is
2950
often done by using the --message option (getting the message from the
2951
command line) or by using the --file option (getting the message from
2952
a file). If neither of these options is given, an editor is opened for
2953
the user to enter the message. To see the changed files in the
2954
boilerplate text loaded into the editor, use the --show-diff option.
2956
By default, the entire tree is committed and the person doing the
2957
commit is assumed to be the author. These defaults can be overridden
2962
If selected files are specified, only changes to those files are
2963
committed. If a directory is specified then the directory and
2964
everything within it is committed.
2966
When excludes are given, they take precedence over selected files.
2967
For example, to commit only changes within foo, but not changes
2970
bzr commit foo -x foo/bar
2972
A selective commit after a merge is not yet supported.
2976
If the author of the change is not the same person as the committer,
2977
you can specify the author's name using the --author option. The
2978
name should be in the same format as a committer-id, e.g.
2979
"John Doe <jdoe@example.com>". If there is more than one author of
2980
the change you can specify the option multiple times, once for each
2985
A common mistake is to forget to add a new file or directory before
2986
running the commit command. The --strict option checks for unknown
2987
files and aborts the commit if any are found. More advanced pre-commit
2988
checks can be implemented by defining hooks. See ``bzr help hooks``
2993
If you accidentially commit the wrong changes or make a spelling
2994
mistake in the commit message say, you can use the uncommit command
2995
to undo it. See ``bzr help uncommit`` for details.
2997
Hooks can also be configured to run after a commit. This allows you
2998
to trigger updates to external systems like bug trackers. The --fixes
2999
option can be used to record the association between a revision and
3000
one or more bugs. See ``bzr help bugs`` for details.
3002
A selective commit may fail in some cases where the committed
3003
tree would be invalid. Consider::
3008
bzr commit foo -m "committing foo"
3009
bzr mv foo/bar foo/baz
3012
bzr commit foo/bar -m "committing bar but not baz"
3014
In the example above, the last commit will fail by design. This gives
3015
the user the opportunity to decide whether they want to commit the
3016
rename at the same time, separately first, or not at all. (As a general
3017
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2166
3019
# TODO: Run hooks on tree to-be-committed, and after commit.
2527
3561
short_name='x',
2528
3562
help='Exclude tests that match this regular'
2529
3563
' expression.'),
3565
help='Output test progress via subunit.'),
2530
3566
Option('strict', help='Fail on missing dependencies or '
2531
3567
'known failures.'),
3568
Option('load-list', type=str, argname='TESTLISTFILE',
3569
help='Load a test id list from a text file.'),
3570
ListOption('debugflag', type=str, short_name='E',
3571
help='Turn on a selftest debug flag.'),
3572
ListOption('starting-with', type=str, argname='TESTID',
3573
param_name='starting_with', short_name='s',
3575
'Load only the tests starting with TESTID.'),
2533
3577
encoding_type = 'replace'
2535
def run(self, testspecs_list=None, verbose=None, one=False,
3580
Command.__init__(self)
3581
self.additional_selftest_args = {}
3583
def run(self, testspecs_list=None, verbose=False, one=False,
2536
3584
transport=None, benchmark=None,
2537
lsprof_timed=None, cache_dir=None,
2538
3586
first=False, list_only=False,
2539
randomize=None, exclude=None, strict=False):
2541
from bzrlib.tests import selftest
2542
import bzrlib.benchmarks as benchmarks
2543
from bzrlib.benchmarks import tree_creator
2544
from bzrlib.version import show_version
3587
randomize=None, exclude=None, strict=False,
3588
load_list=None, debugflag=None, starting_with=None, subunit=False,
3589
parallel=None, lsprof_tests=False):
3590
from bzrlib import tests
2546
if cache_dir is not None:
2547
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2549
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2550
print ' %s (%s python%s)' % (
2552
bzrlib.version_string,
2553
'.'.join(map(str, sys.version_info)),
2556
3592
if testspecs_list is not None:
2557
3593
pattern = '|'.join(testspecs_list)
3598
from bzrlib.tests import SubUnitBzrRunner
3600
raise errors.BzrCommandError("subunit not available. subunit "
3601
"needs to be installed to use --subunit.")
3602
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3603
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3604
# stdout, which would corrupt the subunit stream.
3605
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3606
# following code can be deleted when it's sufficiently deployed
3607
# -- vila/mgz 20100514
3608
if (sys.platform == "win32"
3609
and getattr(sys.stdout, 'fileno', None) is not None):
3611
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3613
self.additional_selftest_args.setdefault(
3614
'suite_decorators', []).append(parallel)
2561
test_suite_factory = benchmarks.test_suite
2564
# TODO: should possibly lock the history file...
2565
benchfile = open(".perf_history", "at", buffering=1)
2567
test_suite_factory = None
3616
raise errors.BzrCommandError(
3617
"--benchmark is no longer supported from bzr 2.2; "
3618
"use bzr-usertest instead")
3619
test_suite_factory = None
3620
selftest_kwargs = {"verbose": verbose,
3622
"stop_on_failure": one,
3623
"transport": transport,
3624
"test_suite_factory": test_suite_factory,
3625
"lsprof_timed": lsprof_timed,
3626
"lsprof_tests": lsprof_tests,
3627
"matching_tests_first": first,
3628
"list_only": list_only,
3629
"random_seed": randomize,
3630
"exclude_pattern": exclude,
3632
"load_list": load_list,
3633
"debug_flags": debugflag,
3634
"starting_with": starting_with
3636
selftest_kwargs.update(self.additional_selftest_args)
3638
# Make deprecation warnings visible, unless -Werror is set
3639
cleanup = symbol_versioning.activate_deprecation_warnings(
2572
result = selftest(verbose=verbose,
2574
stop_on_failure=one,
2575
transport=transport,
2576
test_suite_factory=test_suite_factory,
2577
lsprof_timed=lsprof_timed,
2578
bench_history=benchfile,
2579
matching_tests_first=first,
2580
list_only=list_only,
2581
random_seed=randomize,
2582
exclude_pattern=exclude,
3642
result = tests.selftest(**selftest_kwargs)
2586
if benchfile is not None:
2589
info('tests passed')
2591
info('tests failed')
2592
3645
return int(not result)
2595
3648
class cmd_version(Command):
2596
"""Show version of bzr."""
3649
__doc__ = """Show version of bzr."""
3651
encoding_type = 'replace'
3653
Option("short", help="Print just the version number."),
2598
3656
@display_command
3657
def run(self, short=False):
2600
3658
from bzrlib.version import show_version
3660
self.outf.write(bzrlib.version_string + '\n')
3662
show_version(to_file=self.outf)
2604
3665
class cmd_rocks(Command):
2605
"""Statement of optimism."""
3666
__doc__ = """Statement of optimism."""
2609
3670
@display_command
2611
print "It sure does!"
3672
self.outf.write("It sure does!\n")
2614
3675
class cmd_find_merge_base(Command):
2615
"""Find and print a base revision for merging two branches."""
3676
__doc__ = """Find and print a base revision for merging two branches."""
2616
3677
# TODO: Options to specify revisions on either side, as if
2617
3678
# merging only part of the history.
2618
3679
takes_args = ['branch', 'other']
2621
3682
@display_command
2622
3683
def run(self, branch, other):
2623
from bzrlib.revision import ensure_null, MultipleRevisionSources
3684
from bzrlib.revision import ensure_null
2625
3686
branch1 = Branch.open_containing(branch)[0]
2626
3687
branch2 = Branch.open_containing(other)[0]
3688
self.add_cleanup(branch1.lock_read().unlock)
3689
self.add_cleanup(branch2.lock_read().unlock)
2628
3690
last1 = ensure_null(branch1.last_revision())
2629
3691
last2 = ensure_null(branch2.last_revision())
2631
3693
graph = branch1.repository.get_graph(branch2.repository)
2632
3694
base_rev_id = graph.find_unique_lca(last1, last2)
2634
print 'merge base is revision %s' % base_rev_id
3696
self.outf.write('merge base is revision %s\n' % base_rev_id)
2637
3699
class cmd_merge(Command):
2638
"""Perform a three-way merge.
2640
The branch is the branch you will merge from. By default, it will merge
2641
the latest revision. If you specify a revision, that revision will be
2642
merged. If you specify two revisions, the first will be used as a BASE,
2643
and the second one as OTHER. Revision numbers are always relative to the
3700
__doc__ = """Perform a three-way merge.
3702
The source of the merge can be specified either in the form of a branch,
3703
or in the form of a path to a file containing a merge directive generated
3704
with bzr send. If neither is specified, the default is the upstream branch
3705
or the branch most recently merged using --remember.
3707
When merging a branch, by default the tip will be merged. To pick a different
3708
revision, pass --revision. If you specify two values, the first will be used as
3709
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3710
available revisions, like this is commonly referred to as "cherrypicking".
3712
Revision numbers are always relative to the branch being merged.
2646
3714
By default, bzr will try to merge in all new work from the other
2647
3715
branch, automatically determining an appropriate base. If this
2648
3716
fails, you may need to give an explicit base.
2650
3718
Merge will do its best to combine the changes in two branches, but there
2651
3719
are some kinds of problems only a human can fix. When it encounters those,
2652
3720
it will mark a conflict. A conflict means that you need to fix something,
2724
3811
allow_pending = True
2725
3812
verified = 'inapplicable'
2726
3813
tree = WorkingTree.open_containing(directory)[0]
3816
basis_tree = tree.revision_tree(tree.last_revision())
3817
except errors.NoSuchRevision:
3818
basis_tree = tree.basis_tree()
3820
# die as quickly as possible if there are uncommitted changes
3822
if tree.has_changes():
3823
raise errors.UncommittedChanges(tree)
3825
view_info = _get_view_info_for_change_reporter(tree)
2727
3826
change_reporter = delta._ChangeReporter(
2728
unversioned_filter=tree.is_ignored)
2731
pb = ui.ui_factory.nested_progress_bar()
2732
cleanups.append(pb.finished)
2734
cleanups.append(tree.unlock)
2735
if location is not None:
2736
mergeable, other_transport = _get_mergeable_helper(location)
2739
raise errors.BzrCommandError('Cannot use --uncommitted'
2740
' with bundles or merge directives.')
2742
if revision is not None:
2743
raise errors.BzrCommandError(
2744
'Cannot use -r with merge directives or bundles')
2745
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2747
possible_transports.append(other_transport)
2749
if merger is None and uncommitted:
2750
if revision is not None and len(revision) > 0:
2751
raise errors.BzrCommandError('Cannot use --uncommitted and'
2752
' --revision at the same time.')
2753
location = self._select_branch_location(tree, location)[0]
2754
other_tree, other_path = WorkingTree.open_containing(location)
2755
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2757
allow_pending = False
2760
merger, allow_pending = self._get_merger_from_branch(tree,
2761
location, revision, remember, possible_transports, pb)
2763
merger.merge_type = merge_type
2764
merger.reprocess = reprocess
2765
merger.show_base = show_base
2766
merger.change_reporter = change_reporter
2767
self.sanity_check_merger(merger)
2768
if (merger.base_rev_id == merger.other_rev_id and
2769
merger.other_rev_id != None):
2770
note('Nothing to do.')
2773
if merger.interesting_files is not None:
2774
raise BzrCommandError('Cannot pull individual files')
2775
if (merger.base_rev_id == tree.last_revision()):
2776
result = tree.pull(merger.other_branch, False,
2777
merger.other_rev_id)
2778
result.report(self.outf)
2780
merger.check_basis(not force)
2781
conflict_count = merger.do_merge()
2783
merger.set_pending()
2784
if verified == 'failed':
2785
warning('Preview patch does not match changes')
2786
if conflict_count != 0:
3827
unversioned_filter=tree.is_ignored, view_info=view_info)
3828
pb = ui.ui_factory.nested_progress_bar()
3829
self.add_cleanup(pb.finished)
3830
self.add_cleanup(tree.lock_write().unlock)
3831
if location is not None:
3833
mergeable = bundle.read_mergeable_from_url(location,
3834
possible_transports=possible_transports)
3835
except errors.NotABundle:
3839
raise errors.BzrCommandError('Cannot use --uncommitted'
3840
' with bundles or merge directives.')
3842
if revision is not None:
3843
raise errors.BzrCommandError(
3844
'Cannot use -r with merge directives or bundles')
3845
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3848
if merger is None and uncommitted:
3849
if revision is not None and len(revision) > 0:
3850
raise errors.BzrCommandError('Cannot use --uncommitted and'
3851
' --revision at the same time.')
3852
merger = self.get_merger_from_uncommitted(tree, location, None)
3853
allow_pending = False
3856
merger, allow_pending = self._get_merger_from_branch(tree,
3857
location, revision, remember, possible_transports, None)
3859
merger.merge_type = merge_type
3860
merger.reprocess = reprocess
3861
merger.show_base = show_base
3862
self.sanity_check_merger(merger)
3863
if (merger.base_rev_id == merger.other_rev_id and
3864
merger.other_rev_id is not None):
3865
note('Nothing to do.')
3868
if merger.interesting_files is not None:
3869
raise errors.BzrCommandError('Cannot pull individual files')
3870
if (merger.base_rev_id == tree.last_revision()):
3871
result = tree.pull(merger.other_branch, False,
3872
merger.other_rev_id)
3873
result.report(self.outf)
3875
if merger.this_basis is None:
3876
raise errors.BzrCommandError(
3877
"This branch has no commits."
3878
" (perhaps you would prefer 'bzr pull')")
3880
return self._do_preview(merger)
3882
return self._do_interactive(merger)
3884
return self._do_merge(merger, change_reporter, allow_pending,
3887
def _get_preview(self, merger):
3888
tree_merger = merger.make_merger()
3889
tt = tree_merger.make_preview_transform()
3890
self.add_cleanup(tt.finalize)
3891
result_tree = tt.get_preview_tree()
3894
def _do_preview(self, merger):
3895
from bzrlib.diff import show_diff_trees
3896
result_tree = self._get_preview(merger)
3897
path_encoding = osutils.get_diff_header_encoding()
3898
show_diff_trees(merger.this_tree, result_tree, self.outf,
3899
old_label='', new_label='',
3900
path_encoding=path_encoding)
3902
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3903
merger.change_reporter = change_reporter
3904
conflict_count = merger.do_merge()
3906
merger.set_pending()
3907
if verified == 'failed':
3908
warning('Preview patch does not match changes')
3909
if conflict_count != 0:
3914
def _do_interactive(self, merger):
3915
"""Perform an interactive merge.
3917
This works by generating a preview tree of the merge, then using
3918
Shelver to selectively remove the differences between the working tree
3919
and the preview tree.
3921
from bzrlib import shelf_ui
3922
result_tree = self._get_preview(merger)
3923
writer = bzrlib.option.diff_writer_registry.get()
3924
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3925
reporter=shelf_ui.ApplyReporter(),
3926
diff_writer=writer(sys.stdout))
2791
for cleanup in reversed(cleanups):
2794
3932
def sanity_check_merger(self, merger):
2795
3933
if (merger.show_base and
2796
3934
not merger.merge_type is _mod_merge.Merge3Merger):
2797
3935
raise errors.BzrCommandError("Show-base is not supported for this"
2798
3936
" merge type. %s" % merger.merge_type)
3937
if merger.reprocess is None:
3938
if merger.show_base:
3939
merger.reprocess = False
3941
# Use reprocess if the merger supports it
3942
merger.reprocess = merger.merge_type.supports_reprocess
2799
3943
if merger.reprocess and not merger.merge_type.supports_reprocess:
2800
3944
raise errors.BzrCommandError("Conflict reduction is not supported"
2801
3945
" for merge type %s." %
3156
4361
" or specified.")
3157
4362
display_url = urlutils.unescape_for_display(parent,
3158
4363
self.outf.encoding)
3159
self.outf.write("Using last location: " + display_url + "\n")
4364
message("Using saved parent location: "
4365
+ display_url + "\n")
3161
4367
remote_branch = Branch.open(other_branch)
3162
4368
if remote_branch.base == local_branch.base:
3163
4369
remote_branch = local_branch
3164
local_branch.lock_read()
3166
remote_branch.lock_read()
3168
local_extra, remote_extra = find_unmerged(local_branch,
3170
if log_format is None:
3171
registry = log.log_formatter_registry
3172
log_format = registry.get_default(local_branch)
3173
lf = log_format(to_file=self.outf,
3175
show_timezone='original')
3176
if reverse is False:
3177
local_extra.reverse()
3178
remote_extra.reverse()
3179
if local_extra and not theirs_only:
3180
self.outf.write("You have %d extra revision(s):\n" %
3182
for revision in iter_log_revisions(local_extra,
3183
local_branch.repository,
3185
lf.log_revision(revision)
3186
printed_local = True
3188
printed_local = False
3189
if remote_extra and not mine_only:
3190
if printed_local is True:
3191
self.outf.write("\n\n\n")
3192
self.outf.write("You are missing %d revision(s):\n" %
3194
for revision in iter_log_revisions(remote_extra,
3195
remote_branch.repository,
3197
lf.log_revision(revision)
3198
if not remote_extra and not local_extra:
3200
self.outf.write("Branches are up to date.\n")
3204
remote_branch.unlock()
3206
local_branch.unlock()
4371
self.add_cleanup(remote_branch.lock_read().unlock)
4373
local_revid_range = _revision_range_to_revid_range(
4374
_get_revision_range(my_revision, local_branch,
4377
remote_revid_range = _revision_range_to_revid_range(
4378
_get_revision_range(revision,
4379
remote_branch, self.name()))
4381
local_extra, remote_extra = find_unmerged(
4382
local_branch, remote_branch, restrict,
4383
backward=not reverse,
4384
include_merges=include_merges,
4385
local_revid_range=local_revid_range,
4386
remote_revid_range=remote_revid_range)
4388
if log_format is None:
4389
registry = log.log_formatter_registry
4390
log_format = registry.get_default(local_branch)
4391
lf = log_format(to_file=self.outf,
4393
show_timezone='original')
4396
if local_extra and not theirs_only:
4397
message("You have %d extra revision(s):\n" %
4399
for revision in iter_log_revisions(local_extra,
4400
local_branch.repository,
4402
lf.log_revision(revision)
4403
printed_local = True
4406
printed_local = False
4408
if remote_extra and not mine_only:
4409
if printed_local is True:
4411
message("You are missing %d revision(s):\n" %
4413
for revision in iter_log_revisions(remote_extra,
4414
remote_branch.repository,
4416
lf.log_revision(revision)
4419
if mine_only and not local_extra:
4420
# We checked local, and found nothing extra
4421
message('This branch is up to date.\n')
4422
elif theirs_only and not remote_extra:
4423
# We checked remote, and found nothing extra
4424
message('Other branch is up to date.\n')
4425
elif not (mine_only or theirs_only or local_extra or
4427
# We checked both branches, and neither one had extra
4429
message("Branches are up to date.\n")
3207
4431
if not status_code and parent is None and other_branch is not None:
3208
local_branch.lock_write()
3210
# handle race conditions - a parent might be set while we run.
3211
if local_branch.get_parent() is None:
3212
local_branch.set_parent(remote_branch.base)
3214
local_branch.unlock()
4432
self.add_cleanup(local_branch.lock_write().unlock)
4433
# handle race conditions - a parent might be set while we run.
4434
if local_branch.get_parent() is None:
4435
local_branch.set_parent(remote_branch.base)
3215
4436
return status_code
3218
4439
class cmd_pack(Command):
3219
"""Compress the data within a repository."""
4440
__doc__ = """Compress the data within a repository.
4442
This operation compresses the data within a bazaar repository. As
4443
bazaar supports automatic packing of repository, this operation is
4444
normally not required to be done manually.
4446
During the pack operation, bazaar takes a backup of existing repository
4447
data, i.e. pack files. This backup is eventually removed by bazaar
4448
automatically when it is safe to do so. To save disk space by removing
4449
the backed up pack files, the --clean-obsolete-packs option may be
4452
Warning: If you use --clean-obsolete-packs and your machine crashes
4453
during or immediately after repacking, you may be left with a state
4454
where the deletion has been written to disk but the new packs have not
4455
been. In this case the repository may be unusable.
3221
4458
_see_also = ['repositories']
3222
4459
takes_args = ['branch_or_repo?']
4461
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
3224
def run(self, branch_or_repo='.'):
4464
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3225
4465
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3227
4467
branch = dir.open_branch()
3228
4468
repository = branch.repository
3229
4469
except errors.NotBranchError:
3230
4470
repository = dir.open_repository()
4471
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
3234
4474
class cmd_plugins(Command):
3235
"""List the installed plugins.
3237
This command displays the list of installed plugins including the
3238
path where each one is located and a short description of each.
4475
__doc__ = """List the installed plugins.
4477
This command displays the list of installed plugins including
4478
version of plugin and a short description of each.
4480
--verbose shows the path where each plugin is located.
3240
4482
A plugin is an external component for Bazaar that extends the
3241
4483
revision control system, by adding or replacing code in Bazaar.
3860
5214
'rather than the one containing the working directory.',
3861
5215
short_name='f',
3863
Option('output', short_name='o', help='Write directive to this file.',
5217
Option('output', short_name='o',
5218
help='Write merge directive to this file or directory; '
5219
'use - for stdout.',
5222
help='Refuse to send if there are uncommitted changes in'
5223
' the working tree, --no-strict disables the check.'),
3865
5224
Option('mail-to', help='Mail the request to this address.',
3869
RegistryOption.from_kwargs('format',
3870
'Use the specified output format.',
3871
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
3872
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5228
Option('body', help='Body for the email.', type=unicode),
5229
RegistryOption('format',
5230
help='Use the specified output format.',
5231
lazy_registry=('bzrlib.send', 'format_registry')),
3875
5234
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
3876
5235
no_patch=False, revision=None, remember=False, output=None,
3877
format='4', mail_to=None, message=None, **kwargs):
3878
return self._run(submit_branch, revision, public_branch, remember,
3879
format, no_bundle, no_patch, output,
3880
kwargs.get('from', '.'), mail_to, message)
3882
def _run(self, submit_branch, revision, public_branch, remember, format,
3883
no_bundle, no_patch, output, from_, mail_to, message):
3884
from bzrlib.revision import ensure_null, NULL_REVISION
3886
outfile = StringIO()
3890
outfile = open(output, 'wb')
3892
branch = Branch.open_containing(from_)[0]
3894
config = branch.get_config()
3896
mail_to = config.get_user_option('submit_to')
3898
raise errors.BzrCommandError('No mail-to address'
3900
mail_client = config.get_mail_client()
3901
if remember and submit_branch is None:
3902
raise errors.BzrCommandError(
3903
'--remember requires a branch to be specified.')
3904
stored_submit_branch = branch.get_submit_branch()
3905
remembered_submit_branch = False
3906
if submit_branch is None:
3907
submit_branch = stored_submit_branch
3908
remembered_submit_branch = True
3910
if stored_submit_branch is None or remember:
3911
branch.set_submit_branch(submit_branch)
3912
if submit_branch is None:
3913
submit_branch = branch.get_parent()
3914
remembered_submit_branch = True
3915
if submit_branch is None:
3916
raise errors.BzrCommandError('No submit branch known or'
3918
if remembered_submit_branch:
3919
note('Using saved location: %s', submit_branch)
3921
stored_public_branch = branch.get_public_branch()
3922
if public_branch is None:
3923
public_branch = stored_public_branch
3924
elif stored_public_branch is None or remember:
3925
branch.set_public_branch(public_branch)
3926
if no_bundle and public_branch is None:
3927
raise errors.BzrCommandError('No public branch specified or'
3929
base_revision_id = None
3931
if revision is not None:
3932
if len(revision) > 2:
3933
raise errors.BzrCommandError('bzr send takes '
3934
'at most two one revision identifiers')
3935
revision_id = revision[-1].in_history(branch).rev_id
3936
if len(revision) == 2:
3937
base_revision_id = revision[0].in_history(branch).rev_id
3938
if revision_id is None:
3939
revision_id = branch.last_revision()
3940
if revision_id == NULL_REVISION:
3941
raise errors.BzrCommandError('No revisions to submit.')
3943
directive = merge_directive.MergeDirective2.from_objects(
3944
branch.repository, revision_id, time.time(),
3945
osutils.local_time_offset(), submit_branch,
3946
public_branch=public_branch, include_patch=not no_patch,
3947
include_bundle=not no_bundle, message=message,
3948
base_revision_id=base_revision_id)
3949
elif format == '0.9':
3952
patch_type = 'bundle'
3954
raise errors.BzrCommandError('Format 0.9 does not'
3955
' permit bundle with no patch')
3961
directive = merge_directive.MergeDirective.from_objects(
3962
branch.repository, revision_id, time.time(),
3963
osutils.local_time_offset(), submit_branch,
3964
public_branch=public_branch, patch_type=patch_type,
3967
outfile.writelines(directive.to_lines())
3969
subject = '[MERGE] '
3970
if message is not None:
3973
revision = branch.repository.get_revision(revision_id)
3974
subject += revision.get_summary()
3975
mail_client.compose_merge_request(mail_to, subject,
5236
format=None, mail_to=None, message=None, body=None,
5237
strict=None, **kwargs):
5238
from bzrlib.send import send
5239
return send(submit_branch, revision, public_branch, remember,
5240
format, no_bundle, no_patch, output,
5241
kwargs.get('from', '.'), mail_to, message, body,
3982
5246
class cmd_bundle_revisions(cmd_send):
3984
"""Create a merge-directive for submiting changes.
5247
__doc__ = """Create a merge-directive for submitting changes.
3986
5249
A merge directive provides many things needed for requesting merges:
4059
5326
Tags are stored in the branch. Tags are copied from one branch to another
4060
5327
along when you branch, push, pull or merge.
4062
It is an error to give a tag name that already exists unless you pass
5329
It is an error to give a tag name that already exists unless you pass
4063
5330
--force, in which case the tag is moved to point to the new revision.
5332
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5333
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5335
If no tag name is specified it will be determined through the
5336
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5337
upstream releases by reading configure.ac. See ``bzr help hooks`` for
4066
5341
_see_also = ['commit', 'tags']
4067
takes_args = ['tag_name']
5342
takes_args = ['tag_name?']
4068
5343
takes_options = [
4069
5344
Option('delete',
4070
5345
help='Delete this tag rather than placing it.',
4073
help='Branch in which to place the tag.',
5347
custom_help('directory',
5348
help='Branch in which to place the tag.'),
4077
5349
Option('force',
4078
5350
help='Replace existing tags.',
4083
def run(self, tag_name,
5355
def run(self, tag_name=None,
4089
5361
branch, relpath = Branch.open_containing(directory)
4093
branch.tags.delete_tag(tag_name)
4094
self.outf.write('Deleted tag %s.\n' % tag_name)
5362
self.add_cleanup(branch.lock_write().unlock)
5364
if tag_name is None:
5365
raise errors.BzrCommandError("No tag specified to delete.")
5366
branch.tags.delete_tag(tag_name)
5367
self.outf.write('Deleted tag %s.\n' % tag_name)
5370
if len(revision) != 1:
5371
raise errors.BzrCommandError(
5372
"Tags can only be placed on a single revision, "
5374
revision_id = revision[0].as_revision_id(branch)
4097
if len(revision) != 1:
4098
raise errors.BzrCommandError(
4099
"Tags can only be placed on a single revision, "
4101
revision_id = revision[0].in_history(branch).rev_id
4103
revision_id = branch.last_revision()
4104
if (not force) and branch.tags.has_tag(tag_name):
4105
raise errors.TagAlreadyExists(tag_name)
4106
branch.tags.set_tag(tag_name, revision_id)
4107
self.outf.write('Created tag %s.\n' % tag_name)
5376
revision_id = branch.last_revision()
5377
if tag_name is None:
5378
tag_name = branch.automatic_tag_name(revision_id)
5379
if tag_name is None:
5380
raise errors.BzrCommandError(
5381
"Please specify a tag name.")
5382
if (not force) and branch.tags.has_tag(tag_name):
5383
raise errors.TagAlreadyExists(tag_name)
5384
branch.tags.set_tag(tag_name, revision_id)
5385
self.outf.write('Created tag %s.\n' % tag_name)
4112
5388
class cmd_tags(Command):
5389
__doc__ = """List tags.
4115
This tag shows a table of tag names and the revisions they reference.
5391
This command shows a table of tag names and the revisions they reference.
4118
5394
_see_also = ['tag']
4119
5395
takes_options = [
4121
help='Branch whose tags should be displayed.',
5396
custom_help('directory',
5397
help='Branch whose tags should be displayed.'),
5398
RegistryOption.from_kwargs('sort',
5399
'Sort tags by different criteria.', title='Sorting',
5400
alpha='Sort tags lexicographically (default).',
5401
time='Sort tags chronologically.',
4127
5407
@display_command
4131
5414
branch, relpath = Branch.open_containing(directory)
4132
for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4133
self.outf.write('%-20s %s\n' % (tag_name, target))
4136
def _create_prefix(cur_transport):
4137
needed = [cur_transport]
4138
# Recurse upwards until we can create a directory successfully
4140
new_transport = cur_transport.clone('..')
4141
if new_transport.base == cur_transport.base:
4142
raise errors.BzrCommandError(
4143
"Failed to create path prefix for %s."
4144
% cur_transport.base)
4146
new_transport.mkdir('.')
4147
except errors.NoSuchFile:
4148
needed.append(new_transport)
4149
cur_transport = new_transport
4152
# Now we only need to create child directories
4154
cur_transport = needed.pop()
4155
cur_transport.ensure_base()
4158
def _get_mergeable_helper(location):
4159
"""Get a merge directive or bundle if 'location' points to one.
4161
Try try to identify a bundle and returns its mergeable form. If it's not,
4162
we return the tried transport anyway so that it can reused to access the
4165
:param location: can point to a bundle or a branch.
4167
:return: mergeable, transport
4170
url = urlutils.normalize_url(location)
4171
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4172
location_transport = transport.get_transport(url)
4175
# There may be redirections but we ignore the intermediate
4176
# and final transports used
4177
read = bundle.read_mergeable_from_transport
4178
mergeable, t = read(location_transport, filename)
4179
except errors.NotABundle:
4180
# Continue on considering this url a Branch but adjust the
4181
# location_transport
4182
location_transport = location_transport.clone(filename)
4183
return mergeable, location_transport
4186
# these get imported and then picked up by the scan for cmd_*
4187
# TODO: Some more consistent way to split command definitions across files;
4188
# we do need to load at least some information about them to know of
4189
# aliases. ideally we would avoid loading the implementation until the
4190
# details were needed.
4191
from bzrlib.cmd_version_info import cmd_version_info
4192
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4193
from bzrlib.bundle.commands import (
4196
from bzrlib.sign_my_commits import cmd_sign_my_commits
4197
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4198
cmd_weave_plan_merge, cmd_weave_merge_text
5416
tags = branch.tags.get_tag_dict().items()
5420
self.add_cleanup(branch.lock_read().unlock)
5422
graph = branch.repository.get_graph()
5423
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5424
revid1, revid2 = rev1.rev_id, rev2.rev_id
5425
# only show revisions between revid1 and revid2 (inclusive)
5426
tags = [(tag, revid) for tag, revid in tags if
5427
graph.is_between(revid, revid1, revid2)]
5430
elif sort == 'time':
5432
for tag, revid in tags:
5434
revobj = branch.repository.get_revision(revid)
5435
except errors.NoSuchRevision:
5436
timestamp = sys.maxint # place them at the end
5438
timestamp = revobj.timestamp
5439
timestamps[revid] = timestamp
5440
tags.sort(key=lambda x: timestamps[x[1]])
5442
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5443
for index, (tag, revid) in enumerate(tags):
5445
revno = branch.revision_id_to_dotted_revno(revid)
5446
if isinstance(revno, tuple):
5447
revno = '.'.join(map(str, revno))
5448
except errors.NoSuchRevision:
5449
# Bad tag data/merges can lead to tagged revisions
5450
# which are not in this branch. Fail gracefully ...
5452
tags[index] = (tag, revno)
5454
for tag, revspec in tags:
5455
self.outf.write('%-20s %s\n' % (tag, revspec))
5458
class cmd_reconfigure(Command):
5459
__doc__ = """Reconfigure the type of a bzr directory.
5461
A target configuration must be specified.
5463
For checkouts, the bind-to location will be auto-detected if not specified.
5464
The order of preference is
5465
1. For a lightweight checkout, the current bound location.
5466
2. For branches that used to be checkouts, the previously-bound location.
5467
3. The push location.
5468
4. The parent location.
5469
If none of these is available, --bind-to must be specified.
5472
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5473
takes_args = ['location?']
5475
RegistryOption.from_kwargs(
5477
title='Target type',
5478
help='The type to reconfigure the directory to.',
5479
value_switches=True, enum_switch=False,
5480
branch='Reconfigure to be an unbound branch with no working tree.',
5481
tree='Reconfigure to be an unbound branch with a working tree.',
5482
checkout='Reconfigure to be a bound branch with a working tree.',
5483
lightweight_checkout='Reconfigure to be a lightweight'
5484
' checkout (with no local history).',
5485
standalone='Reconfigure to be a standalone branch '
5486
'(i.e. stop using shared repository).',
5487
use_shared='Reconfigure to use a shared repository.',
5488
with_trees='Reconfigure repository to create '
5489
'working trees on branches by default.',
5490
with_no_trees='Reconfigure repository to not create '
5491
'working trees on branches by default.'
5493
Option('bind-to', help='Branch to bind checkout to.', type=str),
5495
help='Perform reconfiguration even if local changes'
5497
Option('stacked-on',
5498
help='Reconfigure a branch to be stacked on another branch.',
5502
help='Reconfigure a branch to be unstacked. This '
5503
'may require copying substantial data into it.',
5507
def run(self, location=None, target_type=None, bind_to=None, force=False,
5510
directory = bzrdir.BzrDir.open(location)
5511
if stacked_on and unstacked:
5512
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5513
elif stacked_on is not None:
5514
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5516
reconfigure.ReconfigureUnstacked().apply(directory)
5517
# At the moment you can use --stacked-on and a different
5518
# reconfiguration shape at the same time; there seems no good reason
5520
if target_type is None:
5521
if stacked_on or unstacked:
5524
raise errors.BzrCommandError('No target configuration '
5526
elif target_type == 'branch':
5527
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5528
elif target_type == 'tree':
5529
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5530
elif target_type == 'checkout':
5531
reconfiguration = reconfigure.Reconfigure.to_checkout(
5533
elif target_type == 'lightweight-checkout':
5534
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5536
elif target_type == 'use-shared':
5537
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5538
elif target_type == 'standalone':
5539
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5540
elif target_type == 'with-trees':
5541
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5543
elif target_type == 'with-no-trees':
5544
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5546
reconfiguration.apply(force)
5549
class cmd_switch(Command):
5550
__doc__ = """Set the branch of a checkout and update.
5552
For lightweight checkouts, this changes the branch being referenced.
5553
For heavyweight checkouts, this checks that there are no local commits
5554
versus the current bound branch, then it makes the local branch a mirror
5555
of the new location and binds to it.
5557
In both cases, the working tree is updated and uncommitted changes
5558
are merged. The user can commit or revert these as they desire.
5560
Pending merges need to be committed or reverted before using switch.
5562
The path to the branch to switch to can be specified relative to the parent
5563
directory of the current branch. For example, if you are currently in a
5564
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5567
Bound branches use the nickname of its master branch unless it is set
5568
locally, in which case switching will update the local nickname to be
5572
takes_args = ['to_location?']
5573
takes_options = ['directory',
5575
help='Switch even if local commits will be lost.'),
5577
Option('create-branch', short_name='b',
5578
help='Create the target branch from this one before'
5579
' switching to it.'),
5582
def run(self, to_location=None, force=False, create_branch=False,
5583
revision=None, directory=u'.'):
5584
from bzrlib import switch
5585
tree_location = directory
5586
revision = _get_one_revision('switch', revision)
5587
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5588
if to_location is None:
5589
if revision is None:
5590
raise errors.BzrCommandError('You must supply either a'
5591
' revision or a location')
5592
to_location = tree_location
5594
branch = control_dir.open_branch()
5595
had_explicit_nick = branch.get_config().has_explicit_nickname()
5596
except errors.NotBranchError:
5598
had_explicit_nick = False
5601
raise errors.BzrCommandError('cannot create branch without'
5603
to_location = directory_service.directories.dereference(
5605
if '/' not in to_location and '\\' not in to_location:
5606
# This path is meant to be relative to the existing branch
5607
this_url = self._get_branch_location(control_dir)
5608
to_location = urlutils.join(this_url, '..', to_location)
5609
to_branch = branch.bzrdir.sprout(to_location,
5610
possible_transports=[branch.bzrdir.root_transport],
5611
source_branch=branch).open_branch()
5614
to_branch = Branch.open(to_location)
5615
except errors.NotBranchError:
5616
this_url = self._get_branch_location(control_dir)
5617
to_branch = Branch.open(
5618
urlutils.join(this_url, '..', to_location))
5619
if revision is not None:
5620
revision = revision.as_revision_id(to_branch)
5621
switch.switch(control_dir, to_branch, force, revision_id=revision)
5622
if had_explicit_nick:
5623
branch = control_dir.open_branch() #get the new branch!
5624
branch.nick = to_branch.nick
5625
note('Switched to branch: %s',
5626
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5628
def _get_branch_location(self, control_dir):
5629
"""Return location of branch for this control dir."""
5631
this_branch = control_dir.open_branch()
5632
# This may be a heavy checkout, where we want the master branch
5633
master_location = this_branch.get_bound_location()
5634
if master_location is not None:
5635
return master_location
5636
# If not, use a local sibling
5637
return this_branch.base
5638
except errors.NotBranchError:
5639
format = control_dir.find_branch_format()
5640
if getattr(format, 'get_reference', None) is not None:
5641
return format.get_reference(control_dir)
5643
return control_dir.root_transport.base
5646
class cmd_view(Command):
5647
__doc__ = """Manage filtered views.
5649
Views provide a mask over the tree so that users can focus on
5650
a subset of a tree when doing their work. After creating a view,
5651
commands that support a list of files - status, diff, commit, etc -
5652
effectively have that list of files implicitly given each time.
5653
An explicit list of files can still be given but those files
5654
must be within the current view.
5656
In most cases, a view has a short life-span: it is created to make
5657
a selected change and is deleted once that change is committed.
5658
At other times, you may wish to create one or more named views
5659
and switch between them.
5661
To disable the current view without deleting it, you can switch to
5662
the pseudo view called ``off``. This can be useful when you need
5663
to see the whole tree for an operation or two (e.g. merge) but
5664
want to switch back to your view after that.
5667
To define the current view::
5669
bzr view file1 dir1 ...
5671
To list the current view::
5675
To delete the current view::
5679
To disable the current view without deleting it::
5681
bzr view --switch off
5683
To define a named view and switch to it::
5685
bzr view --name view-name file1 dir1 ...
5687
To list a named view::
5689
bzr view --name view-name
5691
To delete a named view::
5693
bzr view --name view-name --delete
5695
To switch to a named view::
5697
bzr view --switch view-name
5699
To list all views defined::
5703
To delete all views::
5705
bzr view --delete --all
5709
takes_args = ['file*']
5712
help='Apply list or delete action to all views.',
5715
help='Delete the view.',
5718
help='Name of the view to define, list or delete.',
5722
help='Name of the view to switch to.',
5727
def run(self, file_list,
5733
tree, file_list = WorkingTree.open_containing_paths(file_list,
5735
current_view, view_dict = tree.views.get_view_info()
5740
raise errors.BzrCommandError(
5741
"Both --delete and a file list specified")
5743
raise errors.BzrCommandError(
5744
"Both --delete and --switch specified")
5746
tree.views.set_view_info(None, {})
5747
self.outf.write("Deleted all views.\n")
5749
raise errors.BzrCommandError("No current view to delete")
5751
tree.views.delete_view(name)
5752
self.outf.write("Deleted '%s' view.\n" % name)
5755
raise errors.BzrCommandError(
5756
"Both --switch and a file list specified")
5758
raise errors.BzrCommandError(
5759
"Both --switch and --all specified")
5760
elif switch == 'off':
5761
if current_view is None:
5762
raise errors.BzrCommandError("No current view to disable")
5763
tree.views.set_view_info(None, view_dict)
5764
self.outf.write("Disabled '%s' view.\n" % (current_view))
5766
tree.views.set_view_info(switch, view_dict)
5767
view_str = views.view_display_str(tree.views.lookup_view())
5768
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5771
self.outf.write('Views defined:\n')
5772
for view in sorted(view_dict):
5773
if view == current_view:
5777
view_str = views.view_display_str(view_dict[view])
5778
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5780
self.outf.write('No views defined.\n')
5783
# No name given and no current view set
5786
raise errors.BzrCommandError(
5787
"Cannot change the 'off' pseudo view")
5788
tree.views.set_view(name, sorted(file_list))
5789
view_str = views.view_display_str(tree.views.lookup_view())
5790
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5794
# No name given and no current view set
5795
self.outf.write('No current view.\n')
5797
view_str = views.view_display_str(tree.views.lookup_view(name))
5798
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5801
class cmd_hooks(Command):
5802
__doc__ = """Show hooks."""
5807
for hook_key in sorted(hooks.known_hooks.keys()):
5808
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5809
self.outf.write("%s:\n" % type(some_hooks).__name__)
5810
for hook_name, hook_point in sorted(some_hooks.items()):
5811
self.outf.write(" %s:\n" % (hook_name,))
5812
found_hooks = list(hook_point)
5814
for hook in found_hooks:
5815
self.outf.write(" %s\n" %
5816
(some_hooks.get_hook_name(hook),))
5818
self.outf.write(" <no hooks installed>\n")
5821
class cmd_remove_branch(Command):
5822
__doc__ = """Remove a branch.
5824
This will remove the branch from the specified location but
5825
will keep any working tree or repository in place.
5829
Remove the branch at repo/trunk::
5831
bzr remove-branch repo/trunk
5835
takes_args = ["location?"]
5837
aliases = ["rmbranch"]
5839
def run(self, location=None):
5840
if location is None:
5842
branch = Branch.open_containing(location)[0]
5843
branch.bzrdir.destroy_branch()
5846
class cmd_shelve(Command):
5847
__doc__ = """Temporarily set aside some changes from the current tree.
5849
Shelve allows you to temporarily put changes you've made "on the shelf",
5850
ie. out of the way, until a later time when you can bring them back from
5851
the shelf with the 'unshelve' command. The changes are stored alongside
5852
your working tree, and so they aren't propagated along with your branch nor
5853
will they survive its deletion.
5855
If shelve --list is specified, previously-shelved changes are listed.
5857
Shelve is intended to help separate several sets of changes that have
5858
been inappropriately mingled. If you just want to get rid of all changes
5859
and you don't need to restore them later, use revert. If you want to
5860
shelve all text changes at once, use shelve --all.
5862
If filenames are specified, only the changes to those files will be
5863
shelved. Other files will be left untouched.
5865
If a revision is specified, changes since that revision will be shelved.
5867
You can put multiple items on the shelf, and by default, 'unshelve' will
5868
restore the most recently shelved changes.
5871
takes_args = ['file*']
5876
Option('all', help='Shelve all changes.'),
5878
RegistryOption('writer', 'Method to use for writing diffs.',
5879
bzrlib.option.diff_writer_registry,
5880
value_switches=True, enum_switch=False),
5882
Option('list', help='List shelved changes.'),
5884
help='Destroy removed changes instead of shelving them.'),
5886
_see_also = ['unshelve']
5888
def run(self, revision=None, all=False, file_list=None, message=None,
5889
writer=None, list=False, destroy=False, directory=u'.'):
5891
return self.run_for_list()
5892
from bzrlib.shelf_ui import Shelver
5894
writer = bzrlib.option.diff_writer_registry.get()
5896
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5897
file_list, message, destroy=destroy, directory=directory)
5902
except errors.UserAbort:
5905
def run_for_list(self):
5906
tree = WorkingTree.open_containing('.')[0]
5907
self.add_cleanup(tree.lock_read().unlock)
5908
manager = tree.get_shelf_manager()
5909
shelves = manager.active_shelves()
5910
if len(shelves) == 0:
5911
note('No shelved changes.')
5913
for shelf_id in reversed(shelves):
5914
message = manager.get_metadata(shelf_id).get('message')
5916
message = '<no message>'
5917
self.outf.write('%3d: %s\n' % (shelf_id, message))
5921
class cmd_unshelve(Command):
5922
__doc__ = """Restore shelved changes.
5924
By default, the most recently shelved changes are restored. However if you
5925
specify a shelf by id those changes will be restored instead. This works
5926
best when the changes don't depend on each other.
5929
takes_args = ['shelf_id?']
5932
RegistryOption.from_kwargs(
5933
'action', help="The action to perform.",
5934
enum_switch=False, value_switches=True,
5935
apply="Apply changes and remove from the shelf.",
5936
dry_run="Show changes, but do not apply or remove them.",
5937
preview="Instead of unshelving the changes, show the diff that "
5938
"would result from unshelving.",
5939
delete_only="Delete changes without applying them.",
5940
keep="Apply changes but don't delete them.",
5943
_see_also = ['shelve']
5945
def run(self, shelf_id=None, action='apply', directory=u'.'):
5946
from bzrlib.shelf_ui import Unshelver
5947
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5951
unshelver.tree.unlock()
5954
class cmd_clean_tree(Command):
5955
__doc__ = """Remove unwanted files from working tree.
5957
By default, only unknown files, not ignored files, are deleted. Versioned
5958
files are never deleted.
5960
Another class is 'detritus', which includes files emitted by bzr during
5961
normal operations and selftests. (The value of these files decreases with
5964
If no options are specified, unknown files are deleted. Otherwise, option
5965
flags are respected, and may be combined.
5967
To check what clean-tree will do, use --dry-run.
5969
takes_options = ['directory',
5970
Option('ignored', help='Delete all ignored files.'),
5971
Option('detritus', help='Delete conflict files, merge'
5972
' backups, and failed selftest dirs.'),
5974
help='Delete files unknown to bzr (default).'),
5975
Option('dry-run', help='Show files to delete instead of'
5977
Option('force', help='Do not prompt before deleting.')]
5978
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5979
force=False, directory=u'.'):
5980
from bzrlib.clean_tree import clean_tree
5981
if not (unknown or ignored or detritus):
5985
clean_tree(directory, unknown=unknown, ignored=ignored,
5986
detritus=detritus, dry_run=dry_run, no_prompt=force)
5989
class cmd_reference(Command):
5990
__doc__ = """list, view and set branch locations for nested trees.
5992
If no arguments are provided, lists the branch locations for nested trees.
5993
If one argument is provided, display the branch location for that tree.
5994
If two arguments are provided, set the branch location for that tree.
5999
takes_args = ['path?', 'location?']
6001
def run(self, path=None, location=None):
6003
if path is not None:
6005
tree, branch, relpath =(
6006
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6007
if path is not None:
6010
tree = branch.basis_tree()
6012
info = branch._get_all_reference_info().iteritems()
6013
self._display_reference_info(tree, branch, info)
6015
file_id = tree.path2id(path)
6017
raise errors.NotVersionedError(path)
6018
if location is None:
6019
info = [(file_id, branch.get_reference_info(file_id))]
6020
self._display_reference_info(tree, branch, info)
6022
branch.set_reference_info(file_id, path, location)
6024
def _display_reference_info(self, tree, branch, info):
6026
for file_id, (path, location) in info:
6028
path = tree.id2path(file_id)
6029
except errors.NoSuchId:
6031
ref_list.append((path, location))
6032
for path, location in sorted(ref_list):
6033
self.outf.write('%s %s\n' % (path, location))
6036
def _register_lazy_builtins():
6037
# register lazy builtins from other modules; called at startup and should
6038
# be only called once.
6039
for (name, aliases, module_name) in [
6040
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6041
('cmd_dpush', [], 'bzrlib.foreign'),
6042
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6043
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6044
('cmd_conflicts', [], 'bzrlib.conflicts'),
6045
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6047
builtin_command_registry.register_lazy(name, aliases, module_name)