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
29
from bzrlib import (
42
41
merge as _mod_merge,
47
46
revision as _mod_revision,
55
55
from bzrlib.branch import Branch
56
56
from bzrlib.conflicts import ConflictList
57
from bzrlib.revisionspec import RevisionSpec
57
from bzrlib.transport import memory
58
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
58
59
from bzrlib.smtp_connection import SMTPConnection
59
60
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]))
63
from bzrlib.commands import (
65
builtin_command_registry,
68
from bzrlib.option import (
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
78
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
79
def tree_files(file_list, default_branch=u'.', canonicalize=True,
81
return internal_tree_files(file_list, default_branch, canonicalize,
85
def tree_files_for_add(file_list):
87
Return a tree and list of absolute paths from a file list.
89
Similar to tree_files, but add handles files a bit differently, so it a
90
custom implementation. In particular, MutableTreeTree.smart_add expects
91
absolute paths, which it immediately converts to relative paths.
93
# FIXME Would be nice to just return the relative paths like
94
# internal_tree_files does, but there are a large number of unit tests
95
# that assume the current interface to mutabletree.smart_add
97
tree, relpath = WorkingTree.open_containing(file_list[0])
98
if tree.supports_views():
99
view_files = tree.views.lookup_view()
101
for filename in file_list:
102
if not osutils.is_inside_any(view_files, filename):
103
raise errors.FileOutsideView(filename, view_files)
104
file_list = file_list[:]
105
file_list[0] = tree.abspath(relpath)
107
tree = WorkingTree.open_containing(u'.')[0]
108
if tree.supports_views():
109
view_files = tree.views.lookup_view()
111
file_list = view_files
112
view_str = views.view_display_str(view_files)
113
note("Ignoring files outside view. View is %s" % view_str)
114
return tree, file_list
117
def _get_one_revision(command_name, revisions):
118
if revisions is None:
120
if len(revisions) != 1:
121
raise errors.BzrCommandError(
122
'bzr %s --revision takes exactly one revision identifier' % (
127
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
128
"""Get a revision tree. Not suitable for commands that change the tree.
130
Specifically, the basis tree in dirstate trees is coupled to the dirstate
131
and doing a commit/uncommit/pull will at best fail due to changing the
134
If tree is passed in, it should be already locked, for lifetime management
135
of the trees internal cached state.
139
if revisions is None:
141
rev_tree = tree.basis_tree()
143
rev_tree = branch.basis_tree()
145
revision = _get_one_revision(command_name, revisions)
146
rev_tree = revision.as_tree(branch)
76
150
# XXX: Bad function name; should possibly also be a class method of
77
151
# WorkingTree rather than a function.
78
def internal_tree_files(file_list, default_branch=u'.'):
152
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
153
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
79
155
"""Convert command-line paths to a WorkingTree and relative paths.
157
Deprecated: use WorkingTree.open_containing_paths instead.
81
159
This is typically used for command-line processors that take one or
82
160
more filenames, and infer the workingtree that contains them.
84
162
The filenames given are not required to exist.
86
:param file_list: Filenames to convert.
164
:param file_list: Filenames to convert.
88
166
:param default_branch: Fallback tree path to use if file_list is empty or
169
:param apply_view: if True and a view is set, apply it or check that
170
specified files are within it
91
172
: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()
174
return WorkingTree.open_containing_paths(
175
file_list, default_directory='.',
180
def _get_view_info_for_change_reporter(tree):
181
"""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)
184
current_view = tree.views.get_view_info()[0]
185
if current_view is not None:
186
view_info = (current_view, tree.views.lookup_view())
187
except errors.ViewsNotSupported:
192
def _open_directory_or_containing_tree_or_branch(filename, directory):
193
"""Open the tree or branch containing the specified file, unless
194
the --directory option is used to specify a different branch."""
195
if directory is not None:
196
return (None, Branch.open(directory), filename)
197
return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
119
200
# TODO: Make sure no commands unconditionally use the working directory as a
150
231
Not versioned and not matching an ignore pattern.
233
Additionally for directories, symlinks and files with an executable
234
bit, Bazaar indicates their type using a trailing character: '/', '@'
152
237
To see ignored files use 'bzr ignored'. For details on the
153
238
changes to file texts, use 'bzr diff'.
155
--short gives a status flags for each item, similar to the SVN's status
240
Note that --short or -S gives status flags for each item, similar
241
to Subversion's status command. To get output similar to svn -q,
158
244
If no arguments are specified, the status of the entire working
159
245
directory is shown. Otherwise, only the status of the specified
160
246
files or directories is reported. If a directory is given, status
161
247
is reported for everything inside that directory.
249
Before merges are committed, the pending merge tip revisions are
250
shown. To see all pending merge revisions, use the -v option.
251
To skip the display of pending merge information altogether, use
252
the no-pending option or specify a file/directory.
163
254
If a revision argument is given, the status is calculated against
164
255
that revision, or between two revisions if two are provided.
167
258
# TODO: --no-recurse, --recurse options
169
260
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.')]
261
takes_options = ['show-ids', 'revision', 'change', 'verbose',
262
Option('short', help='Use short status indicators.',
264
Option('versioned', help='Only show versioned files.',
266
Option('no-pending', help='Don\'t show pending merges.',
173
269
aliases = ['st', 'stat']
175
271
encoding_type = 'replace'
176
272
_see_also = ['diff', 'revert', 'status-flags']
179
275
def run(self, show_ids=False, file_list=None, revision=None, short=False,
276
versioned=False, no_pending=False, verbose=False):
181
277
from bzrlib.status import show_tree_status
183
279
if revision and len(revision) > 2:
184
280
raise errors.BzrCommandError('bzr status --revision takes exactly'
185
281
' one or two revision specifiers')
187
tree, file_list = tree_files(file_list)
283
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
284
# Avoid asking for specific files when that is not needed.
285
if relfile_list == ['']:
287
# Don't disable pending merges for full trees other than '.'.
288
if file_list == ['.']:
290
# A specific path within a tree was given.
291
elif relfile_list is not None:
189
293
show_tree_status(tree, show_ids=show_ids,
190
specific_files=file_list, revision=revision,
191
to_file=self.outf, short=short, versioned=versioned)
294
specific_files=relfile_list, revision=revision,
295
to_file=self.outf, short=short, versioned=versioned,
296
show_pending=(not no_pending), verbose=verbose)
194
299
class cmd_cat_revision(Command):
195
"""Write out metadata for a revision.
300
__doc__ = """Write out metadata for a revision.
197
302
The revision to print can either be specified by a specific
198
303
revision identifier, or you can use --revision.
202
307
takes_args = ['revision_id?']
203
takes_options = ['revision']
308
takes_options = ['directory', 'revision']
204
309
# cat-revision is more for frontends so should be exact
205
310
encoding = 'strict'
312
def print_revision(self, revisions, revid):
313
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
314
record = stream.next()
315
if record.storage_kind == 'absent':
316
raise errors.NoSuchRevision(revisions, revid)
317
revtext = record.get_bytes_as('fulltext')
318
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)
321
def run(self, revision_id=None, revision=None, directory=u'.'):
211
322
if revision_id is not None and revision is not None:
212
323
raise errors.BzrCommandError('You can only supply one of'
213
324
' revision_id or --revision')
214
325
if revision_id is None and revision is None:
215
326
raise errors.BzrCommandError('You must supply either'
216
327
' --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'))
328
b = WorkingTree.open_containing(directory)[0].branch
330
revisions = b.repository.revisions
331
if revisions is None:
332
raise errors.BzrCommandError('Repository %r does not support '
333
'access to raw revision texts')
335
b.repository.lock_read()
337
# TODO: jam 20060112 should cat-revision always output utf-8?
338
if revision_id is not None:
339
revision_id = osutils.safe_revision_id(revision_id, warn=False)
341
self.print_revision(revisions, revision_id)
342
except errors.NoSuchRevision:
343
msg = "The repository %s contains no revision %s." % (
344
b.repository.base, revision_id)
345
raise errors.BzrCommandError(msg)
346
elif revision is not None:
349
raise errors.BzrCommandError(
350
'You cannot specify a NULL revision.')
351
rev_id = rev.as_revision_id(b)
352
self.print_revision(revisions, rev_id)
354
b.repository.unlock()
357
class cmd_dump_btree(Command):
358
__doc__ = """Dump the contents of a btree index file to stdout.
360
PATH is a btree index file, it can be any URL. This includes things like
361
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
363
By default, the tuples stored in the index file will be displayed. With
364
--raw, we will uncompress the pages, but otherwise display the raw bytes
368
# TODO: Do we want to dump the internal nodes as well?
369
# TODO: It would be nice to be able to dump the un-parsed information,
370
# rather than only going through iter_all_entries. However, this is
371
# good enough for a start
373
encoding_type = 'exact'
374
takes_args = ['path']
375
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
376
' rather than the parsed tuples.'),
379
def run(self, path, raw=False):
380
dirname, basename = osutils.split(path)
381
t = transport.get_transport(dirname)
383
self._dump_raw_bytes(t, basename)
385
self._dump_entries(t, basename)
387
def _get_index_and_bytes(self, trans, basename):
388
"""Create a BTreeGraphIndex and raw bytes."""
389
bt = btree_index.BTreeGraphIndex(trans, basename, None)
390
bytes = trans.get_bytes(basename)
391
bt._file = cStringIO.StringIO(bytes)
392
bt._size = len(bytes)
395
def _dump_raw_bytes(self, trans, basename):
398
# We need to parse at least the root node.
399
# This is because the first page of every row starts with an
400
# uncompressed header.
401
bt, bytes = self._get_index_and_bytes(trans, basename)
402
for page_idx, page_start in enumerate(xrange(0, len(bytes),
403
btree_index._PAGE_SIZE)):
404
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
405
page_bytes = bytes[page_start:page_end]
407
self.outf.write('Root node:\n')
408
header_end, data = bt._parse_header_from_bytes(page_bytes)
409
self.outf.write(page_bytes[:header_end])
411
self.outf.write('\nPage %d\n' % (page_idx,))
412
decomp_bytes = zlib.decompress(page_bytes)
413
self.outf.write(decomp_bytes)
414
self.outf.write('\n')
416
def _dump_entries(self, trans, basename):
418
st = trans.stat(basename)
419
except errors.TransportNotPossible:
420
# We can't stat, so we'll fake it because we have to do the 'get()'
422
bt, _ = self._get_index_and_bytes(trans, basename)
424
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
425
for node in bt.iter_all_entries():
426
# Node is made up of:
427
# (index, key, value, [references])
431
refs_as_tuples = None
433
refs_as_tuples = static_tuple.as_tuples(refs)
434
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
435
self.outf.write('%s\n' % (as_tuple,))
231
438
class cmd_remove_tree(Command):
232
"""Remove the working tree from a given branch/checkout.
439
__doc__ = """Remove the working tree from a given branch/checkout.
234
441
Since a lightweight checkout is little more than a working tree
235
442
this will refuse to run against one.
237
444
To re-create the working tree, use "bzr checkout".
239
446
_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()
447
takes_args = ['location*']
450
help='Remove the working tree even if it has '
451
'uncommitted or shelved changes.'),
454
def run(self, location_list, force=False):
455
if not location_list:
458
for location in location_list:
459
d = bzrdir.BzrDir.open(location)
462
working = d.open_workingtree()
463
except errors.NoWorkingTree:
464
raise errors.BzrCommandError("No working tree to remove")
465
except errors.NotLocalUrl:
466
raise errors.BzrCommandError("You cannot remove the working tree"
469
if (working.has_changes()):
470
raise errors.UncommittedChanges(working)
471
if working.get_shelf_manager().last_shelf() is not None:
472
raise errors.ShelvedChanges(working)
474
if working.user_url != working.branch.user_url:
475
raise errors.BzrCommandError("You cannot remove the working tree"
476
" from a lightweight checkout")
478
d.destroy_workingtree()
263
481
class cmd_revno(Command):
264
"""Show current revision number.
482
__doc__ = """Show current revision number.
266
484
This is equal to the number of revisions on this branch.
269
487
_see_also = ['info']
270
488
takes_args = ['location?']
490
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')
494
def run(self, tree=False, location=u'.'):
497
wt = WorkingTree.open_containing(location)[0]
498
self.add_cleanup(wt.lock_read().unlock)
499
except (errors.NoWorkingTree, errors.NotLocalUrl):
500
raise errors.NoWorkingTree(location)
501
revid = wt.last_revision()
503
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
504
except errors.NoSuchRevision:
506
revno = ".".join(str(n) for n in revno_t)
508
b = Branch.open_containing(location)[0]
509
self.add_cleanup(b.lock_read().unlock)
512
self.outf.write(str(revno) + '\n')
278
515
class cmd_revision_info(Command):
279
"""Show revision number and revision id for a given revision identifier.
516
__doc__ = """Show revision number and revision id for a given revision identifier.
282
519
takes_args = ['revision_info*']
283
takes_options = ['revision']
522
custom_help('directory',
523
help='Branch to examine, '
524
'rather than the one containing the working directory.'),
525
Option('tree', help='Show revno of working tree'),
286
def run(self, revision=None, revision_info_list=[]):
529
def run(self, revision=None, directory=u'.', tree=False,
530
revision_info_list=[]):
533
wt = WorkingTree.open_containing(directory)[0]
535
self.add_cleanup(wt.lock_read().unlock)
536
except (errors.NoWorkingTree, errors.NotLocalUrl):
538
b = Branch.open_containing(directory)[0]
539
self.add_cleanup(b.lock_read().unlock)
289
541
if revision is not None:
290
revs.extend(revision)
542
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
291
543
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)
544
for rev_str in revision_info_list:
545
rev_spec = RevisionSpec.from_string(rev_str)
546
revision_ids.append(rev_spec.as_revision_id(b))
547
# No arguments supplied, default to the last revision
548
if len(revision_ids) == 0:
551
raise errors.NoWorkingTree(directory)
552
revision_ids.append(wt.last_revision())
307
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
554
revision_ids.append(b.last_revision())
558
for revision_id in revision_ids:
560
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
561
revno = '.'.join(str(i) for i in dotted_revno)
562
except errors.NoSuchRevision:
564
maxlen = max(maxlen, len(revno))
565
revinfos.append([revno, revision_id])
569
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
310
572
class cmd_add(Command):
311
"""Add specified files or directories.
573
__doc__ = """Add specified files or directories.
313
575
In non-recursive mode, all the named items are added, regardless
314
576
of whether they were previously ignored. A warning is given if
526
774
takes_args = ['names*']
527
775
takes_options = [Option("after", help="Move only the bzr identifier"
528
776
" of the file, because the file has already been moved."),
777
Option('auto', help='Automatically guess renames.'),
778
Option('dry-run', help='Avoid making changes when guessing renames.'),
530
780
aliases = ['move', 'rename']
531
781
encoding_type = 'replace'
533
def run(self, names_list, after=False):
783
def run(self, names_list, after=False, auto=False, dry_run=False):
785
return self.run_auto(names_list, after, dry_run)
787
raise errors.BzrCommandError('--dry-run requires --auto.')
534
788
if names_list is None:
537
790
if len(names_list) < 2:
538
791
raise errors.BzrCommandError("missing file argument")
539
tree, rel_names = tree_files(names_list)
541
if os.path.isdir(names_list[-1]):
792
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
793
self.add_cleanup(tree.lock_tree_write().unlock)
794
self._run(tree, names_list, rel_names, after)
796
def run_auto(self, names_list, after, dry_run):
797
if names_list is not None and len(names_list) > 1:
798
raise errors.BzrCommandError('Only one path may be specified to'
801
raise errors.BzrCommandError('--after cannot be specified with'
803
work_tree, file_list = WorkingTree.open_containing_paths(
804
names_list, default_directory='.')
805
self.add_cleanup(work_tree.lock_tree_write().unlock)
806
rename_map.RenameMap.guess_renames(work_tree, dry_run)
808
def _run(self, tree, names_list, rel_names, after):
809
into_existing = osutils.isdir(names_list[-1])
810
if into_existing and len(names_list) == 2:
812
# a. case-insensitive filesystem and change case of dir
813
# b. move directory after the fact (if the source used to be
814
# a directory, but now doesn't exist in the working tree
815
# and the target is an existing directory, just rename it)
816
if (not tree.case_sensitive
817
and rel_names[0].lower() == rel_names[1].lower()):
818
into_existing = False
821
# 'fix' the case of a potential 'from'
822
from_id = tree.path2id(
823
tree.get_canonical_inventory_path(rel_names[0]))
824
if (not osutils.lexists(names_list[0]) and
825
from_id and inv.get_file_kind(from_id) == "directory"):
826
into_existing = False
542
829
# 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)
830
# All entries reference existing inventory items, so fix them up
831
# for cicp file-systems.
832
rel_names = tree.get_canonical_inventory_paths(rel_names)
833
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
835
self.outf.write("%s => %s\n" % (src, dest))
546
837
if len(names_list) != 2:
547
838
raise errors.BzrCommandError('to mv multiple files the'
548
839
' 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]))
842
# for cicp file-systems: the src references an existing inventory
844
src = tree.get_canonical_inventory_path(rel_names[0])
845
# Find the canonical version of the destination: In all cases, the
846
# parent of the target must be in the inventory, so we fetch the
847
# canonical version from there (we do not always *use* the
848
# canonicalized tail portion - we may be attempting to rename the
850
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
851
dest_parent = osutils.dirname(canon_dest)
852
spec_tail = osutils.basename(rel_names[1])
853
# For a CICP file-system, we need to avoid creating 2 inventory
854
# entries that differ only by case. So regardless of the case
855
# we *want* to use (ie, specified by the user or the file-system),
856
# we must always choose to use the case of any existing inventory
857
# items. The only exception to this is when we are attempting a
858
# case-only rename (ie, canonical versions of src and dest are
860
dest_id = tree.path2id(canon_dest)
861
if dest_id is None or tree.path2id(src) == dest_id:
862
# No existing item we care about, so work out what case we
863
# are actually going to use.
865
# If 'after' is specified, the tail must refer to a file on disk.
867
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
869
# pathjoin with an empty tail adds a slash, which breaks
871
dest_parent_fq = tree.basedir
873
dest_tail = osutils.canonical_relpath(
875
osutils.pathjoin(dest_parent_fq, spec_tail))
877
# not 'after', so case as specified is used
878
dest_tail = spec_tail
880
# Use the existing item so 'mv' fails with AlreadyVersioned.
881
dest_tail = os.path.basename(canon_dest)
882
dest = osutils.pathjoin(dest_parent, dest_tail)
883
mutter("attempting to move %s => %s", src, dest)
884
tree.rename_one(src, dest, after=after)
886
self.outf.write("%s => %s\n" % (src, dest))
554
889
class cmd_pull(Command):
555
"""Turn this branch into a mirror of another branch.
890
__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.
892
By default, this command only works on branches that have not diverged.
893
Branches are considered diverged if the destination branch's most recent
894
commit is one that has not been merged (directly or indirectly) into the
561
897
If branches have diverged, you can use 'bzr merge' to integrate the changes
562
898
from one into the other. Once one branch has merged, the other should
563
899
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.
901
If you want to replace your local changes and just want your branch to
902
match the remote one, use pull --overwrite. This will work even if the two
903
branches have diverged.
568
905
If there is no default location set, the first pull will set it. After
569
906
that, you can omit the location to use the default. To change the
570
907
default, use --remember. The value will only be saved if the remote
571
908
location can be accessed.
910
Note: The location can be specified either in the form of a branch,
911
or in the form of a path to a file containing a merge directive generated
574
_see_also = ['push', 'update', 'status-flags']
915
_see_also = ['push', 'update', 'status-flags', 'send']
575
916
takes_options = ['remember', 'overwrite', 'revision',
576
Option('verbose', short_name='v',
917
custom_help('verbose',
577
918
help='Show logs of pulled revisions.'),
919
custom_help('directory',
579
920
help='Branch to pull into, '
580
'rather than the one containing the working directory.',
921
'rather than the one containing the working directory.'),
923
help="Perform a local pull in a bound "
924
"branch. Local pulls are not applied to "
585
928
takes_args = ['location?']
680
1036
_see_also = ['pull', 'update', 'working-trees']
681
takes_options = ['remember', 'overwrite', 'verbose',
1037
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
682
1038
Option('create-prefix',
683
1039
help='Create the path leading up to the branch '
684
1040
'if it does not already exist.'),
1041
custom_help('directory',
686
1042
help='Branch to push from, '
687
'rather than the one containing the working directory.',
1043
'rather than the one containing the working directory.'),
691
1044
Option('use-existing-dir',
692
1045
help='By default push will fail if the target'
693
1046
' directory exists, but does not already'
694
1047
' have a control directory. This flag will'
695
1048
' allow push to proceed.'),
1050
help='Create a stacked branch that references the public location '
1051
'of the parent branch.'),
1052
Option('stacked-on',
1053
help='Create a stacked branch that refers to another branch '
1054
'for the commit history. Only the work not present in the '
1055
'referenced branch is included in the branch created.',
1058
help='Refuse to push if there are uncommitted changes in'
1059
' the working tree, --no-strict disables the check.'),
697
1061
takes_args = ['location?']
698
1062
encoding_type = 'replace'
700
1064
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
1065
create_prefix=False, verbose=False, revision=None,
1066
use_existing_dir=False, directory=None, stacked_on=None,
1067
stacked=False, strict=None):
1068
from bzrlib.push import _show_push_branch
706
1070
if directory is None:
708
br_from = Branch.open_containing(directory)[0]
709
stored_loc = br_from.get_push_location()
1072
# Get the source branch
1074
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1075
# Get the tip's revision_id
1076
revision = _get_one_revision('push', revision)
1077
if revision is not None:
1078
revision_id = revision.in_history(br_from).rev_id
1081
if tree is not None and revision_id is None:
1082
tree.check_changed_or_out_of_date(
1083
strict, 'push_strict',
1084
more_error='Use --no-strict to force the push.',
1085
more_warning='Uncommitted changes will not be pushed.')
1086
# Get the stacked_on branch, if any
1087
if stacked_on is not None:
1088
stacked_on = urlutils.normalize_url(stacked_on)
1090
parent_url = br_from.get_parent()
1092
parent = Branch.open(parent_url)
1093
stacked_on = parent.get_public_branch()
1095
# I considered excluding non-http url's here, thus forcing
1096
# 'public' branches only, but that only works for some
1097
# users, so it's best to just depend on the user spotting an
1098
# error by the feedback given to them. RBC 20080227.
1099
stacked_on = parent_url
1101
raise errors.BzrCommandError(
1102
"Could not determine branch to refer to.")
1104
# Get the destination location
710
1105
if location is None:
1106
stored_loc = br_from.get_push_location()
711
1107
if stored_loc is None:
712
raise errors.BzrCommandError("No push location known or specified.")
1108
raise errors.BzrCommandError(
1109
"No push location known or specified.")
714
1111
display_url = urlutils.unescape_for_display(stored_loc,
715
1112
self.outf.encoding)
716
self.outf.write("Using saved location: %s\n" % display_url)
1113
self.outf.write("Using saved push location: %s\n" % display_url)
717
1114
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
1116
_show_push_branch(br_from, revision_id, location, self.outf,
1117
verbose=verbose, overwrite=overwrite, remember=remember,
1118
stacked_on=stacked_on, create_prefix=create_prefix,
1119
use_existing_dir=use_existing_dir)
835
1122
class cmd_branch(Command):
836
"""Create a new copy of a branch.
1123
__doc__ = """Create a new branch that is a copy of an existing branch.
838
1125
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
839
1126
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
849
1136
_see_also = ['checkout']
850
1137
takes_args = ['from_location', 'to_location?']
851
takes_options = ['revision']
1138
takes_options = ['revision',
1139
Option('hardlink', help='Hard-link working tree files where possible.'),
1140
Option('files-from', type=str,
1141
help="Get file contents from this tree."),
1143
help="Create a branch without a working-tree."),
1145
help="Switch the checkout in the current directory "
1146
"to the new branch."),
1148
help='Create a stacked branch referring to the source branch. '
1149
'The new branch will depend on the availability of the source '
1150
'branch for all operations.'),
1151
Option('standalone',
1152
help='Do not use a shared repository, even if available.'),
1153
Option('use-existing-dir',
1154
help='By default branch will fail if the target'
1155
' directory exists, but does not already'
1156
' have a control directory. This flag will'
1157
' allow branch to proceed.'),
1159
help="Bind new branch to from location."),
852
1161
aliases = ['get', 'clone']
854
def run(self, from_location, to_location=None, revision=None):
1163
def run(self, from_location, to_location=None, revision=None,
1164
hardlink=False, stacked=False, standalone=False, no_tree=False,
1165
use_existing_dir=False, switch=False, bind=False,
1167
from bzrlib import switch as _mod_switch
855
1168
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)
1169
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1171
if not (hardlink or files_from):
1172
# accelerator_tree is usually slower because you have to read N
1173
# files (no readahead, lots of seeks, etc), but allow the user to
1174
# explicitly request it
1175
accelerator_tree = None
1176
if files_from is not None and files_from != from_location:
1177
accelerator_tree = WorkingTree.open(files_from)
1178
revision = _get_one_revision('branch', revision)
1179
self.add_cleanup(br_from.lock_read().unlock)
1180
if revision is not None:
1181
revision_id = revision.as_revision_id(br_from)
1183
# FIXME - wt.last_revision, fallback to branch, fall back to
1184
# None or perhaps NULL_REVISION to mean copy nothing
1186
revision_id = br_from.last_revision()
1187
if to_location is None:
1188
to_location = urlutils.derive_to_location(from_location)
1189
to_transport = transport.get_transport(to_location)
1191
to_transport.mkdir('.')
1192
except errors.FileExists:
1193
if not use_existing_dir:
1194
raise errors.BzrCommandError('Target directory "%s" '
1195
'already exists.' % to_location)
1198
bzrdir.BzrDir.open_from_transport(to_transport)
1199
except errors.NotBranchError:
1202
raise errors.AlreadyBranchError(to_location)
1203
except errors.NoSuchFile:
1204
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1207
# preserve whatever source format we have.
1208
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1209
possible_transports=[to_transport],
1210
accelerator_tree=accelerator_tree,
1211
hardlink=hardlink, stacked=stacked,
1212
force_new_repo=standalone,
1213
create_tree_if_local=not no_tree,
1214
source_branch=br_from)
1215
branch = dir.open_branch()
1216
except errors.NoSuchRevision:
1217
to_transport.delete_tree('.')
1218
msg = "The branch %s has no revision %s." % (from_location,
1220
raise errors.BzrCommandError(msg)
1221
_merge_tags_if_possible(br_from, branch)
1222
# If the source branch is stacked, the new branch may
1223
# be stacked whether we asked for that explicitly or not.
1224
# We therefore need a try/except here and not just 'if stacked:'
1226
note('Created new stacked branch referring to %s.' %
1227
branch.get_stacked_on_url())
1228
except (errors.NotStacked, errors.UnstackableBranchFormat,
1229
errors.UnstackableRepositoryFormat), e:
899
1230
note('Branched %d revision(s).' % branch.revno())
1232
# Bind to the parent
1233
parent_branch = Branch.open(from_location)
1234
branch.bind(parent_branch)
1235
note('New branch bound to %s' % from_location)
1237
# Switch to the new branch
1238
wt, _ = WorkingTree.open_containing('.')
1239
_mod_switch.switch(wt.bzrdir, branch)
1240
note('Switched to branch: %s',
1241
urlutils.unescape_for_display(branch.base, 'utf-8'))
904
1244
class cmd_checkout(Command):
905
"""Create a new checkout of an existing branch.
1245
__doc__ = """Create a new checkout of an existing branch.
907
1247
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
908
1248
the branch found in '.'. This is useful if you have removed the working tree
909
1249
or if it was never created - i.e. if you pushed the branch to its current
910
1250
location using SFTP.
912
1252
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
913
1253
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
914
1254
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
978
1327
@display_command
979
1328
def run(self, dir=u'.'):
980
1329
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))
1330
self.add_cleanup(tree.lock_read().unlock)
1331
new_inv = tree.inventory
1332
old_tree = tree.basis_tree()
1333
self.add_cleanup(old_tree.lock_read().unlock)
1334
old_inv = old_tree.inventory
1336
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1337
for f, paths, c, v, p, n, k, e in iterator:
1338
if paths[0] == paths[1]:
1342
renames.append(paths)
1344
for old_name, new_name in renames:
1345
self.outf.write("%s => %s\n" % (old_name, new_name))
998
1348
class cmd_update(Command):
999
"""Update a tree to have the latest code committed to its branch.
1349
__doc__ = """Update a tree to have the latest code committed to its branch.
1001
1351
This will perform a merge into the working tree, and may generate
1002
conflicts. If you have any local changes, you will still
1352
conflicts. If you have any local changes, you will still
1003
1353
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
1355
If you want to discard your local changes, you can just do a
1006
1356
'bzr revert' instead of 'bzr commit' after the update.
1358
If the tree's branch is bound to a master branch, it will also update
1359
the branch from the master.
1009
1362
_see_also = ['pull', 'working-trees', 'status-flags']
1010
1363
takes_args = ['dir?']
1364
takes_options = ['revision']
1011
1365
aliases = ['up']
1013
def run(self, dir='.'):
1367
def run(self, dir='.', revision=None):
1368
if revision is not None and len(revision) != 1:
1369
raise errors.BzrCommandError(
1370
"bzr update --revision takes exactly one revision")
1014
1371
tree = WorkingTree.open_containing(dir)[0]
1015
master = tree.branch.get_master_branch()
1372
branch = tree.branch
1373
possible_transports = []
1374
master = branch.get_master_branch(
1375
possible_transports=possible_transports)
1016
1376
if master is not None:
1377
branch_location = master.base
1017
1378
tree.lock_write()
1380
branch_location = tree.branch.base
1019
1381
tree.lock_tree_write()
1382
self.add_cleanup(tree.unlock)
1383
# get rid of the final '/' and be ready for display
1384
branch_location = urlutils.unescape_for_display(
1385
branch_location.rstrip('/'),
1387
existing_pending_merges = tree.get_parent_ids()[1:]
1391
# may need to fetch data into a heavyweight checkout
1392
# XXX: this may take some time, maybe we should display a
1394
old_tip = branch.update(possible_transports)
1395
if revision is not None:
1396
revision_id = revision[0].as_revision_id(branch)
1398
revision_id = branch.last_revision()
1399
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1400
revno = branch.revision_id_to_dotted_revno(revision_id)
1401
note("Tree is up to date at revision %s of branch %s" %
1402
('.'.join(map(str, revno)), branch_location))
1404
view_info = _get_view_info_for_change_reporter(tree)
1405
change_reporter = delta._ChangeReporter(
1406
unversioned_filter=tree.is_ignored,
1407
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'.")
1409
conflicts = tree.update(
1411
possible_transports=possible_transports,
1412
revision=revision_id,
1414
except errors.NoSuchRevision, e:
1415
raise errors.BzrCommandError(
1416
"branch has no revision %s\n"
1417
"bzr update --revision only works"
1418
" for a revision in the branch history"
1420
revno = tree.branch.revision_id_to_dotted_revno(
1421
_mod_revision.ensure_null(tree.last_revision()))
1422
note('Updated to revision %s of branch %s' %
1423
('.'.join(map(str, revno)), branch_location))
1424
parent_ids = tree.get_parent_ids()
1425
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1426
note('Your local commits will now show as pending merges with '
1427
"'bzr status', and can be committed with 'bzr commit'.")
1047
1434
class cmd_info(Command):
1048
"""Show information about a working tree, branch or repository.
1435
__doc__ = """Show information about a working tree, branch or repository.
1050
1437
This command will show all known locations and formats associated to the
1051
tree, branch or repository. Statistical information is included with
1438
tree, branch or repository.
1440
In verbose mode, statistical information is included with each report.
1441
To see extended statistic information, use a verbosity level of 2 or
1442
higher by specifying the verbose option multiple times, e.g. -vv.
1054
1444
Branches and working trees will also report any missing revisions.
1448
Display information on the format and related locations:
1452
Display the above together with extended format information and
1453
basic statistics (like the number of files in the working tree and
1454
number of revisions in the branch and repository):
1458
Display the above together with number of committers to the branch:
1056
1462
_see_also = ['revno', 'working-trees', 'repositories']
1057
1463
takes_args = ['location?']
1058
1464
takes_options = ['verbose']
1465
encoding_type = 'replace'
1060
1467
@display_command
1061
def run(self, location=None, verbose=0):
1468
def run(self, location=None, verbose=False):
1470
noise_level = get_verbosity_level()
1062
1473
from bzrlib.info import show_bzrdir_info
1063
1474
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1475
verbose=noise_level, outfile=self.outf)
1067
1478
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.
1479
__doc__ = """Remove files or directories.
1481
This makes bzr stop tracking changes to the specified files. bzr will delete
1482
them if they can easily be recovered using revert. If no options or
1483
parameters are given bzr will scan for files that are being tracked by bzr
1484
but missing in your tree and stop tracking them for you.
1078
1486
takes_args = ['file*']
1079
1487
takes_options = ['verbose',
1080
Option('new', help='Remove newly-added files.'),
1488
Option('new', help='Only remove files that have never been committed.'),
1081
1489
RegistryOption.from_kwargs('file-deletion-strategy',
1082
1490
'The file deletion mode to be used.',
1083
1491
title='Deletion Strategy', value_switches=True, enum_switch=False,
1084
1492
safe='Only delete files if they can be'
1085
1493
' safely recovered (default).',
1086
keep="Don't delete any files.",
1494
keep='Delete from bzr but leave the working copy.',
1087
1495
force='Delete all the specified files, even if they can not be '
1088
1496
'recovered and even if they are non-empty directories.')]
1497
aliases = ['rm', 'del']
1090
1498
encoding_type = 'replace'
1092
1500
def run(self, file_list, verbose=False, new=False,
1093
1501
file_deletion_strategy='safe'):
1094
tree, file_list = tree_files(file_list)
1502
tree, file_list = WorkingTree.open_containing_paths(file_list)
1096
1504
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.')
1505
file_list = [f for f in file_list]
1507
self.add_cleanup(tree.lock_write().unlock)
1508
# Heuristics should probably all move into tree.remove_smart or
1103
1511
added = tree.changes_from(tree.basis_tree(),
1104
1512
specific_files=file_list).added
1105
1513
file_list = sorted([f[0] for f in added], reverse=True)
1106
1514
if len(file_list) == 0:
1107
1515
raise errors.BzrCommandError('No matching files.')
1516
elif file_list is None:
1517
# missing files show up in iter_changes(basis) as
1518
# versioned-with-no-kind.
1520
for change in tree.iter_changes(tree.basis_tree()):
1521
# Find paths in the working tree that have no kind:
1522
if change[1][1] is not None and change[6][1] is None:
1523
missing.append(change[1][1])
1524
file_list = sorted(missing, reverse=True)
1525
file_deletion_strategy = 'keep'
1108
1526
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1109
1527
keep_files=file_deletion_strategy=='keep',
1110
1528
force=file_deletion_strategy=='force')
1113
1531
class cmd_file_id(Command):
1114
"""Print file_id of a particular file or directory.
1532
__doc__ = """Print file_id of a particular file or directory.
1116
1534
The file_id is assigned when the file is first added and remains the
1117
1535
same through all revisions where the file exists, even when it is
1594
2057
raise errors.BzrCommandError(msg)
2060
def _parse_levels(s):
2064
msg = "The levels argument must be an integer."
2065
raise errors.BzrCommandError(msg)
1597
2068
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
2069
__doc__ = """Show historical log for a branch or subset of a branch.
2071
log is bzr's default tool for exploring the history of a branch.
2072
The branch to use is taken from the first parameter. If no parameters
2073
are given, the branch containing the working directory is logged.
2074
Here are some simple examples::
2076
bzr log log the current branch
2077
bzr log foo.py log a file in its branch
2078
bzr log http://server/branch log a branch on a server
2080
The filtering, ordering and information shown for each revision can
2081
be controlled as explained below. By default, all revisions are
2082
shown sorted (topologically) so that newer revisions appear before
2083
older ones and descendants always appear before ancestors. If displayed,
2084
merged revisions are shown indented under the revision in which they
2089
The log format controls how information about each revision is
2090
displayed. The standard log formats are called ``long``, ``short``
2091
and ``line``. The default is long. See ``bzr help log-formats``
2092
for more details on log formats.
2094
The following options can be used to control what information is
2097
-l N display a maximum of N revisions
2098
-n N display N levels of revisions (0 for all, 1 for collapsed)
2099
-v display a status summary (delta) for each revision
2100
-p display a diff (patch) for each revision
2101
--show-ids display revision-ids (and file-ids), not just revnos
2103
Note that the default number of levels to display is a function of the
2104
log format. If the -n option is not used, the standard log formats show
2105
just the top level (mainline).
2107
Status summaries are shown using status flags like A, M, etc. To see
2108
the changes explained using words like ``added`` and ``modified``
2109
instead, use the -vv option.
2113
To display revisions from oldest to newest, use the --forward option.
2114
In most cases, using this option will have little impact on the total
2115
time taken to produce a log, though --forward does not incrementally
2116
display revisions like --reverse does when it can.
2118
:Revision filtering:
2120
The -r option can be used to specify what revision or range of revisions
2121
to filter against. The various forms are shown below::
2123
-rX display revision X
2124
-rX.. display revision X and later
2125
-r..Y display up to and including revision Y
2126
-rX..Y display from X to Y inclusive
2128
See ``bzr help revisionspec`` for details on how to specify X and Y.
2129
Some common examples are given below::
2131
-r-1 show just the tip
2132
-r-10.. show the last 10 mainline revisions
2133
-rsubmit:.. show what's new on this branch
2134
-rancestor:path.. show changes since the common ancestor of this
2135
branch and the one at location path
2136
-rdate:yesterday.. show changes since yesterday
2138
When logging a range of revisions using -rX..Y, log starts at
2139
revision Y and searches back in history through the primary
2140
("left-hand") parents until it finds X. When logging just the
2141
top level (using -n1), an error is reported if X is not found
2142
along the way. If multi-level logging is used (-n0), X may be
2143
a nested merge revision and the log will be truncated accordingly.
2147
If parameters are given and the first one is not a branch, the log
2148
will be filtered to show only those revisions that changed the
2149
nominated files or directories.
2151
Filenames are interpreted within their historical context. To log a
2152
deleted file, specify a revision range so that the file existed at
2153
the end or start of the range.
2155
Historical context is also important when interpreting pathnames of
2156
renamed files/directories. Consider the following example:
2158
* revision 1: add tutorial.txt
2159
* revision 2: modify tutorial.txt
2160
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2164
* ``bzr log guide.txt`` will log the file added in revision 1
2166
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2168
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2169
the original file in revision 2.
2171
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2172
was no file called guide.txt in revision 2.
2174
Renames are always followed by log. By design, there is no need to
2175
explicitly ask for this (and no way to stop logging a file back
2176
until it was last renamed).
2180
The --message option can be used for finding revisions that match a
2181
regular expression in a commit message.
2185
GUI tools and IDEs are often better at exploring history than command
2186
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2187
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2188
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2189
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2191
You may find it useful to add the aliases below to ``bazaar.conf``::
2195
top = log -l10 --line
2198
``bzr tip`` will then show the latest revision while ``bzr top``
2199
will show the last 10 mainline revisions. To see the details of a
2200
particular revision X, ``bzr show -rX``.
2202
If you are interested in looking deeper into a particular merge X,
2203
use ``bzr log -n0 -rX``.
2205
``bzr log -v`` on a branch with lots of history is currently
2206
very slow. A fix for this issue is currently under development.
2207
With or without that fix, it is recommended that a revision range
2208
be given when using the -v option.
2210
bzr has a generic full-text matching plugin, bzr-search, that can be
2211
used to find revisions matching user names, commit messages, etc.
2212
Among other features, this plugin can find all revisions containing
2213
a list of words but not others.
2215
When exploring non-mainline history on large projects with deep
2216
history, the performance of log can be greatly improved by installing
2217
the historycache plugin. This plugin buffers historical information
2218
trading disk space for faster speed.
1620
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1622
takes_args = ['location?']
2220
takes_args = ['file*']
2221
_see_also = ['log-formats', 'revisionspec']
1623
2222
takes_options = [
1624
2223
Option('forward',
1625
2224
help='Show from oldest to newest.'),
1628
help='Display timezone as local, original, or utc.'),
2226
custom_help('verbose',
1631
2227
help='Show files changed in each revision.'),
2231
type=bzrlib.option._parse_revision_str,
2233
help='Show just the specified revision.'
2234
' See also "help revisionspec".'),
2236
RegistryOption('authors',
2237
'What names to list as authors - first, all or committer.',
2239
lazy_registry=('bzrlib.log', 'author_list_registry'),
2243
help='Number of levels to display - 0 for all, 1 for flat.',
2245
type=_parse_levels),
1635
2246
Option('message',
1636
2247
short_name='m',
1637
2248
help='Show revisions whose message matches this '
1638
2249
'regular expression.',
1640
2251
Option('limit',
1641
2253
help='Limit the output to the first N revisions.',
1643
2255
type=_parse_limit),
2258
help='Show changes made in each revision as a patch.'),
2259
Option('include-merges',
2260
help='Show merged revisions like --levels 0 does.'),
2261
Option('exclude-common-ancestry',
2262
help='Display only the revisions that are not part'
2263
' of both ancestries (require -rX..Y)'
1645
2266
encoding_type = 'replace'
1647
2268
@display_command
1648
def run(self, location=None, timezone='original',
2269
def run(self, file_list=None, timezone='original',
1650
2271
show_ids=False,
1653
2275
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
2280
include_merges=False,
2282
exclude_common_ancestry=False,
2284
from bzrlib.log import (
2286
make_log_request_dict,
2287
_get_info_for_log_files,
1659
2289
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)
2290
if (exclude_common_ancestry
2291
and (revision is None or len(revision) != 2)):
2292
raise errors.BzrCommandError(
2293
'--exclude-common-ancestry requires -r with two revisions')
2298
raise errors.BzrCommandError(
2299
'--levels and --include-merges are mutually exclusive')
2301
if change is not None:
2303
raise errors.RangeInChangeOption()
2304
if revision is not None:
2305
raise errors.BzrCommandError(
2306
'--revision and --change are mutually exclusive')
2311
filter_by_dir = False
2313
# find the file ids to log and check for directory filtering
2314
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2315
revision, file_list, self.add_cleanup)
2316
for relpath, file_id, kind in file_info_list:
1672
2317
if file_id is None:
1673
2318
raise errors.BzrCommandError(
1674
"Path does not have any revision history: %s" %
2319
"Path unknown at end or start of revision range: %s" %
2321
# If the relpath is the top of the tree, we log everything
2326
file_ids.append(file_id)
2327
filter_by_dir = filter_by_dir or (
2328
kind in ['directory', 'tree-reference'])
1678
# FIXME ? log the current subdir only RBC 20060203
2331
# FIXME ? log the current subdir only RBC 20060203
1679
2332
if revision is not None \
1680
2333
and len(revision) > 0 and revision[0].get_branch():
1681
2334
location = revision[0].get_branch()
1796
2517
if path is None:
1801
2521
raise errors.BzrCommandError('cannot specify both --from-root'
1805
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2524
tree, branch, relpath = \
2525
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2527
# 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')
2531
prefix = relpath + '/'
2532
elif fs_path != '.' and not fs_path.endswith('/'):
2533
prefix = fs_path + '/'
2535
if revision is not None or tree is None:
2536
tree = _get_one_revision_tree('ls', revision, branch=branch)
2539
if isinstance(tree, WorkingTree) and tree.supports_views():
2540
view_files = tree.views.lookup_view()
2543
view_str = views.view_display_str(view_files)
2544
note("Ignoring files outside view. View is %s" % view_str)
2546
self.add_cleanup(tree.lock_read().unlock)
2547
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2548
from_dir=relpath, recursive=recursive):
2549
# Apply additional masking
2550
if not all and not selection[fc]:
2552
if kind is not None and fkind != kind:
2557
fullpath = osutils.pathjoin(relpath, fp)
2560
views.check_path_in_view(tree, fullpath)
2561
except errors.FileOutsideView:
2566
fp = osutils.pathjoin(prefix, fp)
2567
kindch = entry.kind_character()
2568
outstring = fp + kindch
2569
ui.ui_factory.clear_term()
2571
outstring = '%-8s %s' % (fc, outstring)
2572
if show_ids and fid is not None:
2573
outstring = "%-50s %s" % (outstring, fid)
2574
self.outf.write(outstring + '\n')
2576
self.outf.write(fp + '\0')
2579
self.outf.write(fid)
2580
self.outf.write('\0')
2588
self.outf.write('%-50s %s\n' % (outstring, my_id))
2590
self.outf.write(outstring + '\n')
1854
2593
class cmd_unknowns(Command):
1855
"""List unknown files.
2594
__doc__ = """List unknown files.
1859
2598
_see_also = ['ls']
2599
takes_options = ['directory']
1861
2601
@display_command
1863
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2602
def run(self, directory=u'.'):
2603
for f in WorkingTree.open_containing(directory)[0].unknowns():
1864
2604
self.outf.write(osutils.quotefn(f) + '\n')
1867
2607
class cmd_ignore(Command):
1868
"""Ignore specified files or patterns.
2608
__doc__ = """Ignore specified files or patterns.
2610
See ``bzr help patterns`` for details on the syntax of patterns.
2612
If a .bzrignore file does not exist, the ignore command
2613
will create one and add the specified files or patterns to the newly
2614
created file. The ignore command will also automatically add the
2615
.bzrignore file to be versioned. Creating a .bzrignore file without
2616
the use of the ignore command will require an explicit add command.
1870
2618
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
2619
After adding, editing or deleting that file either indirectly by
2620
using this command or directly by using an editor, be sure to commit
2623
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2624
the global ignore file can be found in the application data directory as
2625
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2626
Global ignores are not touched by this command. The global ignore file
2627
can be edited directly using an editor.
2629
Patterns prefixed with '!' are exceptions to ignore patterns and take
2630
precedence over regular ignores. Such exceptions are used to specify
2631
files that should be versioned which would otherwise be ignored.
2633
Patterns prefixed with '!!' act as regular ignore patterns, but have
2634
precedence over the '!' exception patterns.
2636
Note: ignore patterns containing shell wildcards must be quoted from
1893
2637
the shell on Unix.
1898
2642
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'
2644
Ignore .class files in all directories...::
2646
bzr ignore "*.class"
2648
...but do not ignore "special.class"::
2650
bzr ignore "!special.class"
2652
Ignore .o files under the lib directory::
2654
bzr ignore "lib/**/*.o"
2656
Ignore .o files under the lib directory::
2658
bzr ignore "RE:lib/.*\.o"
2660
Ignore everything but the "debian" toplevel directory::
2662
bzr ignore "RE:(?!debian/).*"
2664
Ignore everything except the "local" toplevel directory,
2665
but always ignore "*~" autosave files, even under local/::
2668
bzr ignore "!./local"
1913
_see_also = ['status', 'ignored']
2672
_see_also = ['status', 'ignored', 'patterns']
1914
2673
takes_args = ['name_pattern*']
1916
Option('old-default-rules',
1917
help='Write out the ignore rules bzr < 0.9 always used.')
2674
takes_options = ['directory',
2675
Option('default-rules',
2676
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:
2679
def run(self, name_pattern_list=None, default_rules=None,
2681
from bzrlib import ignores
2682
if default_rules is not None:
2683
# dump the default rules and exit
2684
for pattern in ignores.USER_DEFAULTS:
2685
self.outf.write("%s\n" % pattern)
1927
2687
if not name_pattern_list:
1928
2688
raise errors.BzrCommandError("ignore requires at least one "
1929
"NAME_PATTERN or --old-default-rules")
1930
name_pattern_list = [globbing.normalize_pattern(p)
2689
"NAME_PATTERN or --default-rules.")
2690
name_pattern_list = [globbing.normalize_pattern(p)
1931
2691
for p in name_pattern_list]
1932
2692
for name_pattern in name_pattern_list:
1933
if (name_pattern[0] == '/' or
2693
if (name_pattern[0] == '/' or
1934
2694
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1935
2695
raise errors.BzrCommandError(
1936
2696
"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'])
2697
tree, relpath = WorkingTree.open_containing(directory)
2698
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2699
ignored = globbing.Globster(name_pattern_list)
2701
self.add_cleanup(tree.lock_read().unlock)
2702
for entry in tree.list_files():
2706
if ignored.match(filename):
2707
matches.append(filename)
2708
if len(matches) > 0:
2709
self.outf.write("Warning: the following files are version controlled and"
2710
" match your ignore pattern:\n%s"
2711
"\nThese files will continue to be version controlled"
2712
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1967
2715
class cmd_ignored(Command):
1968
"""List ignored files and the patterns that matched them.
2716
__doc__ = """List ignored files and the patterns that matched them.
2718
List all the ignored files and the ignore pattern that caused the file to
2721
Alternatively, to list just the files::
1971
_see_also = ['ignore']
2726
encoding_type = 'replace'
2727
_see_also = ['ignore', 'ls']
2728
takes_options = ['directory']
1972
2730
@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)
2731
def run(self, directory=u'.'):
2732
tree = WorkingTree.open_containing(directory)[0]
2733
self.add_cleanup(tree.lock_read().unlock)
2734
for path, file_class, kind, file_id, entry in tree.list_files():
2735
if file_class != 'I':
2737
## XXX: Slightly inefficient since this was already calculated
2738
pat = tree.is_ignored(path)
2739
self.outf.write('%-50s %s\n' % (path, pat))
1987
2742
class cmd_lookup_revision(Command):
1988
"""Lookup the revision-id from a revision-number
2743
__doc__ = """Lookup the revision-id from a revision-number
1991
2746
bzr lookup-revision 33
1994
2749
takes_args = ['revno']
2750
takes_options = ['directory']
1996
2752
@display_command
1997
def run(self, revno):
2753
def run(self, revno, directory=u'.'):
1999
2755
revno = int(revno)
2000
2756
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)
2757
raise errors.BzrCommandError("not a valid revision-number: %r"
2759
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2760
self.outf.write("%s\n" % revid)
2006
2763
class cmd_export(Command):
2007
"""Export current or past revision to a destination directory or archive.
2764
__doc__ = """Export current or past revision to a destination directory or archive.
2009
2766
If no revision is specified this exports the last committed revision.
2032
2789
================= =========================
2034
takes_args = ['dest', 'branch?']
2791
takes_args = ['dest', 'branch_or_subdir?']
2792
takes_options = ['directory',
2036
2793
Option('format',
2037
2794
help="Type of file to export to.",
2797
Option('filters', help='Apply content filters to export the '
2798
'convenient form.'),
2042
2801
help="Name of the root directory inside the exported file."),
2802
Option('per-file-timestamps',
2803
help='Set modification time of files to that of the last '
2804
'revision in which it was changed.'),
2044
def run(self, dest, branch=None, revision=None, format=None, root=None):
2806
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2807
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2045
2808
from bzrlib.export import export
2048
tree = WorkingTree.open_containing(u'.')[0]
2810
if branch_or_subdir is None:
2811
tree = WorkingTree.open_containing(directory)[0]
2049
2812
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)
2815
b, subdir = Branch.open_containing(branch_or_subdir)
2818
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2062
export(t, dest, format, root)
2820
export(rev_tree, dest, format, root, subdir, filtered=filters,
2821
per_file_timestamps=per_file_timestamps)
2063
2822
except errors.NoSuchExportFormat, e:
2064
2823
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2067
2826
class cmd_cat(Command):
2068
"""Write the contents of a file as of a given revision to standard output.
2827
__doc__ = """Write the contents of a file as of a given revision to standard output.
2070
2829
If no revision is nominated, the last revision is used.
2072
2831
Note: Take care to redirect standard output when using this command on a
2076
2835
_see_also = ['ls']
2836
takes_options = ['directory',
2078
2837
Option('name-from-revision', help='The path name in the old tree.'),
2838
Option('filters', help='Apply content filters to display the '
2839
'convenience form.'),
2081
2842
takes_args = ['filename']
2082
2843
encoding_type = 'exact'
2084
2845
@display_command
2085
def run(self, filename, revision=None, name_from_revision=False):
2846
def run(self, filename, revision=None, name_from_revision=False,
2847
filters=False, directory=None):
2086
2848
if revision is not None and len(revision) != 1:
2087
2849
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())
2850
" one revision specifier")
2851
tree, branch, relpath = \
2852
_open_directory_or_containing_tree_or_branch(filename, directory)
2853
self.add_cleanup(branch.lock_read().unlock)
2854
return self._run(tree, branch, relpath, filename, revision,
2855
name_from_revision, filters)
2857
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2099
2859
if tree is None:
2100
2860
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
2861
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2862
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
2864
old_file_id = rev_tree.path2id(relpath)
2110
2866
if name_from_revision:
2867
# Try in revision if requested
2111
2868
if old_file_id is None:
2112
raise errors.BzrCommandError("%r is not present in revision %s"
2113
% (filename, revision_id))
2869
raise errors.BzrCommandError(
2870
"%r is not present in revision %s" % (
2871
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))
2873
content = rev_tree.get_file_text(old_file_id)
2875
cur_file_id = tree.path2id(relpath)
2877
if cur_file_id is not None:
2878
# Then try with the actual file id
2880
content = rev_tree.get_file_text(cur_file_id)
2882
except errors.NoSuchId:
2883
# The actual file id didn't exist at that time
2885
if not found and old_file_id is not None:
2886
# Finally try with the old file id
2887
content = rev_tree.get_file_text(old_file_id)
2890
# Can't be found anywhere
2891
raise errors.BzrCommandError(
2892
"%r is not present in revision %s" % (
2893
filename, rev_tree.get_revision_id()))
2895
from bzrlib.filters import (
2896
ContentFilterContext,
2897
filtered_output_bytes,
2899
filters = rev_tree._content_filter_stack(relpath)
2900
chunks = content.splitlines(True)
2901
content = filtered_output_bytes(chunks, filters,
2902
ContentFilterContext(relpath, rev_tree))
2904
self.outf.writelines(content)
2907
self.outf.write(content)
2125
2910
class cmd_local_time_offset(Command):
2126
"""Show the offset in seconds from GMT to local time."""
2911
__doc__ = """Show the offset in seconds from GMT to local time."""
2128
2913
@display_command
2130
print osutils.local_time_offset()
2915
self.outf.write("%s\n" % osutils.local_time_offset())
2134
2919
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.
2920
__doc__ = """Commit changes into a new revision.
2922
An explanatory message needs to be given for each commit. This is
2923
often done by using the --message option (getting the message from the
2924
command line) or by using the --file option (getting the message from
2925
a file). If neither of these options is given, an editor is opened for
2926
the user to enter the message. To see the changed files in the
2927
boilerplate text loaded into the editor, use the --show-diff option.
2929
By default, the entire tree is committed and the person doing the
2930
commit is assumed to be the author. These defaults can be overridden
2935
If selected files are specified, only changes to those files are
2936
committed. If a directory is specified then the directory and
2937
everything within it is committed.
2939
When excludes are given, they take precedence over selected files.
2940
For example, to commit only changes within foo, but not changes
2943
bzr commit foo -x foo/bar
2945
A selective commit after a merge is not yet supported.
2949
If the author of the change is not the same person as the committer,
2950
you can specify the author's name using the --author option. The
2951
name should be in the same format as a committer-id, e.g.
2952
"John Doe <jdoe@example.com>". If there is more than one author of
2953
the change you can specify the option multiple times, once for each
2958
A common mistake is to forget to add a new file or directory before
2959
running the commit command. The --strict option checks for unknown
2960
files and aborts the commit if any are found. More advanced pre-commit
2961
checks can be implemented by defining hooks. See ``bzr help hooks``
2966
If you accidentially commit the wrong changes or make a spelling
2967
mistake in the commit message say, you can use the uncommit command
2968
to undo it. See ``bzr help uncommit`` for details.
2970
Hooks can also be configured to run after a commit. This allows you
2971
to trigger updates to external systems like bug trackers. The --fixes
2972
option can be used to record the association between a revision and
2973
one or more bugs. See ``bzr help bugs`` for details.
2975
A selective commit may fail in some cases where the committed
2976
tree would be invalid. Consider::
2981
bzr commit foo -m "committing foo"
2982
bzr mv foo/bar foo/baz
2985
bzr commit foo/bar -m "committing bar but not baz"
2987
In the example above, the last commit will fail by design. This gives
2988
the user the opportunity to decide whether they want to commit the
2989
rename at the same time, separately first, or not at all. (As a general
2990
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2166
2992
# TODO: Run hooks on tree to-be-committed, and after commit.
2527
3533
short_name='x',
2528
3534
help='Exclude tests that match this regular'
2529
3535
' expression.'),
3537
help='Output test progress via subunit.'),
2530
3538
Option('strict', help='Fail on missing dependencies or '
2531
3539
'known failures.'),
3540
Option('load-list', type=str, argname='TESTLISTFILE',
3541
help='Load a test id list from a text file.'),
3542
ListOption('debugflag', type=str, short_name='E',
3543
help='Turn on a selftest debug flag.'),
3544
ListOption('starting-with', type=str, argname='TESTID',
3545
param_name='starting_with', short_name='s',
3547
'Load only the tests starting with TESTID.'),
2533
3549
encoding_type = 'replace'
2535
def run(self, testspecs_list=None, verbose=None, one=False,
3552
Command.__init__(self)
3553
self.additional_selftest_args = {}
3555
def run(self, testspecs_list=None, verbose=False, one=False,
2536
3556
transport=None, benchmark=None,
2537
3557
lsprof_timed=None, cache_dir=None,
2538
3558
first=False, list_only=False,
2539
randomize=None, exclude=None, strict=False):
3559
randomize=None, exclude=None, strict=False,
3560
load_list=None, debugflag=None, starting_with=None, subunit=False,
3561
parallel=None, lsprof_tests=False):
2541
3562
from bzrlib.tests import selftest
2542
3563
import bzrlib.benchmarks as benchmarks
2543
3564
from bzrlib.benchmarks import tree_creator
2544
from bzrlib.version import show_version
3566
# Make deprecation warnings visible, unless -Werror is set
3567
symbol_versioning.activate_deprecation_warnings(override=False)
2546
3569
if cache_dir is not None:
2547
3570
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
3571
if testspecs_list is not None:
2557
3572
pattern = '|'.join(testspecs_list)
3577
from bzrlib.tests import SubUnitBzrRunner
3579
raise errors.BzrCommandError("subunit not available. subunit "
3580
"needs to be installed to use --subunit.")
3581
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3582
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3583
# stdout, which would corrupt the subunit stream.
3584
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3585
# following code can be deleted when it's sufficiently deployed
3586
# -- vila/mgz 20100514
3587
if (sys.platform == "win32"
3588
and getattr(sys.stdout, 'fileno', None) is not None):
3590
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3592
self.additional_selftest_args.setdefault(
3593
'suite_decorators', []).append(parallel)
2561
3595
test_suite_factory = benchmarks.test_suite
3596
# Unless user explicitly asks for quiet, be verbose in benchmarks
3597
verbose = not is_quiet()
2564
3598
# TODO: should possibly lock the history file...
2565
3599
benchfile = open(".perf_history", "at", buffering=1)
3600
self.add_cleanup(benchfile.close)
2567
3602
test_suite_factory = None
2570
3603
benchfile = None
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,
2586
if benchfile is not None:
2589
info('tests passed')
2591
info('tests failed')
3604
selftest_kwargs = {"verbose": verbose,
3606
"stop_on_failure": one,
3607
"transport": transport,
3608
"test_suite_factory": test_suite_factory,
3609
"lsprof_timed": lsprof_timed,
3610
"lsprof_tests": lsprof_tests,
3611
"bench_history": benchfile,
3612
"matching_tests_first": first,
3613
"list_only": list_only,
3614
"random_seed": randomize,
3615
"exclude_pattern": exclude,
3617
"load_list": load_list,
3618
"debug_flags": debugflag,
3619
"starting_with": starting_with
3621
selftest_kwargs.update(self.additional_selftest_args)
3622
result = selftest(**selftest_kwargs)
2592
3623
return int(not result)
2595
3626
class cmd_version(Command):
2596
"""Show version of bzr."""
3627
__doc__ = """Show version of bzr."""
3629
encoding_type = 'replace'
3631
Option("short", help="Print just the version number."),
2598
3634
@display_command
3635
def run(self, short=False):
2600
3636
from bzrlib.version import show_version
3638
self.outf.write(bzrlib.version_string + '\n')
3640
show_version(to_file=self.outf)
2604
3643
class cmd_rocks(Command):
2605
"""Statement of optimism."""
3644
__doc__ = """Statement of optimism."""
2609
3648
@display_command
2611
print "It sure does!"
3650
self.outf.write("It sure does!\n")
2614
3653
class cmd_find_merge_base(Command):
2615
"""Find and print a base revision for merging two branches."""
3654
__doc__ = """Find and print a base revision for merging two branches."""
2616
3655
# TODO: Options to specify revisions on either side, as if
2617
3656
# merging only part of the history.
2618
3657
takes_args = ['branch', 'other']
2621
3660
@display_command
2622
3661
def run(self, branch, other):
2623
from bzrlib.revision import ensure_null, MultipleRevisionSources
3662
from bzrlib.revision import ensure_null
2625
3664
branch1 = Branch.open_containing(branch)[0]
2626
3665
branch2 = Branch.open_containing(other)[0]
3666
self.add_cleanup(branch1.lock_read().unlock)
3667
self.add_cleanup(branch2.lock_read().unlock)
2628
3668
last1 = ensure_null(branch1.last_revision())
2629
3669
last2 = ensure_null(branch2.last_revision())
2631
3671
graph = branch1.repository.get_graph(branch2.repository)
2632
3672
base_rev_id = graph.find_unique_lca(last1, last2)
2634
print 'merge base is revision %s' % base_rev_id
3674
self.outf.write('merge base is revision %s\n' % base_rev_id)
2637
3677
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
3678
__doc__ = """Perform a three-way merge.
3680
The source of the merge can be specified either in the form of a branch,
3681
or in the form of a path to a file containing a merge directive generated
3682
with bzr send. If neither is specified, the default is the upstream branch
3683
or the branch most recently merged using --remember.
3685
When merging a branch, by default the tip will be merged. To pick a different
3686
revision, pass --revision. If you specify two values, the first will be used as
3687
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3688
available revisions, like this is commonly referred to as "cherrypicking".
3690
Revision numbers are always relative to the branch being merged.
2646
3692
By default, bzr will try to merge in all new work from the other
2647
3693
branch, automatically determining an appropriate base. If this
2648
3694
fails, you may need to give an explicit base.
2650
3696
Merge will do its best to combine the changes in two branches, but there
2651
3697
are some kinds of problems only a human can fix. When it encounters those,
2652
3698
it will mark a conflict. A conflict means that you need to fix something,
2724
3789
allow_pending = True
2725
3790
verified = 'inapplicable'
2726
3791
tree = WorkingTree.open_containing(directory)[0]
3794
basis_tree = tree.revision_tree(tree.last_revision())
3795
except errors.NoSuchRevision:
3796
basis_tree = tree.basis_tree()
3798
# die as quickly as possible if there are uncommitted changes
3800
if tree.has_changes():
3801
raise errors.UncommittedChanges(tree)
3803
view_info = _get_view_info_for_change_reporter(tree)
2727
3804
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:
3805
unversioned_filter=tree.is_ignored, view_info=view_info)
3806
pb = ui.ui_factory.nested_progress_bar()
3807
self.add_cleanup(pb.finished)
3808
self.add_cleanup(tree.lock_write().unlock)
3809
if location is not None:
3811
mergeable = bundle.read_mergeable_from_url(location,
3812
possible_transports=possible_transports)
3813
except errors.NotABundle:
3817
raise errors.BzrCommandError('Cannot use --uncommitted'
3818
' with bundles or merge directives.')
3820
if revision is not None:
3821
raise errors.BzrCommandError(
3822
'Cannot use -r with merge directives or bundles')
3823
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3826
if merger is None and uncommitted:
3827
if revision is not None and len(revision) > 0:
3828
raise errors.BzrCommandError('Cannot use --uncommitted and'
3829
' --revision at the same time.')
3830
merger = self.get_merger_from_uncommitted(tree, location, None)
3831
allow_pending = False
3834
merger, allow_pending = self._get_merger_from_branch(tree,
3835
location, revision, remember, possible_transports, None)
3837
merger.merge_type = merge_type
3838
merger.reprocess = reprocess
3839
merger.show_base = show_base
3840
self.sanity_check_merger(merger)
3841
if (merger.base_rev_id == merger.other_rev_id and
3842
merger.other_rev_id is not None):
3843
note('Nothing to do.')
3846
if merger.interesting_files is not None:
3847
raise errors.BzrCommandError('Cannot pull individual files')
3848
if (merger.base_rev_id == tree.last_revision()):
3849
result = tree.pull(merger.other_branch, False,
3850
merger.other_rev_id)
3851
result.report(self.outf)
3853
if merger.this_basis is None:
3854
raise errors.BzrCommandError(
3855
"This branch has no commits."
3856
" (perhaps you would prefer 'bzr pull')")
3858
return self._do_preview(merger)
3860
return self._do_interactive(merger)
3862
return self._do_merge(merger, change_reporter, allow_pending,
3865
def _get_preview(self, merger):
3866
tree_merger = merger.make_merger()
3867
tt = tree_merger.make_preview_transform()
3868
self.add_cleanup(tt.finalize)
3869
result_tree = tt.get_preview_tree()
3872
def _do_preview(self, merger):
3873
from bzrlib.diff import show_diff_trees
3874
result_tree = self._get_preview(merger)
3875
path_encoding = osutils.get_diff_header_encoding()
3876
show_diff_trees(merger.this_tree, result_tree, self.outf,
3877
old_label='', new_label='',
3878
path_encoding=path_encoding)
3880
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3881
merger.change_reporter = change_reporter
3882
conflict_count = merger.do_merge()
3884
merger.set_pending()
3885
if verified == 'failed':
3886
warning('Preview patch does not match changes')
3887
if conflict_count != 0:
3892
def _do_interactive(self, merger):
3893
"""Perform an interactive merge.
3895
This works by generating a preview tree of the merge, then using
3896
Shelver to selectively remove the differences between the working tree
3897
and the preview tree.
3899
from bzrlib import shelf_ui
3900
result_tree = self._get_preview(merger)
3901
writer = bzrlib.option.diff_writer_registry.get()
3902
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3903
reporter=shelf_ui.ApplyReporter(),
3904
diff_writer=writer(sys.stdout))
2791
for cleanup in reversed(cleanups):
2794
3910
def sanity_check_merger(self, merger):
2795
3911
if (merger.show_base and
2796
3912
not merger.merge_type is _mod_merge.Merge3Merger):
2797
3913
raise errors.BzrCommandError("Show-base is not supported for this"
2798
3914
" merge type. %s" % merger.merge_type)
3915
if merger.reprocess is None:
3916
if merger.show_base:
3917
merger.reprocess = False
3919
# Use reprocess if the merger supports it
3920
merger.reprocess = merger.merge_type.supports_reprocess
2799
3921
if merger.reprocess and not merger.merge_type.supports_reprocess:
2800
3922
raise errors.BzrCommandError("Conflict reduction is not supported"
2801
3923
" for merge type %s." %
3156
4339
" or specified.")
3157
4340
display_url = urlutils.unescape_for_display(parent,
3158
4341
self.outf.encoding)
3159
self.outf.write("Using last location: " + display_url + "\n")
4342
message("Using saved parent location: "
4343
+ display_url + "\n")
3161
4345
remote_branch = Branch.open(other_branch)
3162
4346
if remote_branch.base == local_branch.base:
3163
4347
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()
4349
self.add_cleanup(remote_branch.lock_read().unlock)
4351
local_revid_range = _revision_range_to_revid_range(
4352
_get_revision_range(my_revision, local_branch,
4355
remote_revid_range = _revision_range_to_revid_range(
4356
_get_revision_range(revision,
4357
remote_branch, self.name()))
4359
local_extra, remote_extra = find_unmerged(
4360
local_branch, remote_branch, restrict,
4361
backward=not reverse,
4362
include_merges=include_merges,
4363
local_revid_range=local_revid_range,
4364
remote_revid_range=remote_revid_range)
4366
if log_format is None:
4367
registry = log.log_formatter_registry
4368
log_format = registry.get_default(local_branch)
4369
lf = log_format(to_file=self.outf,
4371
show_timezone='original')
4374
if local_extra and not theirs_only:
4375
message("You have %d extra revision(s):\n" %
4377
for revision in iter_log_revisions(local_extra,
4378
local_branch.repository,
4380
lf.log_revision(revision)
4381
printed_local = True
4384
printed_local = False
4386
if remote_extra and not mine_only:
4387
if printed_local is True:
4389
message("You are missing %d revision(s):\n" %
4391
for revision in iter_log_revisions(remote_extra,
4392
remote_branch.repository,
4394
lf.log_revision(revision)
4397
if mine_only and not local_extra:
4398
# We checked local, and found nothing extra
4399
message('This branch is up to date.\n')
4400
elif theirs_only and not remote_extra:
4401
# We checked remote, and found nothing extra
4402
message('Other branch is up to date.\n')
4403
elif not (mine_only or theirs_only or local_extra or
4405
# We checked both branches, and neither one had extra
4407
message("Branches are up to date.\n")
3207
4409
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()
4410
self.add_cleanup(local_branch.lock_write().unlock)
4411
# handle race conditions - a parent might be set while we run.
4412
if local_branch.get_parent() is None:
4413
local_branch.set_parent(remote_branch.base)
3215
4414
return status_code
3218
4417
class cmd_pack(Command):
3219
"""Compress the data within a repository."""
4418
__doc__ = """Compress the data within a repository.
4420
This operation compresses the data within a bazaar repository. As
4421
bazaar supports automatic packing of repository, this operation is
4422
normally not required to be done manually.
4424
During the pack operation, bazaar takes a backup of existing repository
4425
data, i.e. pack files. This backup is eventually removed by bazaar
4426
automatically when it is safe to do so. To save disk space by removing
4427
the backed up pack files, the --clean-obsolete-packs option may be
4430
Warning: If you use --clean-obsolete-packs and your machine crashes
4431
during or immediately after repacking, you may be left with a state
4432
where the deletion has been written to disk but the new packs have not
4433
been. In this case the repository may be unusable.
3221
4436
_see_also = ['repositories']
3222
4437
takes_args = ['branch_or_repo?']
4439
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
3224
def run(self, branch_or_repo='.'):
4442
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3225
4443
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3227
4445
branch = dir.open_branch()
3228
4446
repository = branch.repository
3229
4447
except errors.NotBranchError:
3230
4448
repository = dir.open_repository()
4449
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
3234
4452
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.
4453
__doc__ = """List the installed plugins.
4455
This command displays the list of installed plugins including
4456
version of plugin and a short description of each.
4458
--verbose shows the path where each plugin is located.
3240
4460
A plugin is an external component for Bazaar that extends the
3241
4461
revision control system, by adding or replacing code in Bazaar.
3860
5170
'rather than the one containing the working directory.',
3861
5171
short_name='f',
3863
Option('output', short_name='o', help='Write directive to this file.',
5173
Option('output', short_name='o',
5174
help='Write merge directive to this file or directory; '
5175
'use - for stdout.',
5178
help='Refuse to send if there are uncommitted changes in'
5179
' the working tree, --no-strict disables the check.'),
3865
5180
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',})
5184
Option('body', help='Body for the email.', type=unicode),
5185
RegistryOption('format',
5186
help='Use the specified output format.',
5187
lazy_registry=('bzrlib.send', 'format_registry')),
3875
5190
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
3876
5191
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,
5192
format=None, mail_to=None, message=None, body=None,
5193
strict=None, **kwargs):
5194
from bzrlib.send import send
5195
return send(submit_branch, revision, public_branch, remember,
5196
format, no_bundle, no_patch, output,
5197
kwargs.get('from', '.'), mail_to, message, body,
3982
5202
class cmd_bundle_revisions(cmd_send):
3984
"""Create a merge-directive for submiting changes.
5203
__doc__ = """Create a merge-directive for submitting changes.
3986
5205
A merge directive provides many things needed for requesting merges:
4059
5282
Tags are stored in the branch. Tags are copied from one branch to another
4060
5283
along when you branch, push, pull or merge.
4062
It is an error to give a tag name that already exists unless you pass
5285
It is an error to give a tag name that already exists unless you pass
4063
5286
--force, in which case the tag is moved to point to the new revision.
5288
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5289
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5291
If no tag name is specified it will be determined through the
5292
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5293
upstream releases by reading configure.ac. See ``bzr help hooks`` for
4066
5297
_see_also = ['commit', 'tags']
4067
takes_args = ['tag_name']
5298
takes_args = ['tag_name?']
4068
5299
takes_options = [
4069
5300
Option('delete',
4070
5301
help='Delete this tag rather than placing it.',
4073
help='Branch in which to place the tag.',
5303
custom_help('directory',
5304
help='Branch in which to place the tag.'),
4077
5305
Option('force',
4078
5306
help='Replace existing tags.',
4083
def run(self, tag_name,
5311
def run(self, tag_name=None,
4089
5317
branch, relpath = Branch.open_containing(directory)
4093
branch.tags.delete_tag(tag_name)
4094
self.outf.write('Deleted tag %s.\n' % tag_name)
5318
self.add_cleanup(branch.lock_write().unlock)
5320
if tag_name is None:
5321
raise errors.BzrCommandError("No tag specified to delete.")
5322
branch.tags.delete_tag(tag_name)
5323
self.outf.write('Deleted tag %s.\n' % tag_name)
5326
if len(revision) != 1:
5327
raise errors.BzrCommandError(
5328
"Tags can only be placed on a single revision, "
5330
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)
5332
revision_id = branch.last_revision()
5333
if tag_name is None:
5334
tag_name = branch.automatic_tag_name(revision_id)
5335
if tag_name is None:
5336
raise errors.BzrCommandError(
5337
"Please specify a tag name.")
5338
if (not force) and branch.tags.has_tag(tag_name):
5339
raise errors.TagAlreadyExists(tag_name)
5340
branch.tags.set_tag(tag_name, revision_id)
5341
self.outf.write('Created tag %s.\n' % tag_name)
4112
5344
class cmd_tags(Command):
5345
__doc__ = """List tags.
4115
This tag shows a table of tag names and the revisions they reference.
5347
This command shows a table of tag names and the revisions they reference.
4118
5350
_see_also = ['tag']
4119
5351
takes_options = [
4121
help='Branch whose tags should be displayed.',
5352
custom_help('directory',
5353
help='Branch whose tags should be displayed.'),
5354
RegistryOption.from_kwargs('sort',
5355
'Sort tags by different criteria.', title='Sorting',
5356
alpha='Sort tags lexicographically (default).',
5357
time='Sort tags chronologically.',
4127
5363
@display_command
4131
5370
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
5372
tags = branch.tags.get_tag_dict().items()
5376
self.add_cleanup(branch.lock_read().unlock)
5378
graph = branch.repository.get_graph()
5379
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5380
revid1, revid2 = rev1.rev_id, rev2.rev_id
5381
# only show revisions between revid1 and revid2 (inclusive)
5382
tags = [(tag, revid) for tag, revid in tags if
5383
graph.is_between(revid, revid1, revid2)]
5386
elif sort == 'time':
5388
for tag, revid in tags:
5390
revobj = branch.repository.get_revision(revid)
5391
except errors.NoSuchRevision:
5392
timestamp = sys.maxint # place them at the end
5394
timestamp = revobj.timestamp
5395
timestamps[revid] = timestamp
5396
tags.sort(key=lambda x: timestamps[x[1]])
5398
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5399
for index, (tag, revid) in enumerate(tags):
5401
revno = branch.revision_id_to_dotted_revno(revid)
5402
if isinstance(revno, tuple):
5403
revno = '.'.join(map(str, revno))
5404
except errors.NoSuchRevision:
5405
# Bad tag data/merges can lead to tagged revisions
5406
# which are not in this branch. Fail gracefully ...
5408
tags[index] = (tag, revno)
5410
for tag, revspec in tags:
5411
self.outf.write('%-20s %s\n' % (tag, revspec))
5414
class cmd_reconfigure(Command):
5415
__doc__ = """Reconfigure the type of a bzr directory.
5417
A target configuration must be specified.
5419
For checkouts, the bind-to location will be auto-detected if not specified.
5420
The order of preference is
5421
1. For a lightweight checkout, the current bound location.
5422
2. For branches that used to be checkouts, the previously-bound location.
5423
3. The push location.
5424
4. The parent location.
5425
If none of these is available, --bind-to must be specified.
5428
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5429
takes_args = ['location?']
5431
RegistryOption.from_kwargs(
5433
title='Target type',
5434
help='The type to reconfigure the directory to.',
5435
value_switches=True, enum_switch=False,
5436
branch='Reconfigure to be an unbound branch with no working tree.',
5437
tree='Reconfigure to be an unbound branch with a working tree.',
5438
checkout='Reconfigure to be a bound branch with a working tree.',
5439
lightweight_checkout='Reconfigure to be a lightweight'
5440
' checkout (with no local history).',
5441
standalone='Reconfigure to be a standalone branch '
5442
'(i.e. stop using shared repository).',
5443
use_shared='Reconfigure to use a shared repository.',
5444
with_trees='Reconfigure repository to create '
5445
'working trees on branches by default.',
5446
with_no_trees='Reconfigure repository to not create '
5447
'working trees on branches by default.'
5449
Option('bind-to', help='Branch to bind checkout to.', type=str),
5451
help='Perform reconfiguration even if local changes'
5453
Option('stacked-on',
5454
help='Reconfigure a branch to be stacked on another branch.',
5458
help='Reconfigure a branch to be unstacked. This '
5459
'may require copying substantial data into it.',
5463
def run(self, location=None, target_type=None, bind_to=None, force=False,
5466
directory = bzrdir.BzrDir.open(location)
5467
if stacked_on and unstacked:
5468
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5469
elif stacked_on is not None:
5470
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5472
reconfigure.ReconfigureUnstacked().apply(directory)
5473
# At the moment you can use --stacked-on and a different
5474
# reconfiguration shape at the same time; there seems no good reason
5476
if target_type is None:
5477
if stacked_on or unstacked:
5480
raise errors.BzrCommandError('No target configuration '
5482
elif target_type == 'branch':
5483
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5484
elif target_type == 'tree':
5485
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5486
elif target_type == 'checkout':
5487
reconfiguration = reconfigure.Reconfigure.to_checkout(
5489
elif target_type == 'lightweight-checkout':
5490
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5492
elif target_type == 'use-shared':
5493
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5494
elif target_type == 'standalone':
5495
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5496
elif target_type == 'with-trees':
5497
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5499
elif target_type == 'with-no-trees':
5500
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5502
reconfiguration.apply(force)
5505
class cmd_switch(Command):
5506
__doc__ = """Set the branch of a checkout and update.
5508
For lightweight checkouts, this changes the branch being referenced.
5509
For heavyweight checkouts, this checks that there are no local commits
5510
versus the current bound branch, then it makes the local branch a mirror
5511
of the new location and binds to it.
5513
In both cases, the working tree is updated and uncommitted changes
5514
are merged. The user can commit or revert these as they desire.
5516
Pending merges need to be committed or reverted before using switch.
5518
The path to the branch to switch to can be specified relative to the parent
5519
directory of the current branch. For example, if you are currently in a
5520
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5523
Bound branches use the nickname of its master branch unless it is set
5524
locally, in which case switching will update the local nickname to be
5528
takes_args = ['to_location?']
5529
takes_options = ['directory',
5531
help='Switch even if local commits will be lost.'),
5533
Option('create-branch', short_name='b',
5534
help='Create the target branch from this one before'
5535
' switching to it.'),
5538
def run(self, to_location=None, force=False, create_branch=False,
5539
revision=None, directory=u'.'):
5540
from bzrlib import switch
5541
tree_location = directory
5542
revision = _get_one_revision('switch', revision)
5543
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5544
if to_location is None:
5545
if revision is None:
5546
raise errors.BzrCommandError('You must supply either a'
5547
' revision or a location')
5548
to_location = tree_location
5550
branch = control_dir.open_branch()
5551
had_explicit_nick = branch.get_config().has_explicit_nickname()
5552
except errors.NotBranchError:
5554
had_explicit_nick = False
5557
raise errors.BzrCommandError('cannot create branch without'
5559
to_location = directory_service.directories.dereference(
5561
if '/' not in to_location and '\\' not in to_location:
5562
# This path is meant to be relative to the existing branch
5563
this_url = self._get_branch_location(control_dir)
5564
to_location = urlutils.join(this_url, '..', to_location)
5565
to_branch = branch.bzrdir.sprout(to_location,
5566
possible_transports=[branch.bzrdir.root_transport],
5567
source_branch=branch).open_branch()
5570
to_branch = Branch.open(to_location)
5571
except errors.NotBranchError:
5572
this_url = self._get_branch_location(control_dir)
5573
to_branch = Branch.open(
5574
urlutils.join(this_url, '..', to_location))
5575
if revision is not None:
5576
revision = revision.as_revision_id(to_branch)
5577
switch.switch(control_dir, to_branch, force, revision_id=revision)
5578
if had_explicit_nick:
5579
branch = control_dir.open_branch() #get the new branch!
5580
branch.nick = to_branch.nick
5581
note('Switched to branch: %s',
5582
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5584
def _get_branch_location(self, control_dir):
5585
"""Return location of branch for this control dir."""
5587
this_branch = control_dir.open_branch()
5588
# This may be a heavy checkout, where we want the master branch
5589
master_location = this_branch.get_bound_location()
5590
if master_location is not None:
5591
return master_location
5592
# If not, use a local sibling
5593
return this_branch.base
5594
except errors.NotBranchError:
5595
format = control_dir.find_branch_format()
5596
if getattr(format, 'get_reference', None) is not None:
5597
return format.get_reference(control_dir)
5599
return control_dir.root_transport.base
5602
class cmd_view(Command):
5603
__doc__ = """Manage filtered views.
5605
Views provide a mask over the tree so that users can focus on
5606
a subset of a tree when doing their work. After creating a view,
5607
commands that support a list of files - status, diff, commit, etc -
5608
effectively have that list of files implicitly given each time.
5609
An explicit list of files can still be given but those files
5610
must be within the current view.
5612
In most cases, a view has a short life-span: it is created to make
5613
a selected change and is deleted once that change is committed.
5614
At other times, you may wish to create one or more named views
5615
and switch between them.
5617
To disable the current view without deleting it, you can switch to
5618
the pseudo view called ``off``. This can be useful when you need
5619
to see the whole tree for an operation or two (e.g. merge) but
5620
want to switch back to your view after that.
5623
To define the current view::
5625
bzr view file1 dir1 ...
5627
To list the current view::
5631
To delete the current view::
5635
To disable the current view without deleting it::
5637
bzr view --switch off
5639
To define a named view and switch to it::
5641
bzr view --name view-name file1 dir1 ...
5643
To list a named view::
5645
bzr view --name view-name
5647
To delete a named view::
5649
bzr view --name view-name --delete
5651
To switch to a named view::
5653
bzr view --switch view-name
5655
To list all views defined::
5659
To delete all views::
5661
bzr view --delete --all
5665
takes_args = ['file*']
5668
help='Apply list or delete action to all views.',
5671
help='Delete the view.',
5674
help='Name of the view to define, list or delete.',
5678
help='Name of the view to switch to.',
5683
def run(self, file_list,
5689
tree, file_list = WorkingTree.open_containing_paths(file_list,
5691
current_view, view_dict = tree.views.get_view_info()
5696
raise errors.BzrCommandError(
5697
"Both --delete and a file list specified")
5699
raise errors.BzrCommandError(
5700
"Both --delete and --switch specified")
5702
tree.views.set_view_info(None, {})
5703
self.outf.write("Deleted all views.\n")
5705
raise errors.BzrCommandError("No current view to delete")
5707
tree.views.delete_view(name)
5708
self.outf.write("Deleted '%s' view.\n" % name)
5711
raise errors.BzrCommandError(
5712
"Both --switch and a file list specified")
5714
raise errors.BzrCommandError(
5715
"Both --switch and --all specified")
5716
elif switch == 'off':
5717
if current_view is None:
5718
raise errors.BzrCommandError("No current view to disable")
5719
tree.views.set_view_info(None, view_dict)
5720
self.outf.write("Disabled '%s' view.\n" % (current_view))
5722
tree.views.set_view_info(switch, view_dict)
5723
view_str = views.view_display_str(tree.views.lookup_view())
5724
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5727
self.outf.write('Views defined:\n')
5728
for view in sorted(view_dict):
5729
if view == current_view:
5733
view_str = views.view_display_str(view_dict[view])
5734
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5736
self.outf.write('No views defined.\n')
5739
# No name given and no current view set
5742
raise errors.BzrCommandError(
5743
"Cannot change the 'off' pseudo view")
5744
tree.views.set_view(name, sorted(file_list))
5745
view_str = views.view_display_str(tree.views.lookup_view())
5746
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5750
# No name given and no current view set
5751
self.outf.write('No current view.\n')
5753
view_str = views.view_display_str(tree.views.lookup_view(name))
5754
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5757
class cmd_hooks(Command):
5758
__doc__ = """Show hooks."""
5763
for hook_key in sorted(hooks.known_hooks.keys()):
5764
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5765
self.outf.write("%s:\n" % type(some_hooks).__name__)
5766
for hook_name, hook_point in sorted(some_hooks.items()):
5767
self.outf.write(" %s:\n" % (hook_name,))
5768
found_hooks = list(hook_point)
5770
for hook in found_hooks:
5771
self.outf.write(" %s\n" %
5772
(some_hooks.get_hook_name(hook),))
5774
self.outf.write(" <no hooks installed>\n")
5777
class cmd_remove_branch(Command):
5778
__doc__ = """Remove a branch.
5780
This will remove the branch from the specified location but
5781
will keep any working tree or repository in place.
5785
Remove the branch at repo/trunk::
5787
bzr remove-branch repo/trunk
5791
takes_args = ["location?"]
5793
aliases = ["rmbranch"]
5795
def run(self, location=None):
5796
if location is None:
5798
branch = Branch.open_containing(location)[0]
5799
branch.bzrdir.destroy_branch()
5802
class cmd_shelve(Command):
5803
__doc__ = """Temporarily set aside some changes from the current tree.
5805
Shelve allows you to temporarily put changes you've made "on the shelf",
5806
ie. out of the way, until a later time when you can bring them back from
5807
the shelf with the 'unshelve' command. The changes are stored alongside
5808
your working tree, and so they aren't propagated along with your branch nor
5809
will they survive its deletion.
5811
If shelve --list is specified, previously-shelved changes are listed.
5813
Shelve is intended to help separate several sets of changes that have
5814
been inappropriately mingled. If you just want to get rid of all changes
5815
and you don't need to restore them later, use revert. If you want to
5816
shelve all text changes at once, use shelve --all.
5818
If filenames are specified, only the changes to those files will be
5819
shelved. Other files will be left untouched.
5821
If a revision is specified, changes since that revision will be shelved.
5823
You can put multiple items on the shelf, and by default, 'unshelve' will
5824
restore the most recently shelved changes.
5827
takes_args = ['file*']
5832
Option('all', help='Shelve all changes.'),
5834
RegistryOption('writer', 'Method to use for writing diffs.',
5835
bzrlib.option.diff_writer_registry,
5836
value_switches=True, enum_switch=False),
5838
Option('list', help='List shelved changes.'),
5840
help='Destroy removed changes instead of shelving them.'),
5842
_see_also = ['unshelve']
5844
def run(self, revision=None, all=False, file_list=None, message=None,
5845
writer=None, list=False, destroy=False, directory=u'.'):
5847
return self.run_for_list()
5848
from bzrlib.shelf_ui import Shelver
5850
writer = bzrlib.option.diff_writer_registry.get()
5852
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5853
file_list, message, destroy=destroy, directory=directory)
5858
except errors.UserAbort:
5861
def run_for_list(self):
5862
tree = WorkingTree.open_containing('.')[0]
5863
self.add_cleanup(tree.lock_read().unlock)
5864
manager = tree.get_shelf_manager()
5865
shelves = manager.active_shelves()
5866
if len(shelves) == 0:
5867
note('No shelved changes.')
5869
for shelf_id in reversed(shelves):
5870
message = manager.get_metadata(shelf_id).get('message')
5872
message = '<no message>'
5873
self.outf.write('%3d: %s\n' % (shelf_id, message))
5877
class cmd_unshelve(Command):
5878
__doc__ = """Restore shelved changes.
5880
By default, the most recently shelved changes are restored. However if you
5881
specify a shelf by id those changes will be restored instead. This works
5882
best when the changes don't depend on each other.
5885
takes_args = ['shelf_id?']
5888
RegistryOption.from_kwargs(
5889
'action', help="The action to perform.",
5890
enum_switch=False, value_switches=True,
5891
apply="Apply changes and remove from the shelf.",
5892
dry_run="Show changes, but do not apply or remove them.",
5893
preview="Instead of unshelving the changes, show the diff that "
5894
"would result from unshelving.",
5895
delete_only="Delete changes without applying them.",
5896
keep="Apply changes but don't delete them.",
5899
_see_also = ['shelve']
5901
def run(self, shelf_id=None, action='apply', directory=u'.'):
5902
from bzrlib.shelf_ui import Unshelver
5903
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5907
unshelver.tree.unlock()
5910
class cmd_clean_tree(Command):
5911
__doc__ = """Remove unwanted files from working tree.
5913
By default, only unknown files, not ignored files, are deleted. Versioned
5914
files are never deleted.
5916
Another class is 'detritus', which includes files emitted by bzr during
5917
normal operations and selftests. (The value of these files decreases with
5920
If no options are specified, unknown files are deleted. Otherwise, option
5921
flags are respected, and may be combined.
5923
To check what clean-tree will do, use --dry-run.
5925
takes_options = ['directory',
5926
Option('ignored', help='Delete all ignored files.'),
5927
Option('detritus', help='Delete conflict files, merge'
5928
' backups, and failed selftest dirs.'),
5930
help='Delete files unknown to bzr (default).'),
5931
Option('dry-run', help='Show files to delete instead of'
5933
Option('force', help='Do not prompt before deleting.')]
5934
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5935
force=False, directory=u'.'):
5936
from bzrlib.clean_tree import clean_tree
5937
if not (unknown or ignored or detritus):
5941
clean_tree(directory, unknown=unknown, ignored=ignored,
5942
detritus=detritus, dry_run=dry_run, no_prompt=force)
5945
class cmd_reference(Command):
5946
__doc__ = """list, view and set branch locations for nested trees.
5948
If no arguments are provided, lists the branch locations for nested trees.
5949
If one argument is provided, display the branch location for that tree.
5950
If two arguments are provided, set the branch location for that tree.
5955
takes_args = ['path?', 'location?']
5957
def run(self, path=None, location=None):
5959
if path is not None:
5961
tree, branch, relpath =(
5962
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
5963
if path is not None:
5966
tree = branch.basis_tree()
5968
info = branch._get_all_reference_info().iteritems()
5969
self._display_reference_info(tree, branch, info)
5971
file_id = tree.path2id(path)
5973
raise errors.NotVersionedError(path)
5974
if location is None:
5975
info = [(file_id, branch.get_reference_info(file_id))]
5976
self._display_reference_info(tree, branch, info)
5978
branch.set_reference_info(file_id, path, location)
5980
def _display_reference_info(self, tree, branch, info):
5982
for file_id, (path, location) in info:
5984
path = tree.id2path(file_id)
5985
except errors.NoSuchId:
5987
ref_list.append((path, location))
5988
for path, location in sorted(ref_list):
5989
self.outf.write('%s %s\n' % (path, location))
5992
def _register_lazy_builtins():
5993
# register lazy builtins from other modules; called at startup and should
5994
# be only called once.
5995
for (name, aliases, module_name) in [
5996
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
5997
('cmd_dpush', [], 'bzrlib.foreign'),
5998
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
5999
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6000
('cmd_conflicts', [], 'bzrlib.conflicts'),
6001
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6003
builtin_command_registry.register_lazy(name, aliases, module_name)